~ubuntu-branches/ubuntu/trusty/pylucene/trusty

« back to all changes in this revision

Viewing changes to lucene-java-2.3.1/src/java/org/apache/lucene/analysis/package.html

  • Committer: Package Import Robot
  • Author(s): Dmitry Nezhevenko
  • Date: 2012-04-23 16:43:55 UTC
  • mfrom: (1.1.1)
  • Revision ID: package-import@ubuntu.com-20120423164355-grqtepnwtecdjfk2
Tags: 3.5.0-1
* New maintainer (closes: 670179)
* New upstream release
* Switch to dpkg-source 3.0 (quilt) format
* Switch to machine-readable debian/copyright
* Bump debian/compat to 8, drop debian/pycompat
* Switch from cdbs to dh
* Add watch file
* Build for all supported versions of python2 (closes: 581198, 632240)
* Rename binary package to python-lucene (closes: 581197)
* Add -dbg package

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
2
 
<html>
3
 
<head>
4
 
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
 
   <meta name="Author" content="Doug Cutting">
6
 
</head>
7
 
<body>
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>
10
 
<p>
11
 
Lucene, indexing and search library, accepts only plain text input.
12
 
<p>
13
 
<h2>Parsing</h2>
14
 
<p>
15
 
Applications that build their search capabilities upon Lucene may support documents in various formats &ndash; HTML, XML, PDF, Word &ndash; 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.
18
 
<p>
19
 
<h2>Tokenization</h2>
20
 
<p>
21
 
Plain text passed to Lucene for indexing goes through a process generally called tokenization &ndash; namely breaking of the 
22
 
input text into small indexing elements &ndash; 
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).
28
 
<p>
29
 
In some cases simply breaking the input text into tokens is not enough &ndash; a deeper <i>Analysis</i> is needed,
30
 
providing for several functions, including (but not limited to):
31
 
<ul>
32
 
  <li><a href="http://en.wikipedia.org/wiki/Stemming">Stemming</a> &ndash; 
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".
36
 
  </li>
37
 
  <li><a href="http://en.wikipedia.org/wiki/Stop_words">Stop Words Filtering</a> &ndash; 
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.
41
 
  </li>
42
 
  <li><a href="http://en.wikipedia.org/wiki/Text_normalization">Text Normalization</a> &ndash; 
43
 
      Stripping accents and other character markings can make for better searching.
44
 
  </li>
45
 
  <li><a href="http://en.wikipedia.org/wiki/Synonym">Synonym Expansion</a> &ndash; 
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.
48
 
  </li>
49
 
</ul> 
50
 
<p>
51
 
<h2>Core Analysis</h2>
52
 
<p>
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:
55
 
  <ul>
56
 
    <li>{@link org.apache.lucene.analysis.Analyzer} &ndash; 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} &ndash; 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} &ndash; 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>
64
 
  </ul>
65
 
</p>
66
 
<h2>Hints, Tips and Traps</h2>
67
 
<p>
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:
70
 
   <ul>
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.
77
 
       </li>
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.
80
 
       </li>
81
 
       <li>{@link org.apache.lucene.analysis.Analyzer} is "field aware", but 
82
 
           {@link org.apache.lucene.analysis.Tokenizer} is not.
83
 
       </li>
84
 
   </ul>
85
 
</p>
86
 
<p>
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:
90
 
  <ol>
91
 
    <li>{@link org.apache.lucene.analysis.PerFieldAnalyzerWrapper} &ndash; 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>
102
 
  </ol>
103
 
</p>
104
 
<p>
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.
108
 
</p>
109
 
<h2>Invoking the Analyzer</h2>
110
 
<p>
111
 
  Applications usually do not invoke analysis &ndash; Lucene does it for them:
112
 
  <ul>
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.
116
 
    </li>
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.
121
 
    </li>
122
 
  </ul>
123
 
  However an application might invoke Analysis of any text for testing or for any other purpose, something like:
124
 
  <PRE>
125
 
      Analyzer analyzer = new StandardAnalyzer(); // or any other analyzer
126
 
      TokenStream ts = analyzer.tokenStream("myfield",new StringReader("some text goes here"));
127
 
      Token t = ts.next();
128
 
      while (t!=null) {
129
 
        System.out.println("token: "+t));
130
 
        t = ts.next();
131
 
      }
132
 
  </PRE>
133
 
</p>
134
 
<h2>Indexing Analysis vs. Search Analysis</h2>
135
 
<p>
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:
143
 
  <ol>
144
 
    <li>Test test test... (did we say test?)</li>
145
 
    <li>Beware of over analysis &ndash; 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:
148
 
        <ul>
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>
151
 
        </ul>
152
 
        This might sometimes require a modified analyzer &ndash; see the next section on how to do that.
153
 
    </li>
154
 
  </ol>
155
 
</p>
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.
162
 
</p>
163
 
<p>
164
 
  The following sections discuss some aspects of implementing your own analyzer.
165
 
</p>
166
 
<h3>Field Section Boundaries</h2>
167
 
<p>
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:
178
 
  <PRE>
179
 
      document.add(new Field("f","first ends",...);
180
 
      document.add(new Field("f","starts two",...);
181
 
      indexWriter.addDocument(document);
182
 
  </PRE>
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", 
185
 
  simply by overriding 
186
 
  {@link org.apache.lucene.analysis.Analyzer#getPositionIncrementGap(java.lang.String) Analyzer.getPositionIncrementGap(fieldName)}:
187
 
  <PRE>
188
 
      Analyzer myAnalyzer = new StandardAnalyzer() {
189
 
         public int getPositionIncrementGap(String fieldName) {
190
 
           return 10;
191
 
         }
192
 
      };
193
 
  </PRE>
194
 
</p>
195
 
<h3>Token Position Increments</h2>
196
 
<p>
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.
202
 
</p>
203
 
<p>
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.
209
 
</p>
210
 
<p>   
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:
216
 
   <PRE>
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;
222
 
            while (true) {
223
 
              Token t = ts.next();
224
 
              if (t!=null) {
225
 
                if (stopWords.contains(t.termText())) {
226
 
                  extraIncrement++; // filter this word
227
 
                  continue;
228
 
                } 
229
 
                if (extraIncrement>0) {
230
 
                  t.setPositionIncrement(t.getPositionIncrement()+extraIncrement);
231
 
                }
232
 
              }
233
 
              return t;
234
 
            }
235
 
          }
236
 
        };
237
 
        return res;
238
 
      }
239
 
   </PRE>
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.
243
 
</p>
244
 
<p>
245
 
   Few more use cases for modifying position increments are:
246
 
   <ol>
247
 
     <li>Inhibiting phrase and proximity matches in sentence boundaries &ndash; 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 &ndash; 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>
253
 
   </ol>
254
 
</p>
255
 
</body>
256
 
</html>