选自文档
Package org.apache.lucene.analysis Description 概述
API and code to convert text into indexable/searchable tokens. CoversAnalyzer and related classes.
该包API和code用以转换文本为可index可search的tokens,涉及Analyzer和相关类
Parsing? Tokenization? Analysis! 解析器?分词器?分析器!
Lucene, an indexing and search library, accepts only plain text input.
Parsing =Lucene无解析器,只处理纯文本
Applications that build their search capabilities upon Lucene may support documents in various formats – HTML, XML, PDF, Word – just to name a few.Lucene does not care about theParsing of these and other document formats, and it is the responsibility of the application using Lucene to use an appropriateParser to convert the original format into plain text before passing that plain text to Lucene.
Tokenization 分词
Plain text passed to Lucene for indexing goes through a process generally called tokenization. Tokenization is the processof 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).
长句变分词,分词附权重
In some cases simply breaking the input text into tokens is not enough – a deeperAnalysis 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.
预分词 如跳过HTML标记,转换或剔除固定文本,等等。
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 Readers into tokens that can be indexed by Lucene. There are four main classes in the package from which all analysis processes are derived. These are:
此包专为转换String和Reader为tokens提供实现手段,以便Lucene 来索引。所有的分析过程都继承自如下4大类:
Analyzer– An Analyzer is responsible for building aTokenStreamwhich can be consumed by the indexing and searching processes. See below for more information on implementing your own Analyzer.
- CharFilter – CharFilter extends
Readerto perform pre-tokenization substitutions, deletions, and/or insertions on an input Reader'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.
继承自Reader,用以预分词;
Tokenizer– A Tokenizer is aTokenStreamand 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).
TokenSteam类,用以分词;
TokenFilter– A TokenFilter is also aTokenStreamand 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.
也是TokenStream类,用以修改词目tokens;
Hints, Tips and Traps 暗示,提示,警示
The synergy between
AnalyzerandTokenizeris sometimes confusing. To ease this confusion, some clarifications:
Analyzer 和Tokenizer别搞混了,Analyzer是CEO,Tokenizer是CTO,一个是管事的,一个是做事的,一是将,一是兵。
- The
Analyzeris responsible for the entire task of creating tokens out of the input text, while theTokenizeris only responsible for breaking the input text into tokens. Very likely, tokens created by theTokenizerwould be modified or even omitted by theAnalyzer(via one or moreTokenFilters) before being returned. Tokenizeris aTokenStream, butAnalyzeris not.Analyzeris "field aware", butTokenizeris not.
StandardAnalyzer很强大,不过不能忽视如下类库
Lucene Java provides a number of analysis capabilities, the most commonly used one being theStandardAnalyzer. 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 differentFields.
在不同Analyzer中与不同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.
特色语言包的Analyzer,真心周到~
- There are a variety of Tokenizer and TokenFilter implementations in this package. Take a look around, chances are someone has implemented what you need.
Tokenizer和TokenFilter包中有很多扩展应用,让我们站在巨人的肩膀上~
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.
分析与索引,不可得兼,分析多,时耗长,时耗短,搜不准。 benchmark/ 下有用的工具来测试分析程序
Invoking the Analyzer 何时调用分析器
Applications usually do not invoke analysis – Lucene does it for them:
- At indexing, as a consequence of
addDocument(doc), the Analyzer in effect for indexing is invoked for each indexed field of the added document.
index 时 addDocument(doc) 将调用Analyzer 分析每个doc的field
- At search, a QueryParser may invoke the Analyzer during parsing. Note that for some queries, analysis does not take place, e.g. wildcard queries.
search 时,QueryParser 也调用Analyzer,但并非每个Query都会用。
However an application might invoke Analysis of any text for testing or for any other purpose, something like:
Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY Analyzer analyzer = new StandardAnalyzer(matchVersion); // or any other analyzer TokenStream ts = analyzer.tokenStream("myfield", new StringReader("some text goes here")); OffsetAttribute offsetAtt = ts.addAttribute(OffsetAttribute.class); try { ts.reset(); // Resets this stream to the beginning. (Required) while (ts.incrementToken()) { // Use AttributeSource.reflectAsString(boolean) // for token stream debugging. System.out.println("token: " + ts.reflectAsString(true)); System.out.println("token start offset: " + offsetAtt.startOffset()); System.out.println(" token end offset: " + offsetAtt.endOffset()); } ts.end(); // Perform end-of-stream operations, e.g. set the final offset. } finally { ts.close(); // Release resources associated with this stream. }- The
Indexing Analysis vs. Search Analysis 选择正确的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 pageAnalysisParalysis 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.
注意,analysis有损index啊,伤不起有木有亲!
- Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...
index和search就用一同一个analyzer吧,亲,要专一啊,亲!
- 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.
什么?天不遂人愿!偏要用不同的analyzer,怎么办??欲知后事如何,且听下回分解。
Implementing your own Analyzer 自己动手,丰衣足食,自个的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 theanalyzers-common library and/or ask on the java-user@lucene.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.
简单:就是个大杂烩,啥都往锅里倒。但注意,先看看别人做了没,或者上mailing list问问~(我还不会。。。求指导)
The following sections discuss some aspects of implementing your own analyzer.
如下几方面请注意:
Field Section Boundaries
When document.add(field) 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 totokenStream(field,reader) 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", simply by overridingAnalyzer.getPositionIncrementGap(fieldName):
Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
Analyzer myAnalyzer = new StandardAnalyzer(matchVersion) {
public int getPositionIncrementGap(String fieldName) {
return 10;
}
};
Token Position Increments
By default, all tokens created by Analyzers and Tokenizers have aposition increment 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") = 1 + 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 also the phrase query "blue sky" would find that document.
If this behavior does not fit the application needs, a modified analyzer can be used, that would increment further the positions of tokens following a removed stop word, usingPositionIncrementAttribute.setPositionIncrement(int). This can be done with something like the following (note, however, that StopFilter natively includes this capability by subclassing FilteringTokenFilter}:
public TokenStream tokenStream(final String fieldName, Reader reader) {
final TokenStream ts = someAnalyzer.tokenStream(fieldName, reader);
TokenStream res = new TokenStream() {
CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
public boolean incrementToken() throws IOException {
int extraIncrement = 0;
while (true) {
boolean hasNext = ts.incrementToken();
if (hasNext) {
if (stopWords.contains(termAtt.toString())) {
extraIncrement++; // filter this word
continue;
}
if (extraIncrement>0) {
posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement()+extraIncrement);
}
}
return hasNext;
}
}
};
return res;
}
Now, with this modified analyzer, the phrase query "blue sky" would find that document. But note that this is yet not a perfect solution, because any phrase query "blue w1 w2 sky" where both w1 and w2 are stop words would match that document.
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.
TokenStream API
"Flexible Indexing" summarizes the effort of making the Lucene 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,CharTermAttribute contains the term text of a token, and OffsetAttribute 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 provides seven Attributes out of the box:
CharTermAttribute | The term text of a token. Implements CharSequence (providing methods length() and charAt(), and allowing e.g. for direct use with regular expressionMatchers) and Appendable (allowing the term text to be appended to.) |
OffsetAttribute | The start and end offset of a token in characters. |
PositionIncrementAttribute | See above for detailed information about position increment. |
PayloadAttribute | The payload that a Token can optionally have. |
TypeAttribute | The type of the token. Default is 'word'. |
FlagsAttribute | Optional flags a token can have. |
KeywordAttribute | Keyword-aware TokenStreams/-Filters skip modification of tokens that return true from this attribute's isKeyword() method. |
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 wantto 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 Attributeswith the TokenStream.
- Attribute instances are reused for all tokens of a document. Thus, a TokenStream/-Filter needs to updatethe appropriate Attribute(s) in incrementToken(). The consumer, commonly the Lucene indexer, consumes the data in theAttributes and then calls incrementToken() again until it returns false, which indicates that the end of the streamwas reached. This means that in each call of incrementToken() a TokenStream/-Filter can safely overwrite the data inthe Attribute instances.
- For performance reasons a TokenStream/-Filter should add/get Attributes during instantiation; i.e., create an attribute in theconstructor and store references to it in an instance variable. Using an instance variable instead of calling addAttribute()/getAttribute() 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 sameresult. This is especially important to know for addAttribute(). The method takes thetype (
Class)of an Attribute as an argument and returns aninstance. If an Attribute of the same type was previously added, thenthe already existing instance is returned, otherwise a new instance is created and returned. Therefore TokenStreams/-Filterscan safely call addAttribute() with the same Attribute type multiple times. Even consumers of TokenStreams shouldnormally call addAttribute() instead of getAttribute(), because it would not fail if the TokenStream does not have thisAttribute (getAttribute() would throw an IllegalArgumentException, if the Attribute is missing). More advanced codecould simply check with hasAttribute(), if a TokenStream has it, and may conditionally leave out processing forextra 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 core and its implementation will be explained here to illustrate the usage of the TokenStream API.
Then we will develop a custom Attribute, a PartOfSpeechAttribute, and add another filter to the chain which utilizes the new custom attribute, and call it PartOfSpeechTaggingFilter.
Whitespace tokenization
public class MyAnalyzer extends Analyzer {
private Version matchVersion;
public MyAnalyzer(Version matchVersion) {
this.matchVersion = matchVersion;
}
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
return new TokenStreamComponents(new WhitespaceTokenizer(matchVersion, reader));
}
public static void main(String[] args) throws IOException {
// text to tokenize
final String text = "This is a demo of the TokenStream API";
Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
MyAnalyzer analyzer = new MyAnalyzer(matchVersion);
TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
// get the CharTermAttribute from the TokenStream
CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
try {
stream.reset();
// print all tokens until stream is exhausted
while (stream.incrementToken()) {
System.out.println(termAtt.toString());
}
stream.end();
} finally {
stream.close();
}
}
}
In this easy example a simple white space tokenization is performed. In main() a loop consumes the stream andprints the term text of the tokens by accessing the CharTermAttribute 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 thateasily by adding a LengthFilter to the chain. Only thecreateComponents() method in our analyzer needs to be changed:
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
TokenStream result = new LengthFilter(true, source, 3, Integer.MAX_VALUE);
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 final class LengthFilter extends FilteringTokenFilter {
private final int min;
private final int max;
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
/**
* Build a filter that removes words that are too long or too
* short from the text.
*/
public LengthFilter(boolean enablePositionIncrements, TokenStream in, int min, int max) {
super(enablePositionIncrements, in);
this.min = min;
this.max = max;
}
@Override
public boolean accept() throws IOException {
final int len = termAtt.length();
return (len >= min && len <= max);
}
}
In LengthFilter, the CharTermAttribute is added and stored in the instance variabletermAtt. Remember that there can only be a single instance of CharTermAttribute in the chain, so in our example theaddAttribute() call in LengthFilter returns the CharTermAttribute that the WhitespaceTokenizer already added.
The tokens are retrieved from the input stream in FilteringTokenFilter'sincrementToken() method (see below), which calls LengthFilter'saccept() method. By looking at the term text in the CharTermAttribute, the length of the term can be determined and tokens that are either too short or too long are skipped. Note howaccept() 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.
LengthFilter extends FilteringTokenFilter:
public abstract class FilteringTokenFilter extends TokenFilter { private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class); private boolean enablePositionIncrements; // no init needed, as ctor enforces setting value! public FilteringTokenFilter(boolean enablePositionIncrements, TokenStream input){ super(input); this.enablePositionIncrements = enablePositionIncrements; } /** Override this method and return if the current input token should be returned by {@link #incrementToken}. */ protected abstract boolean accept() throws IOException; @Override public final boolean incrementToken() throws IOException { if (enablePositionIncrements) { int skippedPositions = 0; while (input.incrementToken()) { if (accept()) { if (skippedPositions != 0) { posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions); } return true; } skippedPositions += posIncrAtt.getPositionIncrement(); } } else { while (input.incrementToken()) { if (accept()) { return true; } } } // reached EOS -- return false return false; } /** * @see #setEnablePositionIncrements(boolean) */ public boolean getEnablePositionIncrements() { return enablePositionIncrements; } /** * Iftrue, this TokenFilter will preserve * positions of the incoming tokens (ie, accumulate and * set position increments of the removed tokens). * Generally,trueis best as it does not * lose information (positions of the original tokens) * during indexing. * *When set, when a token is stopped * (omitted), the position increment of the following * token is incremented. * *
NOTE: be sure to also * set org.apache.lucene.queryparser.classic.QueryParser#setEnablePositionIncrements if * you use QueryParser to create queries. */ public void setEnablePositionIncrements(boolean enable) { this.enablePositionIncrements = enable; } }
Adding a custom Attribute
Now we're going to implement our own custom Attribute for part-of-speech tagging and call it consequentlyPartOfSpeechAttribute. First we need to define the interface of the new Attribute:
public interface PartOfSpeechAttribute extends Attribute {
public static enum PartOfSpeech {
Noun, Verb, Adjective, Adverb, Pronoun, Preposition, Conjunction, Article, Unknown
}
public void setPartOfSpeech(PartOfSpeech pos);
public PartOfSpeech getPartOfSpeech();
}
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 Attribute with the suffix 'Impl'. In this example, we would consequently call the implementing class PartOfSpeechAttributeImpl.
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 Attribute 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 extendAttributeImpl:
public final class PartOfSpeechAttributeImpl extends AttributeImpl
implements PartOfSpeechAttribute {
private PartOfSpeech pos = PartOfSpeech.Unknown;
public void setPartOfSpeech(PartOfSpeech pos) {
this.pos = pos;
}
public PartOfSpeech getPartOfSpeech() {
return pos;
}
@Override
public void clear() {
pos = PartOfSpeech.Unknown;
}
@Override
public void copyTo(AttributeImpl target) {
((PartOfSpeechAttribute) target).setPartOfSpeech(pos);
}
}
This is a simple Attribute implementation has only a single variable that stores the part-of-speech of a token. It extends theAttributeImpl class and therefore implements its abstract methodsclear() 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 static class PartOfSpeechTaggingFilter extends TokenFilter {
PartOfSpeechAttribute posAtt = addAttribute(PartOfSpeechAttribute.class);
CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
protected PartOfSpeechTaggingFilter(TokenStream input) {
super(input);
}
public boolean incrementToken() throws IOException {
if (!input.incrementToken()) {return false;}
posAtt.setPartOfSpeech(determinePOS(termAtt.buffer(), 0, termAtt.length()));
return true;
}
// determine the part of speech for the given term
protected PartOfSpeech determinePOS(char[] term, int offset, int length) {
// naive implementation that tags every uppercased word as noun
if (length > 0 && Character.isUpperCase(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:
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
TokenStream result = new LengthFilter(true, source, 3, Integer.MAX_VALUE);
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 notaffect any existing consumers, simply because they don't know the new Attribute. Now let's change the consumerto make use of the new PartOfSpeechAttribute and print it out:
public static void main(String[] args) throws IOException {
// text to tokenize
final String text = "This is a demo of the TokenStream API";
MyAnalyzer analyzer = new MyAnalyzer();
TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
// get the CharTermAttribute from the TokenStream
CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
// get the PartOfSpeechAttribute from the TokenStream
PartOfSpeechAttribute posAtt = stream.addAttribute(PartOfSpeechAttribute.class);
try {
stream.reset();
// print all tokens until stream is exhausted
while (stream.incrementToken()) {
System.out.println(termAtt.toString() + ": " + posAtt.getPartOfSpeech());
}
stream.end();
} finally {
stream.close();
}
}
The change that was made is to get the PartOfSpeechAttribute from the TokenStream and print out its contents inthe 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 itis the first word of a sentence. Actually this is a good opportunity for an exercise. To practice the usage of the newAPI the reader could now write an Attribute and TokenFilter that can specify for each word if it was the first tokenof a sentence or not. Then the PartOfSpeechTaggingFilter can make use of this knowledge and only tag capitalized wordsas 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 Attribute class could begin:
public class FirstTokenOfSentenceAttributeImpl extends AttributeImpl
implements FirstTokenOfSentenceAttribute {
private boolean firstToken;
public void setFirstToken(boolean firstToken) {
this.firstToken = firstToken;
}
public boolean getFirstToken() {
return firstToken;
}
@Override
public void clear() {
firstToken = false;
}
...
Adding a CharFilter chain
Analyzers take JavaReaders as input. Of course you can wrap your Readers with FilterReadersto manipulate content, but this would have the big disadvantage that character offsets might be inconsistent with your originaltext.
CharFilter is designed to allow you to pre-process input like a FilterReader would, but alsopreserve the original offsets associated with those characters. This way mechanisms like highlighting still work correctly.CharFilters can be chained.
Example:
public class MyAnalyzer extends Analyzer {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
return new TokenStreamComponents(new MyTokenizer(reader));
}
@Override
protected Reader initReader(String fieldName, Reader reader) {
// wrap the Reader in a CharFilter chain.
return new SecondCharFilter(new FirstCharFilter(reader));
}
}
本文深入探讨了Lucene的全文检索技术,包括文本转换、解析、分词、深度分析等关键步骤,以及如何选择合适的分析器以提高搜索质量。

1280

被折叠的 条评论
为什么被折叠?



