1
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
4
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
<meta name="Author" content="Doug Cutting">
8
<p>API and code to convert text into indexable/searchable tokens. Covers {@link org.apache.lucene.analysis.Analyzer} and related classes.</p>
9
<h2>Parsing? Tokenization? Analysis!</h2>
11
Lucene, indexing and search library, accepts only plain text input.
15
Applications that build their search capabilities upon Lucene may support documents in various formats – HTML, XML, PDF, Word – just to name a few.
16
Lucene does not care about the <i>Parsing</i> of these and other document formats, and it is the responsibility of the
17
application using Lucene to use an appropriate <i>Parser</i> to convert the original format into plain text before passing that plain text to Lucene.
21
Plain text passed to Lucene for indexing goes through a process generally called tokenization – namely breaking of the
22
input text into small indexing elements –
23
{@link org.apache.lucene.analysis.Token Tokens}.
24
The way input text is broken into tokens very
25
much dictates further capabilities of search upon that text.
26
For instance, sentences beginnings and endings can be identified to provide for more accurate phrase
27
and proximity searches (though sentence identification is not provided by Lucene).
29
In some cases simply breaking the input text into tokens is not enough – a deeper <i>Analysis</i> is needed,
30
providing for several functions, including (but not limited to):
32
<li><a href="http://en.wikipedia.org/wiki/Stemming">Stemming</a> –
33
Replacing of words by their stems.
34
For instance with English stemming "bikes" is replaced by "bike";
35
now query "bike" can find both documents containing "bike" and those containing "bikes".
37
<li><a href="http://en.wikipedia.org/wiki/Stop_words">Stop Words Filtering</a> –
38
Common words like "the", "and" and "a" rarely add any value to a search.
39
Removing them shrinks the index size and increases performance.
40
It may also reduce some "noise" and actually improve search quality.
42
<li><a href="http://en.wikipedia.org/wiki/Text_normalization">Text Normalization</a> –
43
Stripping accents and other character markings can make for better searching.
45
<li><a href="http://en.wikipedia.org/wiki/Synonym">Synonym Expansion</a> –
46
Adding in synonyms at the same token position as the current word can mean better
47
matching when users search with words in the synonym set.
51
<h2>Core Analysis</h2>
53
The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene. There
54
are three main classes in the package from which all analysis processes are derived. These are:
56
<li>{@link org.apache.lucene.analysis.Analyzer} – An Analyzer is responsible for building a {@link org.apache.lucene.analysis.TokenStream} which can be consumed
57
by the indexing and searching processes. See below for more information on implementing your own Analyzer.</li>
58
<li>{@link org.apache.lucene.analysis.Tokenizer} – A Tokenizer is a {@link org.apache.lucene.analysis.TokenStream} and is responsible for breaking
59
up incoming text into {@link org.apache.lucene.analysis.Token}s. In most cases, an Analyzer will use a Tokenizer as the first step in
60
the analysis process.</li>
61
<li>{@link org.apache.lucene.analysis.TokenFilter} – A TokenFilter is also a {@link org.apache.lucene.analysis.TokenStream} and is responsible
62
for modifying {@link org.apache.lucene.analysis.Token}s that have been created by the Tokenizer. Common modifications performed by a
63
TokenFilter are: deletion, stemming, synonym injection, and down casing. Not all Analyzers require TokenFilters</li>
66
<h2>Hints, Tips and Traps</h2>
68
The synergy between {@link org.apache.lucene.analysis.Analyzer} and {@link org.apache.lucene.analysis.Tokenizer}
69
is sometimes confusing. To ease on this confusion, some clarifications:
71
<li>The {@link org.apache.lucene.analysis.Analyzer} is responsible for the entire task of
72
<u>creating</u> tokens out of the input text, while the {@link org.apache.lucene.analysis.Tokenizer}
73
is only responsible for <u>breaking</u> the input text into tokens. Very likely, tokens created
74
by the {@link org.apache.lucene.analysis.Tokenizer} would be modified or even omitted
75
by the {@link org.apache.lucene.analysis.Analyzer} (via one or more
76
{@link org.apache.lucene.analysis.TokenFilter}s) before being returned.
78
<li>{@link org.apache.lucene.analysis.Tokenizer} is a {@link org.apache.lucene.analysis.TokenStream},
79
but {@link org.apache.lucene.analysis.Analyzer} is not.
81
<li>{@link org.apache.lucene.analysis.Analyzer} is "field aware", but
82
{@link org.apache.lucene.analysis.Tokenizer} is not.
87
Lucene Java provides a number of analysis capabilities, the most commonly used one being the {@link
88
org.apache.lucene.analysis.standard.StandardAnalyzer}. Many applications will have a long and industrious life with nothing more
89
than the StandardAnalyzer. However, there are a few other classes/packages that are worth mentioning:
91
<li>{@link org.apache.lucene.analysis.PerFieldAnalyzerWrapper} – Most Analyzers perform the same operation on all
92
{@link org.apache.lucene.document.Field}s. The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different
93
{@link org.apache.lucene.document.Field}s.</li>
94
<li>The contrib/analyzers library located at the root of the Lucene distribution has a number of different Analyzer implementations to solve a variety
95
of different problems related to searching. Many of the Analyzers are designed to analyze non-English languages.</li>
96
<li>The {@link org.apache.lucene.analysis.snowball contrib/snowball library}
97
located at the root of the Lucene distribution has Analyzer and TokenFilter
98
implementations for a variety of Snowball stemmers.
99
See <a href="http://snowball.tartarus.org">http://snowball.tartarus.org</a>
100
for more information on Snowball stemmers.</li>
101
<li>There are a variety of Tokenizer and TokenFilter implementations in this package. Take a look around, chances are someone has implemented what you need.</li>
105
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).
106
Perhaps your application would be just fine using the simple {@link org.apache.lucene.analysis.WhitespaceTokenizer} combined with a
107
{@link org.apache.lucene.analysis.StopFilter}. The contrib/benchmark library can be useful for testing out the speed of the analysis process.
109
<h2>Invoking the Analyzer</h2>
111
Applications usually do not invoke analysis – Lucene does it for them:
113
<li>At indexing, as a consequence of
114
{@link org.apache.lucene.index.IndexWriter#addDocument(org.apache.lucene.document.Document) addDocument(doc)},
115
the Analyzer in effect for indexing is invoked for each indexed field of the added document.
117
<li>At search, as a consequence of
118
{@link org.apache.lucene.queryParser.QueryParser#parse(java.lang.String) QueryParser.parse(queryText)},
119
the QueryParser may invoke the Analyzer in effect.
120
Note that for some queries analysis does not take place, e.g. wildcard queries.
123
However an application might invoke Analysis of any text for testing or for any other purpose, something like:
125
Analyzer analyzer = new StandardAnalyzer(); // or any other analyzer
126
TokenStream ts = analyzer.tokenStream("myfield",new StringReader("some text goes here"));
129
System.out.println("token: "+t));
134
<h2>Indexing Analysis vs. Search Analysis</h2>
136
Selecting the "correct" analyzer is crucial
137
for search quality, and can also affect indexing and search performance.
138
The "correct" analyzer differs between applications.
139
Lucene java's wiki page
140
<a href="http://wiki.apache.org/lucene-java/AnalysisParalysis">AnalysisParalysis</a>
141
provides some data on "analyzing your analyzer".
142
Here are some rules of thumb:
144
<li>Test test test... (did we say test?)</li>
145
<li>Beware of over analysis – might hurt indexing performance.</li>
146
<li>Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...</li>
147
<li>In some cases a different analyzer is required for indexing and search, for instance:
149
<li>Certain searches require more stop words to be filtered. (I.e. more than those that were filtered at indexing.)</li>
150
<li>Query expansion by synonyms, acronyms, auto spell correction, etc.</li>
152
This might sometimes require a modified analyzer – see the next section on how to do that.
156
<h2>Implementing your own Analyzer</h2>
157
<p>Creating your own Analyzer is straightforward. It usually involves either wrapping an existing Tokenizer and set of TokenFilters to create a new Analyzer
158
or creating both the Analyzer and a Tokenizer or TokenFilter. Before pursuing this approach, you may find it worthwhile
159
to explore the contrib/analyzers library and/or ask on the java-user@lucene.apache.org mailing list first to see if what you need already exists.
160
If you are still committed to creating your own Analyzer or TokenStream derivation (Tokenizer or TokenFilter) have a look at
161
the source code of any one of the many samples located in this package.
164
The following sections discuss some aspects of implementing your own analyzer.
166
<h3>Field Section Boundaries</h2>
168
When {@link org.apache.lucene.document.Document#add(org.apache.lucene.document.Fieldable) document.add(field)}
169
is called multiple times for the same field name, we could say that each such call creates a new
170
section for that field in that document.
171
In fact, a separate call to
172
{@link org.apache.lucene.analysis.Analyzer#tokenStream(java.lang.String, java.io.Reader) tokenStream(field,reader)}
173
would take place for each of these so called "sections".
174
However, the default Analyzer behavior is to treat all these sections as one large section.
175
This allows phrase search and proximity search to seamlessly cross
176
boundaries between these "sections".
177
In other words, if a certain field "f" is added like this:
179
document.add(new Field("f","first ends",...);
180
document.add(new Field("f","starts two",...);
181
indexWriter.addDocument(document);
183
Then, a phrase search for "ends starts" would find that document.
184
Where desired, this behavior can be modified by introducing a "position gap" between consecutive field "sections",
186
{@link org.apache.lucene.analysis.Analyzer#getPositionIncrementGap(java.lang.String) Analyzer.getPositionIncrementGap(fieldName)}:
188
Analyzer myAnalyzer = new StandardAnalyzer() {
189
public int getPositionIncrementGap(String fieldName) {
195
<h3>Token Position Increments</h2>
197
By default, all tokens created by Analyzers and Tokenizers have a
198
{@link org.apache.lucene.analysis.Token#getPositionIncrement() position increment} of one.
199
This means that the position stored for that token in the index would be one more than
200
that of the previous token.
201
Recall that phrase and proximity searches rely on position info.
204
If the selected analyzer filters the stop words "is" and "the", then for a document
205
containing the string "blue is the sky", only the tokens "blue", "sky" are indexed,
206
with position("sky") = 1 + position("blue"). Now, a phrase query "blue is the sky"
207
would find that document, because the same analyzer filters the same stop words from
208
that query. But also the phrase query "blue sky" would find that document.
211
If this behavior does not fit the application needs,
212
a modified analyzer can be used, that would increment further the positions of
213
tokens following a removed stop word, using
214
{@link org.apache.lucene.analysis.Token#setPositionIncrement(int)}.
215
This can be done with something like:
217
public TokenStream tokenStream(final String fieldName, Reader reader) {
218
final TokenStream ts = someAnalyzer.tokenStream(fieldName, reader);
219
TokenStream res = new TokenStream() {
220
public Token next() throws IOException {
221
int extraIncrement = 0;
225
if (stopWords.contains(t.termText())) {
226
extraIncrement++; // filter this word
229
if (extraIncrement>0) {
230
t.setPositionIncrement(t.getPositionIncrement()+extraIncrement);
240
Now, with this modified analyzer, the phrase query "blue sky" would find that document.
241
But note that this is yet not a perfect solution, because any phrase query "blue w1 w2 sky"
242
where both w1 and w2 are stop words would match that document.
245
Few more use cases for modifying position increments are:
247
<li>Inhibiting phrase and proximity matches in sentence boundaries – for this, a tokenizer that
248
identifies a new sentence can add 1 to the position increment of the first token of the new sentence.</li>
249
<li>Injecting synonyms – here, synonyms of a token should be added after that token,
250
and their position increment should be set to 0.
251
As result, all synonyms of a token would be considered to appear in exactly the
252
same position as that token, and so would they be seen by phrase and proximity searches.</li>