add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / src / java / org / apache / lucene / analysis / package.html
1 <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
2 <!--
3  Licensed to the Apache Software Foundation (ASF) under one or more
4  contributor license agreements.  See the NOTICE file distributed with
5  this work for additional information regarding copyright ownership.
6  The ASF licenses this file to You under the Apache License, Version 2.0
7  (the "License"); you may not use this file except in compliance with
8  the License.  You may obtain a copy of the License at
9
10      http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  See the License for the specific language governing permissions and
16  limitations under the License.
17 -->
18 <html>
19 <head>
20    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
21 </head>
22 <body>
23 <p>API and code to convert text into indexable/searchable tokens.  Covers {@link org.apache.lucene.analysis.Analyzer} and related classes.</p>
24 <h2>Parsing? Tokenization? Analysis!</h2>
25 <p>
26 Lucene, indexing and search library, accepts only plain text input.
27 <p>
28 <h2>Parsing</h2>
29 <p>
30 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.
31 Lucene does not care about the <i>Parsing</i> of these and other document formats, and it is the responsibility of the 
32 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.
33 <p>
34 <h2>Tokenization</h2>
35 <p>
36 Plain text passed to Lucene for indexing goes through a process generally called tokenization. Tokenization is the process
37 of breaking input text into small indexing elements &ndash; tokens.
38 The way input text is broken into tokens heavily influences how people will then be able to search for that text. 
39 For instance, sentences beginnings and endings can be identified to provide for more accurate phrase 
40 and proximity searches (though sentence identification is not provided by Lucene).
41 <p>
42 In some cases simply breaking the input text into tokens is not enough &ndash; a deeper <i>Analysis</i> may be needed.
43 There are many post tokenization steps that can be done, including (but not limited to):
44 <ul>
45   <li><a href="http://en.wikipedia.org/wiki/Stemming">Stemming</a> &ndash; 
46       Replacing of words by their stems. 
47       For instance with English stemming "bikes" is replaced by "bike"; 
48       now query "bike" can find both documents containing "bike" and those containing "bikes".
49   </li>
50   <li><a href="http://en.wikipedia.org/wiki/Stop_words">Stop Words Filtering</a> &ndash; 
51       Common words like "the", "and" and "a" rarely add any value to a search.
52       Removing them shrinks the index size and increases performance.
53       It may also reduce some "noise" and actually improve search quality.
54   </li>
55   <li><a href="http://en.wikipedia.org/wiki/Text_normalization">Text Normalization</a> &ndash; 
56       Stripping accents and other character markings can make for better searching.
57   </li>
58   <li><a href="http://en.wikipedia.org/wiki/Synonym">Synonym Expansion</a> &ndash; 
59       Adding in synonyms at the same token position as the current word can mean better 
60       matching when users search with words in the synonym set.
61   </li>
62 </ul> 
63 <p>
64 <h2>Core Analysis</h2>
65 <p>
66   The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene.  There
67   are three main classes in the package from which all analysis processes are derived.  These are:
68   <ul>
69     <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
70     by the indexing and searching processes.  See below for more information on implementing your own Analyzer.</li>
71     <li>{@link org.apache.lucene.analysis.Tokenizer} &ndash; A Tokenizer is a {@link org.apache.lucene.analysis.TokenStream} and is responsible for breaking
72     up incoming text into tokens. In most cases, an Analyzer will use a Tokenizer as the first step in
73     the analysis process.</li>
74     <li>{@link org.apache.lucene.analysis.TokenFilter} &ndash; A TokenFilter is also a {@link org.apache.lucene.analysis.TokenStream} and is responsible
75     for modifying tokens that have been created by the Tokenizer.  Common modifications performed by a
76     TokenFilter are: deletion, stemming, synonym injection, and down casing.  Not all Analyzers require TokenFilters</li>
77   </ul>
78   <b>Lucene 2.9 introduces a new TokenStream API. Please see the section "New TokenStream API" below for more details.</b>
79 </p>
80 <h2>Hints, Tips and Traps</h2>
81 <p>
82    The synergy between {@link org.apache.lucene.analysis.Analyzer} and {@link org.apache.lucene.analysis.Tokenizer}
83    is sometimes confusing. To ease on this confusion, some clarifications:
84    <ul>
85       <li>The {@link org.apache.lucene.analysis.Analyzer} is responsible for the entire task of 
86           <u>creating</u> tokens out of the input text, while the {@link org.apache.lucene.analysis.Tokenizer}
87           is only responsible for <u>breaking</u> the input text into tokens. Very likely, tokens created 
88           by the {@link org.apache.lucene.analysis.Tokenizer} would be modified or even omitted 
89           by the {@link org.apache.lucene.analysis.Analyzer} (via one or more
90           {@link org.apache.lucene.analysis.TokenFilter}s) before being returned.
91        </li>
92        <li>{@link org.apache.lucene.analysis.Tokenizer} is a {@link org.apache.lucene.analysis.TokenStream}, 
93            but {@link org.apache.lucene.analysis.Analyzer} is not.
94        </li>
95        <li>{@link org.apache.lucene.analysis.Analyzer} is "field aware", but 
96            {@link org.apache.lucene.analysis.Tokenizer} is not.
97        </li>
98    </ul>
99 </p>
100 <p>
101   Lucene Java provides a number of analysis capabilities, the most commonly used one being the {@link
102   org.apache.lucene.analysis.standard.StandardAnalyzer}.  Many applications will have a long and industrious life with nothing more
103   than the StandardAnalyzer.  However, there are a few other classes/packages that are worth mentioning:
104   <ol>
105     <li>{@link org.apache.lucene.analysis.PerFieldAnalyzerWrapper} &ndash; Most Analyzers perform the same operation on all
106       {@link org.apache.lucene.document.Field}s.  The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different
107       {@link org.apache.lucene.document.Field}s.</li>
108     <li>The contrib/analyzers library located at the root of the Lucene distribution has a number of different Analyzer implementations to solve a variety
109     of different problems related to searching.  Many of the Analyzers are designed to analyze non-English languages.</li>
110     <li>The contrib/snowball library 
111         located at the root of the Lucene distribution has Analyzer and TokenFilter 
112         implementations for a variety of Snowball stemmers.  
113         See <a href="http://snowball.tartarus.org">http://snowball.tartarus.org</a> 
114         for more information on Snowball stemmers.</li>
115     <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>
116   </ol>
117 </p>
118 <p>
119   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).
120   Perhaps your application would be just fine using the simple {@link org.apache.lucene.analysis.WhitespaceTokenizer} combined with a
121   {@link org.apache.lucene.analysis.StopFilter}. The contrib/benchmark library can be useful for testing out the speed of the analysis process.
122 </p>
123 <h2>Invoking the Analyzer</h2>
124 <p>
125   Applications usually do not invoke analysis &ndash; Lucene does it for them:
126   <ul>
127     <li>At indexing, as a consequence of 
128         {@link org.apache.lucene.index.IndexWriter#addDocument(org.apache.lucene.document.Document) addDocument(doc)},
129         the Analyzer in effect for indexing is invoked for each indexed field of the added document.
130     </li>
131     <li>At search, as a consequence of
132         {@link org.apache.lucene.queryParser.QueryParser#parse(java.lang.String) QueryParser.parse(queryText)},
133         the QueryParser may invoke the Analyzer in effect.
134         Note that for some queries analysis does not take place, e.g. wildcard queries.
135     </li>
136   </ul>
137   However an application might invoke Analysis of any text for testing or for any other purpose, something like:
138   <PRE class="prettyprint">
139       Analyzer analyzer = new StandardAnalyzer(); // or any other analyzer
140       TokenStream ts = analyzer.tokenStream("myfield",new StringReader("some text goes here"));
141       while (ts.incrementToken()) {
142         System.out.println("token: "+ts));
143       }
144   </PRE>
145 </p>
146 <h2>Indexing Analysis vs. Search Analysis</h2>
147 <p>
148   Selecting the "correct" analyzer is crucial
149   for search quality, and can also affect indexing and search performance.
150   The "correct" analyzer differs between applications.
151   Lucene java's wiki page 
152   <a href="http://wiki.apache.org/lucene-java/AnalysisParalysis">AnalysisParalysis</a> 
153   provides some data on "analyzing your analyzer".
154   Here are some rules of thumb:
155   <ol>
156     <li>Test test test... (did we say test?)</li>
157     <li>Beware of over analysis &ndash; might hurt indexing performance.</li>
158     <li>Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...</li>
159     <li>In some cases a different analyzer is required for indexing and search, for instance:
160         <ul>
161            <li>Certain searches require more stop words to be filtered. (I.e. more than those that were filtered at indexing.)</li>
162            <li>Query expansion by synonyms, acronyms, auto spell correction, etc.</li>
163         </ul>
164         This might sometimes require a modified analyzer &ndash; see the next section on how to do that.
165     </li>
166   </ol>
167 </p>
168 <h2>Implementing your own Analyzer</h2>
169 <p>Creating your own Analyzer is straightforward. It usually involves either wrapping an existing Tokenizer and  set of TokenFilters to create a new Analyzer
170 or creating both the Analyzer and a Tokenizer or TokenFilter.  Before pursuing this approach, you may find it worthwhile
171 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.
172 If you are still committed to creating your own Analyzer or TokenStream derivation (Tokenizer or TokenFilter) have a look at
173 the source code of any one of the many samples located in this package.
174 </p>
175 <p>
176   The following sections discuss some aspects of implementing your own analyzer.
177 </p>
178 <h3>Field Section Boundaries</h3>
179 <p>
180   When {@link org.apache.lucene.document.Document#add(org.apache.lucene.document.Fieldable) document.add(field)}
181   is called multiple times for the same field name, we could say that each such call creates a new 
182   section for that field in that document. 
183   In fact, a separate call to 
184   {@link org.apache.lucene.analysis.Analyzer#tokenStream(java.lang.String, java.io.Reader) tokenStream(field,reader)}
185   would take place for each of these so called "sections".
186   However, the default Analyzer behavior is to treat all these sections as one large section. 
187   This allows phrase search and proximity search to seamlessly cross 
188   boundaries between these "sections".
189   In other words, if a certain field "f" is added like this:
190   <PRE class="prettyprint">
191       document.add(new Field("f","first ends",...);
192       document.add(new Field("f","starts two",...);
193       indexWriter.addDocument(document);
194   </PRE>
195   Then, a phrase search for "ends starts" would find that document.
196   Where desired, this behavior can be modified by introducing a "position gap" between consecutive field "sections", 
197   simply by overriding 
198   {@link org.apache.lucene.analysis.Analyzer#getPositionIncrementGap(java.lang.String) Analyzer.getPositionIncrementGap(fieldName)}:
199   <PRE class="prettyprint">
200       Analyzer myAnalyzer = new StandardAnalyzer() {
201          public int getPositionIncrementGap(String fieldName) {
202            return 10;
203          }
204       };
205   </PRE>
206 </p>
207 <h3>Token Position Increments</h3>
208 <p>
209    By default, all tokens created by Analyzers and Tokenizers have a 
210    {@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute#getPositionIncrement() position increment} of one.
211    This means that the position stored for that token in the index would be one more than
212    that of the previous token.
213    Recall that phrase and proximity searches rely on position info.
214 </p>
215 <p>
216    If the selected analyzer filters the stop words "is" and "the", then for a document 
217    containing the string "blue is the sky", only the tokens "blue", "sky" are indexed, 
218    with position("sky") = 1 + position("blue"). Now, a phrase query "blue is the sky"
219    would find that document, because the same analyzer filters the same stop words from
220    that query. But also the phrase query "blue sky" would find that document.
221 </p>
222 <p>   
223    If this behavior does not fit the application needs,
224    a modified analyzer can be used, that would increment further the positions of
225    tokens following a removed stop word, using
226    {@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute#setPositionIncrement(int)}.
227    This can be done with something like:
228    <PRE class="prettyprint">
229       public TokenStream tokenStream(final String fieldName, Reader reader) {
230         final TokenStream ts = someAnalyzer.tokenStream(fieldName, reader);
231         TokenStream res = new TokenStream() {
232           TermAttribute termAtt = addAttribute(TermAttribute.class);
233           PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
234         
235           public boolean incrementToken() throws IOException {
236             int extraIncrement = 0;
237             while (true) {
238               boolean hasNext = ts.incrementToken();
239               if (hasNext) {
240                 if (stopWords.contains(termAtt.term())) {
241                   extraIncrement++; // filter this word
242                   continue;
243                 } 
244                 if (extraIncrement>0) {
245                   posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement()+extraIncrement);
246                 }
247               }
248               return hasNext;
249             }
250           }
251         };
252         return res;
253       }
254    </PRE>
255    Now, with this modified analyzer, the phrase query "blue sky" would find that document.
256    But note that this is yet not a perfect solution, because any phrase query "blue w1 w2 sky"
257    where both w1 and w2 are stop words would match that document.
258 </p>
259 <p>
260    Few more use cases for modifying position increments are:
261    <ol>
262      <li>Inhibiting phrase and proximity matches in sentence boundaries &ndash; for this, a tokenizer that 
263          identifies a new sentence can add 1 to the position increment of the first token of the new sentence.</li>
264      <li>Injecting synonyms &ndash; here, synonyms of a token should be added after that token, 
265          and their position increment should be set to 0.
266          As result, all synonyms of a token would be considered to appear in exactly the 
267          same position as that token, and so would they be seen by phrase and proximity searches.</li>
268    </ol>
269 </p>
270 <h2>New TokenStream API</h2>
271 <p>
272         With Lucene 2.9 we introduce a new TokenStream API. The old API used to produce Tokens. A Token
273         has getter and setter methods for different properties like positionIncrement and termText.
274         While this approach was sufficient for the default indexing format, it is not versatile enough for
275         Flexible Indexing, a term which summarizes the effort of making the Lucene indexer pluggable and extensible for custom
276         index formats.
277 </p>
278 <p>
279 A fully customizable indexer means that users will be able to store custom data structures on disk. Therefore an API
280 is necessary that can transport custom types of data from the documents to the indexer.
281 </p>
282 <h3>Attribute and AttributeSource</h3> 
283 Lucene 2.9 therefore introduces a new pair of classes called {@link org.apache.lucene.util.Attribute} and
284 {@link org.apache.lucene.util.AttributeSource}. An Attribute serves as a
285 particular piece of information about a text token. For example, {@link org.apache.lucene.analysis.tokenattributes.TermAttribute}
286  contains the term text of a token, and {@link org.apache.lucene.analysis.tokenattributes.OffsetAttribute} contains the start and end character offsets of a token.
287 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
288 means that one can add Attributes to a TokenStream. Since TokenFilter extends TokenStream, all filters are also
289 AttributeSources.
290 <p>
291         Lucene now provides six Attributes out of the box, which replace the variables the Token class has:
292         <ul>
293           <li>{@link org.apache.lucene.analysis.tokenattributes.TermAttribute}<p>The term text of a token.</p></li>
294           <li>{@link org.apache.lucene.analysis.tokenattributes.OffsetAttribute}<p>The start and end offset of token in characters.</p></li>
295           <li>{@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute}<p>See above for detailed information about position increment.</p></li>
296           <li>{@link org.apache.lucene.analysis.tokenattributes.PayloadAttribute}<p>The payload that a Token can optionally have.</p></li>
297           <li>{@link org.apache.lucene.analysis.tokenattributes.TypeAttribute}<p>The type of the token. Default is 'word'.</p></li>
298           <li>{@link org.apache.lucene.analysis.tokenattributes.FlagsAttribute}<p>Optional flags a token can have.</p></li>
299         </ul>
300 </p>
301 <h3>Using the new TokenStream API</h3>
302 There are a few important things to know in order to use the new API efficiently which are summarized here. You may want
303 to walk through the example below first and come back to this section afterwards.
304 <ol><li>
305 Please keep in mind that an AttributeSource can only have one instance of a particular Attribute. Furthermore, if 
306 a chain of a TokenStream and multiple TokenFilters is used, then all TokenFilters in that chain share the Attributes
307 with the TokenStream.
308 </li>
309 <br>
310 <li>
311 Attribute instances are reused for all tokens of a document. Thus, a TokenStream/-Filter needs to update
312 the appropriate Attribute(s) in incrementToken(). The consumer, commonly the Lucene indexer, consumes the data in the
313 Attributes and then calls incrementToken() again until it returns false, which indicates that the end of the stream
314 was reached. This means that in each call of incrementToken() a TokenStream/-Filter can safely overwrite the data in
315 the Attribute instances.
316 </li>
317 <br>
318 <li>
319 For performance reasons a TokenStream/-Filter should add/get Attributes during instantiation; i.e., create an attribute in the
320 constructor and store references to it in an instance variable.  Using an instance variable instead of calling addAttribute()/getAttribute() 
321 in incrementToken() will avoid attribute lookups for every token in the document.
322 </li>
323 <br>
324 <li>
325 All methods in AttributeSource are idempotent, which means calling them multiple times always yields the same
326 result. This is especially important to know for addAttribute(). The method takes the <b>type</b> (<code>Class</code>)
327 of an Attribute as an argument and returns an <b>instance</b>. If an Attribute of the same type was previously added, then
328 the already existing instance is returned, otherwise a new instance is created and returned. Therefore TokenStreams/-Filters
329 can safely call addAttribute() with the same Attribute type multiple times. Even consumers of TokenStreams should
330 normally call addAttribute() instead of getAttribute(), because it would not fail if the TokenStream does not have this
331 Attribute (getAttribute() would throw an IllegalArgumentException, if the Attribute is missing). More advanced code
332 could simply check with hasAttribute(), if a TokenStream has it, and may conditionally leave out processing for
333 extra performance.
334 </li></ol>
335 <h3>Example</h3>
336 In this example we will create a WhiteSpaceTokenizer and use a LengthFilter to suppress all words that only
337 have two or less characters. The LengthFilter is part of the Lucene core and its implementation will be explained
338 here to illustrate the usage of the new TokenStream API.<br>
339 Then we will develop a custom Attribute, a PartOfSpeechAttribute, and add another filter to the chain which
340 utilizes the new custom attribute, and call it PartOfSpeechTaggingFilter.
341 <h4>Whitespace tokenization</h4>
342 <pre class="prettyprint">
343 public class MyAnalyzer extends Analyzer {
344
345   public TokenStream tokenStream(String fieldName, Reader reader) {
346     TokenStream stream = new WhitespaceTokenizer(reader);
347     return stream;
348   }
349   
350   public static void main(String[] args) throws IOException {
351     // text to tokenize
352     final String text = "This is a demo of the new TokenStream API";
353     
354     MyAnalyzer analyzer = new MyAnalyzer();
355     TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
356     
357     // get the TermAttribute from the TokenStream
358     TermAttribute termAtt = stream.addAttribute(TermAttribute.class);
359
360     stream.reset();
361     
362     // print all tokens until stream is exhausted
363     while (stream.incrementToken()) {
364       System.out.println(termAtt.term());
365     }
366     
367     stream.end()
368     stream.close();
369   }
370 }
371 </pre>
372 In this easy example a simple white space tokenization is performed. In main() a loop consumes the stream and
373 prints the term text of the tokens by accessing the TermAttribute that the WhitespaceTokenizer provides. 
374 Here is the output:
375 <pre>
376 This
377 is
378 a
379 demo
380 of
381 the
382 new
383 TokenStream
384 API
385 </pre>
386 <h4>Adding a LengthFilter</h4>
387 We want to suppress all tokens that have 2 or less characters. We can do that easily by adding a LengthFilter 
388 to the chain. Only the tokenStream() method in our analyzer needs to be changed:
389 <pre class="prettyprint">
390   public TokenStream tokenStream(String fieldName, Reader reader) {
391     TokenStream stream = new WhitespaceTokenizer(reader);
392     stream = new LengthFilter(stream, 3, Integer.MAX_VALUE);
393     return stream;
394   }
395 </pre>
396 Note how now only words with 3 or more characters are contained in the output:
397 <pre>
398 This
399 demo
400 the
401 new
402 TokenStream
403 API
404 </pre>
405 Now let's take a look how the LengthFilter is implemented (it is part of Lucene's core):
406 <pre class="prettyprint">
407 public final class LengthFilter extends TokenFilter {
408
409   final int min;
410   final int max;
411   
412   private TermAttribute termAtt;
413
414   /**
415    * Build a filter that removes words that are too long or too
416    * short from the text.
417    */
418   public LengthFilter(TokenStream in, int min, int max)
419   {
420     super(in);
421     this.min = min;
422     this.max = max;
423     termAtt = addAttribute(TermAttribute.class);
424   }
425   
426   /**
427    * Returns the next input Token whose term() is the right len
428    */
429   public final boolean incrementToken() throws IOException
430   {
431     assert termAtt != null;
432     // return the first non-stop word found
433     while (input.incrementToken()) {
434       int len = termAtt.termLength();
435       if (len >= min && len <= max) {
436           return true;
437       }
438       // note: else we ignore it but should we index each part of it?
439     }
440     // reached EOS -- return null
441     return false;
442   }
443 }
444 </pre>
445 The TermAttribute is added in the constructor and stored in the instance variable <code>termAtt</code>.
446 Remember that there can only be a single instance of TermAttribute in the chain, so in our example the 
447 <code>addAttribute()</code> call in LengthFilter returns the TermAttribute that the WhitespaceTokenizer already added. The tokens
448 are retrieved from the input stream in the <code>incrementToken()</code> method. By looking at the term text
449 in the TermAttribute the length of the term can be determined and too short or too long tokens are skipped. 
450 Note how <code>incrementToken()</code> can efficiently access the instance variable; no attribute lookup
451 is neccessary. The same is true for the consumer, which can simply use local references to the Attributes.
452
453 <h4>Adding a custom Attribute</h4>
454 Now we're going to implement our own custom Attribute for part-of-speech tagging and call it consequently 
455 <code>PartOfSpeechAttribute</code>. First we need to define the interface of the new Attribute:
456 <pre class="prettyprint">
457   public interface PartOfSpeechAttribute extends Attribute {
458     public static enum PartOfSpeech {
459       Noun, Verb, Adjective, Adverb, Pronoun, Preposition, Conjunction, Article, Unknown
460     }
461   
462     public void setPartOfSpeech(PartOfSpeech pos);
463   
464     public PartOfSpeech getPartOfSpeech();
465   }
466 </pre>
467
468 Now we also need to write the implementing class. The name of that class is important here: By default, Lucene
469 checks if there is a class with the name of the Attribute with the postfix 'Impl'. In this example, we would
470 consequently call the implementing class <code>PartOfSpeechAttributeImpl</code>. <br/>
471 This should be the usual behavior. However, there is also an expert-API that allows changing these naming conventions:
472 {@link org.apache.lucene.util.AttributeSource.AttributeFactory}. The factory accepts an Attribute interface as argument
473 and returns an actual instance. You can implement your own factory if you need to change the default behavior. <br/><br/>
474
475 Now here is the actual class that implements our new Attribute. Notice that the class has to extend
476 {@link org.apache.lucene.util.AttributeImpl}:
477
478 <pre class="prettyprint">
479 public final class PartOfSpeechAttributeImpl extends AttributeImpl 
480                             implements PartOfSpeechAttribute{
481   
482   private PartOfSpeech pos = PartOfSpeech.Unknown;
483   
484   public void setPartOfSpeech(PartOfSpeech pos) {
485     this.pos = pos;
486   }
487   
488   public PartOfSpeech getPartOfSpeech() {
489     return pos;
490   }
491
492   public void clear() {
493     pos = PartOfSpeech.Unknown;
494   }
495
496   public void copyTo(AttributeImpl target) {
497     ((PartOfSpeechAttributeImpl) target).pos = pos;
498   }
499
500   public boolean equals(Object other) {
501     if (other == this) {
502       return true;
503     }
504     
505     if (other instanceof PartOfSpeechAttributeImpl) {
506       return pos == ((PartOfSpeechAttributeImpl) other).pos;
507     }
508  
509     return false;
510   }
511
512   public int hashCode() {
513     return pos.ordinal();
514   }
515 }
516 </pre>
517 This is a simple Attribute implementation has only a single variable that stores the part-of-speech of a token. It extends the
518 new <code>AttributeImpl</code> class and therefore implements its abstract methods <code>clear(), copyTo(), equals(), hashCode()</code>.
519 Now we need a TokenFilter that can set this new PartOfSpeechAttribute for each token. In this example we show a very naive filter
520 that tags every word with a leading upper-case letter as a 'Noun' and all other words as 'Unknown'.
521 <pre class="prettyprint">
522   public static class PartOfSpeechTaggingFilter extends TokenFilter {
523     PartOfSpeechAttribute posAtt;
524     TermAttribute termAtt;
525     
526     protected PartOfSpeechTaggingFilter(TokenStream input) {
527       super(input);
528       posAtt = addAttribute(PartOfSpeechAttribute.class);
529       termAtt = addAttribute(TermAttribute.class);
530     }
531     
532     public boolean incrementToken() throws IOException {
533       if (!input.incrementToken()) {return false;}
534       posAtt.setPartOfSpeech(determinePOS(termAtt.termBuffer(), 0, termAtt.termLength()));
535       return true;
536     }
537     
538     // determine the part of speech for the given term
539     protected PartOfSpeech determinePOS(char[] term, int offset, int length) {
540       // naive implementation that tags every uppercased word as noun
541       if (length > 0 && Character.isUpperCase(term[0])) {
542         return PartOfSpeech.Noun;
543       }
544       return PartOfSpeech.Unknown;
545     }
546   }
547 </pre>
548 Just like the LengthFilter, this new filter accesses the attributes it needs in the constructor and
549 stores references in instance variables. Notice how you only need to pass in the interface of the new
550 Attribute and instantiating the correct class is automatically been taken care of.
551 Now we need to add the filter to the chain:
552 <pre class="prettyprint">
553   public TokenStream tokenStream(String fieldName, Reader reader) {
554     TokenStream stream = new WhitespaceTokenizer(reader);
555     stream = new LengthFilter(stream, 3, Integer.MAX_VALUE);
556     stream = new PartOfSpeechTaggingFilter(stream);
557     return stream;
558   }
559 </pre>
560 Now let's look at the output:
561 <pre>
562 This
563 demo
564 the
565 new
566 TokenStream
567 API
568 </pre>
569 Apparently it hasn't changed, which shows that adding a custom attribute to a TokenStream/Filter chain does not
570 affect any existing consumers, simply because they don't know the new Attribute. Now let's change the consumer
571 to make use of the new PartOfSpeechAttribute and print it out:
572 <pre class="prettyprint">
573   public static void main(String[] args) throws IOException {
574     // text to tokenize
575     final String text = "This is a demo of the new TokenStream API";
576     
577     MyAnalyzer analyzer = new MyAnalyzer();
578     TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
579     
580     // get the TermAttribute from the TokenStream
581     TermAttribute termAtt = stream.addAttribute(TermAttribute.class);
582     
583     // get the PartOfSpeechAttribute from the TokenStream
584     PartOfSpeechAttribute posAtt = stream.addAttribute(PartOfSpeechAttribute.class);
585     
586     stream.reset();
587
588     // print all tokens until stream is exhausted
589     while (stream.incrementToken()) {
590       System.out.println(termAtt.term() + ": " + posAtt.getPartOfSpeech());
591     }
592     
593     stream.end();
594     stream.close();
595   }
596 </pre>
597 The change that was made is to get the PartOfSpeechAttribute from the TokenStream and print out its contents in
598 the while loop that consumes the stream. Here is the new output:
599 <pre>
600 This: Noun
601 demo: Unknown
602 the: Unknown
603 new: Unknown
604 TokenStream: Noun
605 API: Noun
606 </pre>
607 Each word is now followed by its assigned PartOfSpeech tag. Of course this is a naive 
608 part-of-speech tagging. The word 'This' should not even be tagged as noun; it is only spelled capitalized because it
609 is the first word of a sentence. Actually this is a good opportunity for an excerise. To practice the usage of the new
610 API the reader could now write an Attribute and TokenFilter that can specify for each word if it was the first token
611 of a sentence or not. Then the PartOfSpeechTaggingFilter can make use of this knowledge and only tag capitalized words
612 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). 
613 As a small hint, this is how the new Attribute class could begin:
614 <pre class="prettyprint">
615   public class FirstTokenOfSentenceAttributeImpl extends Attribute
616                    implements FirstTokenOfSentenceAttribute {
617     
618     private boolean firstToken;
619     
620     public void setFirstToken(boolean firstToken) {
621       this.firstToken = firstToken;
622     }
623     
624     public boolean getFirstToken() {
625       return firstToken;
626     }
627
628     public void clear() {
629       firstToken = false;
630     }
631
632   ...
633 </pre>
634 </body>
635 </html>