Namespace Lucene.Net.Analysis
API and code to convert text into indexable/searchable tokens. Covers Analyzer and related classes.
Parsing? Tokenization? Analysis!
Lucene.NET, an indexing and search library, accepts only plain text input.
Parsing
Applications that build their search capabilities upon Lucene.NET may support documents in various formats – HTML, XML, PDF, Word – just to name a few. Lucene.NET does not care about the Parsing of these and other document formats, and it is the responsibility of the application using Lucene.NET to use an appropriate Parser to convert the original format into plain text before passing that plain text to Lucene.NET.
Tokenization
Plain text passed to Lucene.NET for indexing goes through a process generally called tokenization. Tokenization is the process of breaking input text into small indexing elements – tokens. The way input text is broken into tokens heavily influences how people will then be able to search for that text. For instance, sentences beginnings and endings can be identified to provide for more accurate phrase and proximity searches (though sentence identification is not provided by Lucene.NET).
In some cases simply breaking the input text into tokens is not enough – a deeper Analysis may be needed. Lucene includes both pre- and post-tokenization analysis facilities.
Pre-tokenization analysis can include (but is not limited to) stripping HTML markup, and transforming or removing text matching arbitrary patterns or sets of fixed strings.
There are many post-tokenization steps that can be done, including (but not limited to):
Stemming – Replacing words with their stems. For instance with English stemming "bikes" is replaced with "bike"; now query "bike" can find both documents containing "bike" and those containing "bikes".
Stop Words Filtering – Common words like "the", "and" and "a" rarely add any value to a search. Removing them shrinks the index size and increases performance. It may also reduce some "noise" and actually improve search quality.
Text Normalization – Stripping accents and other character markings can make for better searching.
Synonym Expansion – Adding in synonyms at the same token position as the current word can mean better matching when users search with words in the synonym set.
Core Analysis
The analysis package provides the mechanism to convert Strings and TextReaders into tokens that can be indexed by Lucene.NET. There are four main classes in the package from which all analysis processes are derived. These are:
Analyzer – An Analyzer is responsible for building a TokenStream which can be consumed by the indexing and searching processes. See below for more information on implementing your own Analyzer.
CharFilter – CharFilter extends System.Text.TextReader to perform pre-tokenization substitutions, deletions, and/or insertions on an input TextReader's text, while providing corrected character offsets to account for these modifications. This capability allows highlighting to function over the original text when indexed tokens are created from CharFilter-modified text with offsets that are not the same as those in the original text. Tokenizers' constructors and Reset() methods accept a CharFilter. CharFilters may be chained to perform multiple pre-tokenization modifications.
Tokenizer – A Tokenizer is a TokenStream and is responsible for breaking up incoming text into tokens. In most cases, an Analyzer will use a Tokenizer as the first step in the analysis process. However, to modify text prior to tokenization, use a CharStream subclass (see above).
TokenFilter – A TokenFilter is also a TokenStream and is responsible for modifying tokens that have been created by the Tokenizer. Common modifications performed by a TokenFilter are: deletion, stemming, synonym injection, and down casing. Not all Analyzers require TokenFilters.
Hints, Tips and Traps
The synergy between Analyzer and Tokenizer is sometimes confusing. To ease this confusion, some clarifications:
The Analyzer is responsible for the entire task of creating tokens out of the input text, while the Tokenizer is only responsible for breaking the input text into tokens. Very likely, tokens created by the Tokenizer would be modified or even omitted by the Analyzer (via one or more TokenFilters) before being returned.
Tokenizer is a TokenStream, but Analyzer is not.
Lucene.NET provides a number of analysis capabilities, the most commonly used one being the StandardAnalyzer. Many applications will have a long and industrious life with nothing more than the StandardAnalyzer. However, there are a few other classes/packages that are worth mentioning:
PerFieldAnalyzerWrapper – Most Analyzers perform the same operation on all Fields. The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different Fields.
The analysis library located at the root of the Lucene distribution has a number of different Analyzer implementations to solve a variety of different problems related to searching. Many of the Analyzers are designed to analyze non-English languages.
There are a variety of Tokenizer and TokenFilter implementations in this package. Take a look around, chances are someone has implemented what you need.
Analysis is one of the main causes of performance degradation during indexing. Simply put, the more you analyze the slower the indexing (in most cases). Perhaps your application would be just fine using the simple WhitespaceTokenizer combined with a StopFilter. The benchmark/ library can be useful for testing out the speed of the analysis process.
Invoking the Analyzer
Applications usually do not invoke analysis – Lucene.NET does it for them:
At indexing, as a consequence of AddDocument(), the Analyzer in effect for indexing is invoked for each indexed field of the added document.
At search, a QueryParser may invoke the Analyzer during parsing. Note that for some queries, analysis does not take place, e.g. wildcard queries.
However an application might invoke Analysis of any text for testing or for any other purpose, something like:
LuceneVersion matchVersion = LuceneVersion.LUCENE_XY; // Substitute desired Lucene version for XY
Analyzer analyzer = new StandardAnalyzer(matchVersion); // or any other analyzer
TokenStream ts = analyzer.GetTokenStream("myfield", new StringReader("some text goes here"));
IOffsetAttribute offsetAtt = ts.AddAttribute<IOffsetAttribute>();
try
{
ts.Reset(); // Resets this stream to the beginning. (Required)
while (ts.IncrementToken())
{
// Use [ReflectAsString(bool)](xref:Lucene.Net.Util.AttributeSource#Lucene_Net_Util_AttributeSource_ReflectAsString_System_Boolean_)
// for token stream debugging.
Console.WriteLine("token: " + ts.ReflectAsString(true));
Console.WriteLine("token start offset: " + offsetAtt.StartOffset);
Console.WriteLine(" token end offset: " + offsetAtt.EndOffset);
}
ts.End(); // Perform end-of-stream operations, e.g. set the final offset.
}
finally
{
ts.Dispose(); // Release resources associated with this stream.
}
Indexing Analysis vs. Search Analysis
Selecting the "correct" analyzer is crucial for search quality, and can also affect indexing and search performance. The "correct" analyzer differs between applications. Lucene java's wiki page AnalysisParalysis provides some data on "analyzing your analyzer". Here are some rules of thumb:
- Test test test... (did we say test?)
- Beware of over analysis – might hurt indexing performance.
- Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...
- In some cases a different analyzer is required for indexing and search, for instance:
- Certain searches require more stop words to be filtered. (I.e. more than those that were filtered at indexing.)
- Query expansion by synonyms, acronyms, auto spell correction, etc. This might sometimes require a modified analyzer – see the next section on how to do that.
Implementing your own Analyzer
Creating your own Analyzer is straightforward. Your Analyzer can wrap existing analysis components — CharFilter(s) (optional), a Tokenizer, and TokenFilter(s) (optional) — or components you create, or a combination of existing and newly created components. Before pursuing this approach, you may find it worthwhile to explore the Lucene.Net.Analysis.Common library and/or ask on the user@lucenenet.apache.org mailing list first to see if what you need already exists. If you are still committed to creating your own Analyzer, have a look at the source code of any one of the many samples located in this package.
The following sections discuss some aspects of implementing your own analyzer.
Field Section Boundaries
When Document.Add() is called multiple times for the same field name, we could say that each such call creates a new section for that field in that document. In fact, a separate call to GetTokenStream() would take place for each of these so called "sections". However, the default Analyzer behavior is to treat all these sections as one large section. This allows phrase search and proximity search to seamlessly cross boundaries between these "sections". In other words, if a certain field "f" is added like this:
document.Add(new Field("f","first ends",...);
document.Add(new Field("f","starts two",...);
indexWriter.AddDocument(document);
Then, a phrase search for "ends starts" would find that document. Where desired, this behavior can be modified by introducing a "position gap" between consecutive field "sections", by overriding Analyzer.GetPositionIncrementGap(string):
/// <summary>
/// Similar to <see cref="StandardAnalyzer"/>, but has a different position increment gap.
/// </summary>
public sealed class PositionIncrementGapAnalyzer : StopwordAnalyzerBase
{
public PositionIncrementGapAnalyzer(LuceneVersion matchVersion)
: base(matchVersion, StopAnalyzer.ENGLISH_STOP_WORDS_SET)
{
}
public int MaxTokenLength { get; set; } = 255;
/// <summary>
/// Returns a fixed position increment gap of 10.
/// </summary>
public override int GetPositionIncrementGap(string fieldName)
{
return 10;
}
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
// Same components as StandardAnalyzer
var src = new StandardTokenizer(m_matchVersion, reader);
src.MaxTokenLength = MaxTokenLength;
TokenStream tok = new StandardFilter(m_matchVersion, src);
tok = new LowerCaseFilter(m_matchVersion, tok);
tok = new StopFilter(m_matchVersion, tok, m_stopwords);
return new PositionIncrementGapTokenStreamComponents(this, src, tok);
}
private class PositionIncrementGapTokenStreamComponents : TokenStreamComponents
{
private readonly PositionIncrementGapAnalyzer analyzer;
private readonly StandardTokenizer src;
public PositionIncrementGapTokenStreamComponents(PositionIncrementGapAnalyzer analyzer,
StandardTokenizer src, TokenStream tok)
: base(src, tok)
{
this.analyzer = analyzer;
this.src = src;
}
protected override void SetReader(TextReader reader)
{
src.MaxTokenLength = analyzer.MaxTokenLength;
base.SetReader(reader);
}
}
}
LuceneVersion matchVersion = LuceneVersion.LUCENE_XY; // Substitute desired Lucene version for XY
Analyzer myAnalyzer = new PositionIncrementGapAnalyzer(matchVersion);
Token Position Increments
By default, all tokens created by Analyzers and Tokenizers have a PositionIncrement of one. This means that the position stored for that token in the index would be one more than that of the previous token. Recall that phrase and proximity searches rely on position info.
If the selected analyzer filters the stop words "is" and "the", then for a document containing the string "blue is the sky", only the tokens "blue", "sky" are indexed, with position("sky") = 3 + position("blue"). Now, a phrase query "blue is the sky" would find that document, because the same analyzer filters the same stop words from that query. But the phrase query "blue sky" would not find that document because the position increment between "blue" and "sky" is only 1.
If this behavior does not fit the application needs, the query parser needs to be configured to not take position increments into account when generating phrase queries.
Note that a StopFilter MUST increment the position increment in order not to generate corrupt TokenStream graphs. Here is the logic used by StopFilter to increment positions when filtering out tokens:
public class MyTokenStream : TokenStream
{
private readonly TokenStream ts;
private readonly CharArraySet stopWords;
private readonly ICharTermAttribute termAtt;
private readonly IPositionIncrementAttribute posIncrAtt;
public MyTokenStream(TokenStream ts, CharArraySet stopWords)
{
this.ts = ts;
termAtt = AddAttribute<ICharTermAttribute>();
posIncrAtt = AddAttribute<IPositionIncrementAttribute>();
}
public override bool IncrementToken()
{
int extraIncrement = 0;
while (true)
{
bool hasNext = ts.IncrementToken();
if (hasNext)
{
if (stopWords.Contains(termAttr.ToString()))
{
extraIncrement += posIncrAtt.PositionIncrement; // filter this word
continue;
}
if (extraIncrement > 0)
{
posIncrAtt.PositionIncrement += extraIncrement;
}
}
return hasNext;
}
}
}
public override TokenStream GetTokenStream(string fieldName, Reader reader)
{
TokenStream ts = someAnalyzer.GetTokenStream(fieldName, reader);
return new MyTokenStream(ts, stopWords);
}
A few more use cases for modifying position increments are:
Inhibiting phrase and proximity matches in sentence boundaries – for this, a tokenizer that identifies a new sentence can add 1 to the position increment of the first token of the new sentence.
Injecting synonyms – here, synonyms of a token should be added after that token, and their position increment should be set to 0. As result, all synonyms of a token would be considered to appear in exactly the same position as that token, and so would they be seen by phrase and proximity searches.
Token Position Length
By default, all tokens created by Analyzers and Tokenizers have a Length of one. This means that the token occupies a single position. This attribute is not indexed and thus not taken into account for positional queries, but is used by eg. suggesters.
The main use case for positions lengths is multi-word synonyms. With single-word synonyms, setting the position increment to 0 is enough to denote the fact that two words are synonyms, for example:
Term | red | magenta |
Position increment | 1 | 0 |
Given that position(magenta) = 0 + position(red), they are at the same position, so anything working with analyzers will return the exact same result if you replace "magenta" with "red" in the input. However, multi-word synonyms are more tricky. Let's say that you want to build a TokenStream where "IBM" is a synonym of "Internal Business Machines". Position increments are not enough anymore:
Term | IBM | International | Business | Machines |
Position increment | 1 | 0 | 1 | 1 |
The problem with this token stream is that "IBM" is at the same position as "International" although it is a synonym with "International Business Machines" as a whole. Setting the position increment of "Business" and "Machines" to 0 wouldn't help as it would mean than "International" is a synonym of "Business". The only way to solve this issue is to make "IBM" span across 3 positions, this is where position lengths come to rescue.
Term | IBM | International | Business | Machines |
Position increment | 1 | 0 | 1 | 1 |
Position length | 3 | 1 | 1 | 1 |
This new attribute makes clear that "IBM" and "International Business Machines" start and end at the same positions.
How to not write corrupt token streams
There are a few rules to observe when writing custom Tokenizers and TokenFilters:
The first position increment must be > 0.
Positions must not go backward.
Tokens that have the same start position must have the same start offset.
Tokens that have the same end position (taking into account the position length) must have the same end offset.
Tokenizers must call ClearAttributes() in IncrementToken().
Tokenizers must override End(), and pass the final offset (the total number of input characters processed) to both parameters of OffsetAttribute.SetOffset(int, int).
Although these rules might seem easy to follow, problems can quickly happen when chaining badly implemented filters that play with positions and offsets, such as synonym or n-grams filters. Here are good practices for writing correct filters:
Token filters should not modify offsets. If you feel that your filter would need to modify offsets, then it should probably be implemented as a Tokenizer.
Token filters should not insert positions. If a filter needs to add tokens, then they should all have a position increment of 0.
When they add tokens, token filters should call ClearAttributes() first.
When they remove tokens, token filters should increment the position increment of the following token.
Token filters should preserve position lengths.
TokenStream API
"Flexible Indexing" summarizes the effort of making the Lucene.NET indexer pluggable and extensible for custom index formats. A fully customizable indexer means that users will be able to store custom data structures on disk. Therefore an API is necessary that can transport custom types of data from the documents to the indexer.
Attribute and AttributeSource
Classes Attribute and AttributeSource serve as the basis upon which the analysis elements of "Flexible Indexing" are implemented. An Attribute holds a particular piece of information about a text token. For example, ICharTermAttribute contains the term text of a token, and IOffsetAttribute contains the start and end character offsets of a token. An AttributeSource is a collection of Attributes with a restriction: there may be only one instance of each attribute type. TokenStream now extends AttributeSource, which means that one can add Attributes to a TokenStream. Since TokenFilter extends TokenStream, all filters are also AttributeSources.
Lucene.NET provides seven Attributes out of the box:
The term text of a token. Implements J2N.Text.ICharSequence (providing properties Length and this[int], and allowing e.g. for direct use with J2N.Text.IAppendable (allowing the term text to be appended to.) In .NET, we can only use this indirectly with the [Regex](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex) class by first calling ToString() and then passing the string to the Regex. | |
The start and end offset of a token in characters. | |
See above for detailed information about position increment. | |
The number of positions occupied by a token. | |
The payload that a Token can optionally have. | |
The type of the token. Default is 'word'. | |
Optional flags a token can have. | |
Keyword-aware TokenStreams/-Filters skip modification of tokens that return true from this attribute's [IsKeyword](xref:Lucene.Net.Analysis.TokenAttributes.IKeywordAttribute#Lucene_Net_Analysis_TokenAttributes_IKeywordAttribute_IsKeyword) property. |
More Requirements for Analysis Component Classes
Due to the historical development of the API, there are some perhaps less than obvious requirements to implement analysis components classes.
Token Stream Lifetime
The code fragment of the analysis workflow protocol above shows a token stream being obtained, used, and then left for garbage. However, that does not mean that the components of that token stream will, in fact, be discarded. The default is just the opposite. Analyzer applies a reuse strategy to the tokenizer and the token filters. It will reuse them. For each new input, it calls SetReader(System.IO.TextReader) to set the input. Your components must be prepared for this scenario, as described below.
Tokenizer
You should create your tokenizer class by extending Tokenizer.
Your tokenizer must never make direct use of the System.Text.TextReader supplied to its constructor(s). (A future release of Apache Lucene.NET will remove the reader parameters from the Tokenizer constructors.) Tokenizer wraps the text reader in an object that helps enforce that applications comply with the analysis workflow. Thus, your class should only reference the input via the protected 'input' field of Tokenizer.
Your tokenizer must override End(). Your implementation must call
base.End()
. It must set a correct final offset into the offset attribute, and finish up and other attributes to reflect the end of the stream.If your tokenizer overrides Reset() or Dispose(), it must call the corresponding superclass method.
Token Filter
You should create your token filter class by extending TokenFilter. If your token filter overrides Reset(), End() or Dispose(), it must call the corresponding superclass method.
Creating delegates
Forwarding classes (those which extend Tokenizer but delegate selected logic to another tokenizer) must also set the reader to the delegate in the overridden Reset() method, e.g.:
public class ForwardingTokenizer : Tokenizer
{
private Tokenizer @delegate;
...
public override void Reset()
{
base.Reset();
@delegate.SetReader(this.m_input);
@delegate.Reset();
}
}
Testing Your Analysis Component
The Lucene.Net.TestFramework component defines BaseTokenStreamTestCase. By extending this class, you can create NUnit tests that validate that your Analyzer and/or analysis components correctly implement the protocol. The CheckRandomData()methods of that class are particularly effective in flushing out errors.
Using the TokenStream API
There are a few important things to know in order to use the new API efficiently which are summarized here. You may want to walk through the example below first and come back to this section afterwards.
Please keep in mind that an AttributeSource can only have one instance of a particular Attribute. Furthermore, if a chain of a TokenStream and multiple TokenFilters is used, then all TokenFilters in that chain share the Attributes with the TokenStream.
Attribute instances are reused for all tokens of a document. Thus, a TokenStream/-Filter needs to update the appropriate Attribute(s) in IncrementToken(). The consumer, commonly the Lucene.NET indexer, consumes the data in the Attributes and then calls IncrementToken() again until it returns false, which indicates that the end of the stream was reached. This means that in each call of IncrementToken() a TokenStream/-Filter can safely overwrite the data in the Attribute instances.
For performance reasons a TokenStream/-Filter should add/get Attributes during instantiation; i.e., create an attribute in the constructor and store references to it in an instance variable. Using an instance variable instead of calling
AddAttribute<T>()
/GetAttribute<T>()
in IncrementToken() will avoid attribute lookups for every token in the document.All methods in AttributeSource are idempotent, which means calling them multiple times always yields the same result. This is especially important to know for
AddAttribute<T>()
. The method takes the interface of an Attribute as an generic closing type and returns an instance. If an Attribute of the same type was previously added, then the already existing instance is returned, otherwise a new instance is created and returned. Therefore TokenStreams/-Filters can safely callAddAttribute<T>()
with the same Attribute type multiple times. Even consumers of TokenStreams should normally callAddAttribute<T>()
instead ofGetAttribute<T>()
, because it would not fail if the TokenStream does not have this Attribute (GetAttribute<T>()
would throw an ArgumentException, if the Attribute is missing). More advanced code could simply check withHasAttribute<T>()
, if a TokenStream has it, and may conditionally leave out processing for extra performance.
Example
In this example we will create a WhiteSpaceTokenizer and use a LengthFilter to suppress all words that have only two or fewer characters. The LengthFilter is part of the Lucene.Net assembly and its implementation will be explained here to illustrate the usage of the TokenStream API.
Then we will develop a custom Attribute, a IPartOfSpeechAttribute, and add another filter to the chain which utilizes the new custom attribute, and call it PartOfSpeechTaggingFilter.
Whitespace tokenization
public class MyAnalyzer : Analyzer
{
private LuceneVersion matchVersion;
public MyAnalyzer(LuceneVersion matchVersion)
{
this.matchVersion = matchVersion;
}
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new WhitespaceTokenizer(matchVersion, reader));
}
}
public static class Program
{
public static void Main(string[] args)
{
// text to tokenize
string text = "This is a demo of the TokenStream API";
LuceneVersion matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
MyAnalyzer analyzer = new MyAnalyzer(matchVersion);
TokenStream stream = analyzer.GetTokenStream("field", new StringReader(text));
// get the CharTermAttribute from the TokenStream
ICharTermAttribute termAtt = stream.AddAttribute<ICharTermAttribute>();
try
{
stream.Reset();
// print all tokens until stream is exhausted
while (stream.IncrementToken())
{
Console.WriteLine(termAtt.ToString());
}
stream.End();
}
finally
{
stream.Dispose();
}
}
In this easy example a simple white space tokenization is performed. In Main() a loop consumes the stream and prints the term text of the tokens by accessing the ICharTermAttribute that the WhitespaceTokenizer provides. Here is the output:
This
is
a
demo
of
the
new
TokenStream
API
Adding a LengthFilter
We want to suppress all tokens that have 2 or less characters. We can do that
easily by adding a LengthFilter to the chain. Only the
CreateComponents()
method in our analyzer needs to be changed:
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
TokenStream result = new LengthFilter(true, source, 3, int.MaxValue);
return new TokenStreamComponents(source, result);
}
Note how now only words with 3 or more characters are contained in the output:
This
demo
the
new
TokenStream
API
Now let's take a look how the LengthFilter is implemented:
public sealed class LengthFilter : FilteringTokenFilter
{
private readonly int min;
private readonly int max;
private readonly ICharTermAttribute termAtt = AddAttribute<ICharTermAttribute>();
/// <summary>
/// Create a new LengthFilter. This will filter out tokens whose
/// ICharTermAttribute is either too short
/// (< min) or too long (> max).
/// </summary>
/// <param name="version">the Lucene match version</param>
/// <param name="input">the TokenStream to consume</param>
/// <param name="min">the minimum length</param>
/// <param name="max">the maximum length</param>
public LengthFilter(LuceneVersion version, TokenStream input, int min, int max)
: base(version, input)
{
this.min = min;
this.max = max;
}
public override bool Accept()
{
int len = termAtt.Length;
return len >= min && len <= max;
}
}
In LengthFilter, the ICharTermAttribute is added and stored in the instance variable termAtt
. Remember that there can only be a single instance of ICharTermAttribute in the chain, so in our example the AddAttribute<T>()
call in LengthFilter returns the ICharTermAttribute that the WhitespaceTokenizer already added.
The tokens are retrieved from the input stream in FilteringTokenFilter's IncrementToken()
method (see below), which calls LengthFilter's Accept()
method. By looking at the term text in the ICharTermAttribute, the length of the term can be determined and tokens that are either too short or too long are skipped. Note how Accept()
can efficiently access the instance variable; no attribute lookup is necessary. The same is true for the consumer, which can simply use local references to the Attributes.
public abstract class FilteringTokenFilter : TokenFilter
{
private readonly IPositionIncrementAttribute posIncrAtt = AddAttribute<IPositionIncrementAttribute>();
/// <summary>
/// Create a new FilteringTokenFilter.
/// </summary>
/// <param name="version">the Lucene match version</param>
/// <param name="input">the TokenStream to consume</param>
public FilteringTokenFilter(LuceneVersion version, TokenStream input)
: base(input)
{
}
/// <summary>
/// Override this method and return if the current input token should be returned by IncrementToken.
/// </summary>
protected abstract bool Accept();
public sealed override bool IncrementToken()
{
int skippedPositions = 0;
while (m_input.IncrementToken())
{
if (Accept())
{
if (skippedPositions != 0)
{
posIncrAtt.PositionIncrement += skippedPositions;
}
return true;
}
skippedPositions += posIncrAtt.PositionIncrement;
}
// reached end of stream -- return false
return false;
}
public override void Reset()
{
base.Reset();
}
}
Adding a custom IAttribute
Now we're going to implement our own custom IAttribute for part-of-speech tagging and call it consequently
IPartOfSpeechAttribute
. First we need to define the interface of the new IAttribute:
public enum PartOfSpeech
{
Noun, Verb, Adjective, Adverb, Pronoun, Preposition, Conjunction, Article, Unknown
}
public interface IPartOfSpeechAttribute : IAttribute
{
PartOfSpeech PartOfSpeech { get; set; }
}
Now we also need to write the implementing class. The name of that class is important here: By default, Lucene checks if there is a class with the name of the IAttribute without the prefix 'I'. In this example, we would consequently call the implementing class PartOfSpeechAttribute
.
This should be the usual behavior. However, there is also an expert-API that allows changing these naming conventions: AttributeSource.AttributeFactory. The factory accepts an IAttribute interface as argument and returns an actual instance. You can implement your own factory if you need to change the default behavior.
Now here is the actual class that implements our new Attribute. Notice that the class has to extend Attribute:
public sealed class PartOfSpeechAttribute : Lucene.Net.Util.Attribute, IPartOfSpeechAttribute
{
public PartOfSpeech PartOfSpeech { get; set; } = PartOfSpeech.Unknown;
public override void Clear()
{
PartOfSpeech = PartOfSpeech.Unknown;
}
public override void CopyTo(IAttribute target)
{
((IPartOfSpeechAttribute)target).PartOfSpeech = PartOfSpeech;
}
}
This is a simple Attribute implementation has only a single variable that stores the part-of-speech of a token. It extends the Attribute
class and therefore implements its abstract methods Clear()
and CopyTo()
. Now we need a TokenFilter that can set this new PartOfSpeechAttribute for each token. In this example we show a very naive filter that tags every word with a leading upper-case letter as a 'Noun' and all other words as 'Unknown'.
public class PartOfSpeechTaggingFilter : TokenFilter
{
private readonly IPartOfSpeechAttribute posAtt;
private readonly ICharTermAttribute termAtt;
protected PartOfSpeechTaggingFilter(TokenStream input)
: base(input)
{
posAtt = AddAttribute<IPartOfSpeechAttribute>();
termAtt = AddAttribute<ICharTermAttribute>();
}
public bool IncrementToken()
{
if (!m_input.IncrementToken()) { return false; }
posAtt.PartOfSpeech = DeterminePartOfSpeech(termAtt.Buffer, 0, termAtt.Length);
return true;
}
// determine the part of speech for the given term
protected PartOfSpeech DeterminePartOfSpeech(char[] term, int offset, int length)
{
// naive implementation that tags every uppercased word as noun
if (length > 0 && char.IsUpper(term[0]))
{
return PartOfSpeech.Noun;
}
return PartOfSpeech.Unknown;
}
}
Just like the LengthFilter, this new filter stores references to the attributes it needs in instance variables. Notice how you only need to pass in the interface of the new Attribute and instantiating the correct class is automatically taken care of.
Now we need to add the filter to the chain in MyAnalyzer:
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
TokenStream result = new LengthFilter(matchVersion, source, 3, int.MaxValue);
result = new PartOfSpeechTaggingFilter(result);
return new TokenStreamComponents(source, result);
}
Now let's look at the output:
This
demo
the
new
TokenStream
API
Apparently it hasn't changed, which shows that adding a custom attribute to a TokenStream/Filter chain does not affect any existing consumers, simply because they don't know the new Attribute. Now let's change the consumer to make use of the new PartOfSpeechAttribute and print it out:
public static class Program
{
public static void Main(string[] args)
{
// text to tokenize
string text = "This is a demo of the TokenStream API";
MyAnalyzer analyzer = new MyAnalyzer();
TokenStream stream = analyzer.GetTokenStream("field", new StringReader(text));
// get the ICharTermAttribute from the TokenStream
ICharTermAttribute termAtt = stream.AddAttribute<ICharTermAttribute>();
// get the PartOfSpeechAttribute from the TokenStream
IPartOfSpeechAttribute posAtt = stream.AddAttribute<IPartOfSpeechAttribute>();
try
{
stream.Reset();
// print all tokens until stream is exhausted
while (stream.IncrementToken())
{
Console.WriteLine(termAtt.ToString() + ": " + posAtt.PartOfSpeech);
}
stream.End();
}
finally
{
stream.Dispose();
}
}
}
The change that was made is to get the PartOfSpeechAttribute from the TokenStream and print out its contents in the while loop that consumes the stream. Here is the new output:
This: Noun
demo: Unknown
the: Unknown
new: Unknown
TokenStream: Noun
API: Noun
Each word is now followed by its assigned PartOfSpeech tag. Of course this is a naive part-of-speech tagging. The word 'This' should not even be tagged as noun; it is only spelled capitalized because it is the first word of a sentence. Actually this is a good opportunity for an exercise. To practice the usage of the new API the reader could now write an IAttribute and TokenFilter that can specify for each word if it was the first token of a sentence or not. Then the PartOfSpeechTaggingFilter can make use of this knowledge and only tag capitalized words as nouns if not the first word of a sentence (we know, this is still not a correct behavior, but hey, it's a good exercise). As a small hint, this is how the new IAttribute class could begin:
public class FirstTokenOfSentenceAttribute : Lucene.Net.Util.Attribute, IFirstTokenOfSentenceAttribute
{
public bool FirstToken { get; set; }
public override void Clear()
{
FirstToken = false;
}
// ...
}
Adding a CharFilter chain
Analyzers take .NET System.Text.TextReaders as input. In Java you can wrap Readers with java.io.FilterReaders to manipulate content, but this would have the big disadvantage that character offsets might be inconsistent with your original text.
CharFilter is designed to allow you to pre-process input like a FilterReader would, but also preserve the original offsets associated with those characters. This way mechanisms like highlighting still work correctly. CharFilters can be chained.
Example:
public class MyAnalyzer : Analyzer
{
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new MyTokenizer(reader));
}
protected override TextReader InitReader(string fieldName, TextReader reader)
{
// wrap the Reader in a CharFilter chain.
return new SecondCharFilter(new FirstCharFilter(reader));
}
}
Classes
Analyzer
An Analyzer builds TokenStreams, which analyze text. It thus represents a policy for extracting index terms from text.
In order to define what analysis is done, subclasses must define their TokenStreamComponents in CreateComponents(string, TextReader). The components are then reused in each call to GetTokenStream(string, TextReader). Simple example:Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer source = new FooTokenizer(reader);
TokenStream filter = new FooFilter(source);
filter = new BarFilter(filter);
return new TokenStreamComponents(source, filter);
});
For more examples, see the Lucene.Net.Analysis namespace documentation.
For some concrete implementations bundled with Lucene, look in the analysis modules:
- [Common](../analysis-common/overview.html): Analyzers for indexing content in different languages and domains.
- [ICU](../icu/Lucene.Net.Analysis.Icu.html): Exposes functionality from ICU to Apache Lucene.
- [Kuromoji](../analysis-kuromoji/Lucene.Net.Analysis.Ja.html): Morphological analyzer for Japanese text.
- [Morfologik](../analysis-morfologik/Lucene.Net.Analysis.Morfologik.html): Dictionary-driven lemmatization for the Polish language.
- [OpenNLP](../analysis-opennlp/Lucene.Net.Analysis.OpenNlp.html): Analysis integration with Apache OpenNLP.
- [Phonetic](../analysis-phonetic/Lucene.Net.Analysis.Phonetic.html): Analysis for indexing phonetic signatures (for sounds-alike search).
- [Smart Chinese](../analysis-smartcn/Lucene.Net.Analysis.Cn.Smart.html): Analyzer for Simplified Chinese, which indexes words.
- [Stempel](../analysis-stempel/Lucene.Net.Analysis.Stempel.html): Algorithmic Stemmer for the Polish Language.
Analyzer.GlobalReuseStrategy
Implementation of ReuseStrategy that reuses the same components for every field.
Analyzer.PerFieldReuseStrategy
Implementation of ReuseStrategy that reuses components per-field by maintaining a Map of TokenStreamComponents per field name.
AnalyzerWrapper
Extension to Analyzer suitable for Analyzers which wrap other Analyzers.
GetWrappedAnalyzer(string) allows the Analyzer to wrap multiple Analyzers which are selected on a per field basis. WrapComponents(string, TokenStreamComponents) allows the TokenStreamComponents of the wrapped Analyzer to then be wrapped (such as adding a new TokenFilter to form new TokenStreamComponents).CachingTokenFilter
This class can be used if the token attributes of a TokenStream are intended to be consumed more than once. It caches all token attribute states locally in a List.
CachingTokenFilter implements the optional method Reset(), which repositions the stream to the first Token.CharFilter
Subclasses of CharFilter can be chained to filter a TextReader They can be used as TextReader with additional offset correction. Tokenizers will automatically use CorrectOffset(int) if a CharFilter subclass is used.
This class is abstract: at a minimum you must implement Read(char[], int, int), transforming the input in some way from m_input, and Correct(int) to adjust the offsets to match the originals. You can optionally provide more efficient implementations of additional methods like Read(), but this is not required. For examples and integration with Analyzer, see the Lucene.Net.Analysis namespace documentation.NumericTokenStream
Expert: this class provides a TokenStream for indexing numeric values that can be used by NumericRangeQuery or NumericRangeFilter.
Note that for simple usage, Int32Field, Int64Field, SingleField or DoubleField is recommended. These fields disable norms and term freqs, as they are not usually needed during searching. If you need to change these settings, you should use this class. Here's an example usage, for an int field:IndexableFieldType fieldType = new IndexableFieldType(TextField.TYPE_NOT_STORED)
{
OmitNorms = true,
IndexOptions = IndexOptions.DOCS_ONLY
};
Field field = new Field(name, new NumericTokenStream(precisionStep).SetInt32Value(value), fieldType);
document.Add(field);
For optimal performance, re-use the TokenStream and Field instance
for more than one document:
NumericTokenStream stream = new NumericTokenStream(precisionStep);
IndexableFieldType fieldType = new IndexableFieldType(TextField.TYPE_NOT_STORED)
{
OmitNorms = true,
IndexOptions = IndexOptions.DOCS_ONLY
};
Field field = new Field(name, stream, fieldType);
Document document = new Document();
document.Add(field);
for(all documents)
{
stream.SetInt32Value(value)
writer.AddDocument(document);
}
this stream is not intended to be used in analyzers;
it's more for iterating the different precisions during indexing a specific numeric value.
NOTE: as token streams are only consumed once the document is added to the index, if you index more than one numeric field, use a separate NumericTokenStream instance for each.
See NumericRangeQuery for more details on the
precisionStep
parameter as well as how numeric fields work under the hood.
@since 2.9
NumericTokenStream.NumericTermAttribute
Implementation of NumericTokenStream.INumericTermAttribute.
Note
This API is for internal purposes only and might change in incompatible ways in the next release.
ReusableStringReader
Internal class to enable reuse of the string reader by GetTokenStream(string, string)
ReuseStrategy
Strategy defining how TokenStreamComponents are reused per call to GetTokenStream(string, TextReader).
Token
A Token is an occurrence of a term from the text of a field. It consists of a term's text, the start and end offset of the term in the text of the field, and a type string.
The start and end offsets permit applications to re-associate a token with its source text, e.g., to display highlighted query terms in a document browser, or to show matching text fragments in a KWIC (KeyWord In Context) display, etc. The type is a string, assigned by a lexical analyzer (a.k.a. tokenizer), naming the lexical or syntactic class that the token belongs to. For example an end of sentence marker token might be implemented with type "eos". The default token type is "word". A Token can optionally have metadata (a.k.a. payload) in the form of a variable length byte array. Use GetPayload() to retrieve the payloads from the index. NOTE: As of 2.9, Token implements all IAttribute interfaces that are part of core Lucene and can be found in the Lucene.Net.Analysis.TokenAttributes namespace. Even though it is not necessary to use Token anymore, with the new TokenStream API it can be used as convenience class that implements all IAttributes, which is especially useful to easily switch from the old to the new TokenStream API.Tokenizers and TokenFilters should try to re-use a Token instance when possible for best performance, by implementing the IncrementToken() API. Failing that, to create a new Token you should first use one of the constructors that starts with null text. To load the token from a char[] use CopyBuffer(char[], int, int). To load from a string use SetEmpty() followed by Append(string) or Append(string, int, int). Alternatively you can get the Token's termBuffer by calling either Buffer, if you know that your text is shorter than the capacity of the termBuffer or ResizeBuffer(int), if there is any possibility that you may need to grow the buffer. Fill in the characters of your term into this buffer, with ToCharArray(int, int) if loading from a string, or with Copy(Array, int, Array, int, int), and finally call SetLength(int) to set the length of the term text. See LUCENE-969 for details.
Typical Token reuse patterns:
- Copying text from a string (type is reset to DEFAULT_TYPE if not specified):
return reusableToken.Reinit(string, startOffset, endOffset[, type]);
- Copying some text from a string (type is reset to DEFAULT_TYPE if not specified):
return reusableToken.Reinit(string, 0, string.Length, startOffset, endOffset[, type]);
- Copying text from char[] buffer (type is reset to DEFAULT_TYPE if not specified):
return reusableToken.Reinit(buffer, 0, buffer.Length, startOffset, endOffset[, type]);
- Copying some text from a char[] buffer (type is reset to DEFAULT_TYPE if not specified):
return reusableToken.Reinit(buffer, start, end - start, startOffset, endOffset[, type]);
- Copying from one one Token to another (type is reset to DEFAULT_TYPE if not specified):
return reusableToken.Reinit(source.Buffer, 0, source.Length, source.StartOffset, source.EndOffset[, source.Type]);
- Clear() initializes all of the fields to default values. this was changed in contrast to Lucene 2.4, but should affect no one.
- Because TokenStreams can be chained, one cannot assume that the Token's current type is correct.
- The startOffset and endOffset represent the start and offset in the source text, so be careful in adjusting them.
- When caching a reusable token, clone it. When injecting a cached token into a stream that can be reset, clone it again.
Please note: With Lucene 3.1, the ToString() method had to be changed to match the J2N.Text.ICharSequence interface introduced by the interface ICharTermAttribute. this method now only prints the term text, no additional information anymore.
Token.TokenAttributeFactory
Expert: Creates a Token.TokenAttributeFactory returning Token as instance for the basic attributes and for all other attributes calls the given delegate factory. @since 3.0
TokenFilter
A TokenFilter is a TokenStream whose input is another TokenStream.
This is an abstract class; subclasses must override IncrementToken().TokenStream
A TokenStream enumerates the sequence of tokens, either from Fields of a Document or from query text.
this is an abstract class; concrete subclasses are:- Tokenizer, a TokenStream whose input is a TextReader; and
- TokenFilter, a TokenStream whose input is another TokenStream.
- Instantiation of TokenStream/TokenFilters which add/get attributes to/from the AttributeSource.
- The consumer calls Reset().
- The consumer retrieves attributes from the stream and stores local references to all attributes it wants to access.
- The consumer calls IncrementToken() until it returns false consuming the attributes after each call.
- The consumer calls End() so that any end-of-stream operations can be performed.
- The consumer calls Dispose() to release any resource when finished using the TokenStream.
TokenStreamComponents
This class encapsulates the outer components of a token stream. It provides access to the source (Tokenizer) and the outer end (sink), an instance of TokenFilter which also serves as the TokenStream returned by GetTokenStream(string, TextReader).
TokenStreamToAutomaton
Consumes a TokenStream and creates an Automaton where the transition labels are UTF8 bytes (or Unicode code points if unicodeArcs is true) from the ITermToBytesRefAttribute. Between tokens we insert POS_SEP and for holes we insert HOLE.
Note
This API is experimental and might change in incompatible ways in the next release.
Tokenizer
A Tokenizer is a TokenStream whose input is a TextReader.
This is an abstract class; subclasses must override IncrementToken() NOTE: Subclasses overriding IncrementToken() must call ClearAttributes() before setting attributes.Interfaces
NumericTokenStream.INumericTermAttribute
Expert: Use this attribute to get the details of the currently generated token.
Note
This API is experimental and might change in incompatible ways in the next release.