You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ma...@apache.org on 2012/01/18 23:28:20 UTC

svn commit: r1233096 [3/13] - in /lucene/dev/branches/solrcloud: ./ dev-tools/eclipse/ dev-tools/idea/.idea/ dev-tools/idea/lucene/contrib/ dev-tools/idea/modules/analysis/kuromoji/ dev-tools/idea/solr/contrib/analysis-extras/ dev-tools/maven/modules/a...

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/analysis/package.html
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/analysis/package.html?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/analysis/package.html (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/analysis/package.html Wed Jan 18 22:28:07 2012
@@ -23,7 +23,7 @@
 <p>API and code to convert text into indexable/searchable tokens.  Covers {@link org.apache.lucene.analysis.Analyzer} and related classes.</p>
 <h2>Parsing? Tokenization? Analysis!</h2>
 <p>
-Lucene, indexing and search library, accepts only plain text input.
+Lucene, an indexing and search library, accepts only plain text input.
 <p>
 <h2>Parsing</h2>
 <p>
@@ -39,12 +39,23 @@ The way input text is broken into tokens
 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).
 <p>
-In some cases simply breaking the input text into tokens is not enough &ndash; a deeper <i>Analysis</i> may be needed.
-There are many post tokenization steps that can be done, including (but not limited to):
+  In some cases simply breaking the input text into tokens is not enough
+  &ndash; a deeper <i>Analysis</i> may be needed. Lucene includes both
+  pre- and post-tokenization analysis facilities.
+</p>
+<p>
+  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.
+</p>
+<p>
+  There are many post-tokenization steps that can be done, including 
+  (but not limited to):
+</p>
 <ul>
   <li><a href="http://en.wikipedia.org/wiki/Stemming">Stemming</a> &ndash; 
-      Replacing of words by their stems. 
-      For instance with English stemming "bikes" is replaced by "bike"; 
+      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".
   </li>
   <li><a href="http://en.wikipedia.org/wiki/Stop_words">Stop Words Filtering</a> &ndash; 
@@ -63,53 +74,88 @@ There are many post tokenization steps t
 <p>
 <h2>Core Analysis</h2>
 <p>
-  The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene.  There
-  are three main classes in the package from which all analysis processes are derived.  These are:
-  <ul>
-    <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
-    by the indexing and searching processes.  See below for more information on implementing your own Analyzer.</li>
-    <li>{@link org.apache.lucene.analysis.Tokenizer} &ndash; A Tokenizer is a {@link org.apache.lucene.analysis.TokenStream} and is responsible for breaking
-    up incoming text into tokens. In most cases, an Analyzer will use a Tokenizer as the first step in
-    the analysis process.</li>
-    <li>{@link org.apache.lucene.analysis.TokenFilter} &ndash; A TokenFilter is also a {@link org.apache.lucene.analysis.TokenStream} and is responsible
-    for modifying tokens that have been created by the Tokenizer.  Common modifications performed by a
-    TokenFilter are: deletion, stemming, synonym injection, and down casing.  Not all Analyzers require TokenFilters</li>
-  </ul>
-  <b>Lucene 2.9 introduces a new TokenStream API. Please see the section "New TokenStream API" below for more details.</b>
+  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:
 </p>
+<ul>
+  <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
+    by the indexing and searching processes.  See below for more information
+    on implementing your own Analyzer.
+  </li>
+  <li>
+    CharFilter &ndash; CharFilter extends
+    {@link java.io.Reader} to 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.
+  </li>
+  <li>
+    {@link org.apache.lucene.analysis.Tokenizer} &ndash; A Tokenizer is a 
+    {@link org.apache.lucene.analysis.TokenStream} and is responsible for
+    breaking up incoming text into tokens. In most cases, an Analyzer will
+    use a Tokenizer as the first step in the analysis process.  However,
+    to modify text prior to tokenization, use a CharStream subclass (see
+    above).
+  </li>
+  <li>
+    {@link org.apache.lucene.analysis.TokenFilter} &ndash; A TokenFilter is
+    also a {@link org.apache.lucene.analysis.TokenStream} and is responsible
+    for modifying tokens that have been created by the Tokenizer.  Common 
+    modifications performed by a TokenFilter are: deletion, stemming, synonym 
+    injection, and down casing.  Not all Analyzers require TokenFilters.
+  </li>
+</ul>
 <h2>Hints, Tips and Traps</h2>
 <p>
-   The synergy between {@link org.apache.lucene.analysis.Analyzer} and {@link org.apache.lucene.analysis.Tokenizer}
-   is sometimes confusing. To ease on this confusion, some clarifications:
-   <ul>
-      <li>The {@link org.apache.lucene.analysis.Analyzer} is responsible for the entire task of 
-          <u>creating</u> tokens out of the input text, while the {@link org.apache.lucene.analysis.Tokenizer}
-          is only responsible for <u>breaking</u> the input text into tokens. Very likely, tokens created 
-          by the {@link org.apache.lucene.analysis.Tokenizer} would be modified or even omitted 
-          by the {@link org.apache.lucene.analysis.Analyzer} (via one or more
-          {@link org.apache.lucene.analysis.TokenFilter}s) before being returned.
-       </li>
-       <li>{@link org.apache.lucene.analysis.Tokenizer} is a {@link org.apache.lucene.analysis.TokenStream}, 
-           but {@link org.apache.lucene.analysis.Analyzer} is not.
-       </li>
-       <li>{@link org.apache.lucene.analysis.Analyzer} is "field aware", but 
-           {@link org.apache.lucene.analysis.Tokenizer} is not.
-       </li>
-   </ul>
+  The synergy between {@link org.apache.lucene.analysis.Analyzer} and 
+  {@link org.apache.lucene.analysis.Tokenizer} is sometimes confusing. To ease
+  this confusion, some clarifications:
 </p>
+<ul>
+  <li>
+    The {@link org.apache.lucene.analysis.Analyzer} is responsible for the entire task of 
+    <u>creating</u> tokens out of the input text, while the {@link org.apache.lucene.analysis.Tokenizer}
+    is only responsible for <u>breaking</u> the input text into tokens. Very likely, tokens created 
+    by the {@link org.apache.lucene.analysis.Tokenizer} would be modified or even omitted 
+    by the {@link org.apache.lucene.analysis.Analyzer} (via one or more
+    {@link org.apache.lucene.analysis.TokenFilter}s) before being returned.
+  </li>
+  <li>
+    {@link org.apache.lucene.analysis.Tokenizer} is a {@link org.apache.lucene.analysis.TokenStream}, 
+    but {@link org.apache.lucene.analysis.Analyzer} is not.
+  </li>
+  <li>
+    {@link org.apache.lucene.analysis.Analyzer} is "field aware", but 
+    {@link org.apache.lucene.analysis.Tokenizer} is not.
+  </li>
+</ul>
 <p>
   Lucene Java provides a number of analysis capabilities, the most commonly used one being the StandardAnalyzer.  
   Many applications will have a long and industrious life with nothing more
   than the StandardAnalyzer.  However, there are a few other classes/packages that are worth mentioning:
-  <ol>
-    <li>PerFieldAnalyzerWrapper &ndash; Most Analyzers perform the same operation on all
-      {@link org.apache.lucene.document.Field}s.  The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different
-      {@link org.apache.lucene.document.Field}s.</li>
-    <li>The modules/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.</li>
-    <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>
-  </ol>
 </p>
+<ol>
+  <li>
+    PerFieldAnalyzerWrapper &ndash; Most Analyzers perform the same operation on all
+    {@link org.apache.lucene.document.Field}s.  The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different
+    {@link org.apache.lucene.document.Field}s.
+  </li>
+  <li>
+    The modules/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.
+  </li>
+  <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>
+</ol>
 <p>
   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 contrib/benchmark library can be useful 
@@ -118,24 +164,42 @@ There are many post tokenization steps t
 <h2>Invoking the Analyzer</h2>
 <p>
   Applications usually do not invoke analysis &ndash; Lucene does it for them:
-  <ul>
-    <li>At indexing, as a consequence of 
-        {@link org.apache.lucene.index.IndexWriter#addDocument(Iterable) addDocument(doc)},
-        the Analyzer in effect for indexing is invoked for each indexed field of the added document.
-    </li>
-    <li>At search, a QueryParser may invoke the Analyzer during parsing.  Note that for some queries, analysis does not
-        take place, e.g. wildcard queries.
-    </li>
-  </ul>
+</p>
+<ul>
+  <li>
+    At indexing, as a consequence of 
+    {@link org.apache.lucene.index.IndexWriter#addDocument(Iterable) addDocument(doc)},
+    the Analyzer in effect for indexing is invoked for each indexed field of the added document.
+  </li>
+  <li>
+    At search, a QueryParser may invoke the Analyzer during parsing.  Note that for some queries, analysis does not
+    take place, e.g. wildcard queries.
+  </li>
+</ul>
+<p>
   However an application might invoke Analysis of any text for testing or for any other purpose, something like:
-  <PRE class="prettyprint">
-      Analyzer analyzer = new StandardAnalyzer(); // or any other analyzer
-      TokenStream ts = analyzer.tokenStream("myfield",new StringReader("some text goes here"));
+</p>
+<PRE class="prettyprint">
+    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 = addAttribute(OffsetAttribute.class);
+    
+    try {
+      ts.reset(); // Resets this stream to the beginning. (Required)
       while (ts.incrementToken()) {
-        System.out.println("token: "+ts));
+        // Use {@link org.apache.lucene.util.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());
       }
-  </PRE>
-</p>
+      ts.end();   // Perform end-of-stream operations, e.g. set the final offset.
+    } finally {
+      ts.close(); // Release resources associated with this stream.
+    }
+</PRE>
 <h2>Indexing Analysis vs. Search Analysis</h2>
 <p>
   Selecting the "correct" analyzer is crucial
@@ -159,11 +223,18 @@ There are many post tokenization steps t
   </ol>
 </p>
 <h2>Implementing your own Analyzer</h2>
-<p>Creating your own Analyzer is straightforward. It usually involves either wrapping an existing Tokenizer and  set of TokenFilters to create a new Analyzer
-or creating both the Analyzer and a Tokenizer or TokenFilter.  Before pursuing this approach, you may find it worthwhile
-to explore the modules/analysis 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 or TokenStream derivation (Tokenizer or TokenFilter) have a look at
-the source code of any one of the many samples located in this package.
+<p>
+  Creating your own Analyzer is straightforward. Your Analyzer can wrap
+  existing analysis components &mdash; CharFilter(s) <i>(optional)</i>, a
+  Tokenizer, and TokenFilter(s) <i>(optional)</i> &mdash; or components you
+  create, or a combination of existing and newly created components.  Before
+  pursuing this approach, you may find it worthwhile to explore the
+  contrib/analyzers library and/or ask on the 
+  <a href="http://lucene.apache.org/java/docs/mailinglists.html"
+      >java-user@lucene.apache.org mailing list</a> 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.
 </p>
 <p>
   The following sections discuss some aspects of implementing your own analyzer.
@@ -180,23 +251,25 @@ the source code of any one of the many s
   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:
-  <PRE class="prettyprint">
-      document.add(new Field("f","first ends",...);
-      document.add(new Field("f","starts two",...);
-      indexWriter.addDocument(document);
-  </PRE>
+</p>
+<PRE class="prettyprint">
+    document.add(new Field("f","first ends",...);
+    document.add(new Field("f","starts two",...);
+    indexWriter.addDocument(document);
+</PRE>
+<p>
   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 overriding 
   {@link org.apache.lucene.analysis.Analyzer#getPositionIncrementGap(java.lang.String) Analyzer.getPositionIncrementGap(fieldName)}:
-  <PRE class="prettyprint">
-      Analyzer myAnalyzer = new StandardAnalyzer() {
-         public int getPositionIncrementGap(String fieldName) {
-           return 10;
-         }
-      };
-  </PRE>
 </p>
+<PRE class="prettyprint">
+  Analyzer myAnalyzer = new StandardAnalyzer() {
+    public int getPositionIncrementGap(String fieldName) {
+      return 10;
+    }
+  };
+</PRE>
 <h3>Token Position Increments</h3>
 <p>
    By default, all tokens created by Analyzers and Tokenizers have a 
@@ -213,85 +286,122 @@ the source code of any one of the many s
    that query. But also the phrase query "blue sky" would find that document.
 </p>
 <p>   
-   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, using
+   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, using
    {@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute#setPositionIncrement(int)}.
-   This can be done with something like:
-   <PRE class="prettyprint">
-      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;
+   This can be done with something like the following (note, however, that 
+   StopFilter natively includes this capability by subclassing 
+   FilteringTokenFilter}:
+</p>
+<PRE class="prettyprint">
+  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 res;
+          return hasNext;
+        }
       }
-   </PRE>
-   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.
-</p>
-<p>
-   Few more use cases for modifying position increments are:
-   <ol>
-     <li>Inhibiting phrase and proximity matches in sentence boundaries &ndash; for this, a tokenizer that 
-         identifies a new sentence can add 1 to the position increment of the first token of the new sentence.</li>
-     <li>Injecting synonyms &ndash; 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.</li>
-   </ol>
-</p>
-<h2>New TokenStream API</h2>
-<p>
-	With Lucene 2.9 we introduce a new TokenStream API. The old API used to produce Tokens. A Token
-	has getter and setter methods for different properties like positionIncrement and termText.
-	While this approach was sufficient for the default indexing format, it is not versatile enough for
-	Flexible Indexing, a term which summarizes the effort of making the Lucene indexer pluggable and extensible for custom
-	index formats.
-</p>
-<p>
-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.
-</p>
-<h3>Attribute and AttributeSource</h3> 
-Lucene 2.9 therefore introduces a new pair of classes called {@link org.apache.lucene.util.Attribute} and
-{@link org.apache.lucene.util.AttributeSource}. An Attribute serves as a
-particular piece of information about a text token. For example, {@link org.apache.lucene.analysis.tokenattributes.CharTermAttribute}
- 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.
-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.
-<p>
-	Lucene now provides six Attributes out of the box, which replace the variables the Token class has:
-	<ul>
-	  <li>{@link org.apache.lucene.analysis.tokenattributes.CharTermAttribute}<p>The term text of a token.</p></li>
-  	  <li>{@link org.apache.lucene.analysis.tokenattributes.OffsetAttribute}<p>The start and end offset of token in characters.</p></li>
-	  <li>{@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute}<p>See above for detailed information about position increment.</p></li>
-	  <li>{@link org.apache.lucene.analysis.tokenattributes.PayloadAttribute}<p>The payload that a Token can optionally have.</p></li>
-	  <li>{@link org.apache.lucene.analysis.tokenattributes.TypeAttribute}<p>The type of the token. Default is 'word'.</p></li>
-	  <li>{@link org.apache.lucene.analysis.tokenattributes.FlagsAttribute}<p>Optional flags a token can have.</p></li>
-	</ul>
-</p>
-<h3>Using the new TokenStream API</h3>
+    };
+    return res;
+  }
+</PRE>
+<p>
+  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.
+</p>
+<p>
+   A few more use cases for modifying position increments are:
+</p>
+<ol>
+  <li>Inhibiting phrase and proximity matches in sentence boundaries &ndash; for this, a tokenizer that 
+    identifies a new sentence can add 1 to the position increment of the first token of the new sentence.</li>
+  <li>Injecting synonyms &ndash; 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.</li>
+</ol>
+<h2>TokenStream API</h2>
+<p>
+	"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.
+</p>
+<h3>Attribute and AttributeSource</h3>
+<p>
+  Classes {@link org.apache.lucene.util.Attribute} and 
+  {@link org.apache.lucene.util.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, 
+  {@link org.apache.lucene.analysis.tokenattributes.CharTermAttribute} 
+  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. 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.
+</p>
+<p>
+	Lucene provides seven Attributes out of the box:
+</p>
+<table rules="all" frame="box" cellpadding="3">
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.CharTermAttribute}</td>
+    <td>
+      The term text of a token.  Implements {@link java.lang.CharSequence} 
+      (providing methods length() and charAt(), and allowing e.g. for direct
+      use with regular expression {@link java.util.regex.Matcher}s) and 
+      {@link java.lang.Appendable} (allowing the term text to be appended to.)
+    </td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.OffsetAttribute}</td>
+    <td>The start and end offset of a token in characters.</td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute}</td>
+    <td>See above for detailed information about position increment.</td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.PayloadAttribute}</td>
+    <td>The payload that a Token can optionally have.</td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.TypeAttribute}</td>
+    <td>The type of the token. Default is 'word'.</td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.FlagsAttribute}</td>
+    <td>Optional flags a token can have.</td>
+  </tr>
+  <tr>
+    <td>{@link org.apache.lucene.analysis.tokenattributes.KeywordAttribute}</td>
+    <td>
+      Keyword-aware TokenStreams/-Filters skip modification of tokens that
+      return true from this attribute's isKeyword() method. 
+    </td>
+  </tr>
+</table>
+<h3>Using the TokenStream API</h3>
 There are a few important things to know in order to use the new API efficiently which are summarized here. You may want
 to walk through the example below first and come back to this section afterwards.
 <ol><li>
@@ -326,39 +436,53 @@ could simply check with hasAttribute(), 
 extra performance.
 </li></ol>
 <h3>Example</h3>
-In this example we will create a WhiteSpaceTokenizer and use a LengthFilter to suppress all words that only
-have two or less characters. The LengthFilter is part of the Lucene core and its implementation will be explained
-here to illustrate the usage of the new TokenStream API.<br>
-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.
+<p>
+  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.
+</p>
+<p>
+  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.
+</p>
 <h4>Whitespace tokenization</h4>
 <pre class="prettyprint">
 public class MyAnalyzer extends Analyzer {
 
-  public TokenStream tokenStream(String fieldName, Reader reader) {
-    TokenStream stream = new WhitespaceTokenizer(reader);
-    return stream;
+  private Version matchVersion;
+  
+  public MyAnalyzer(Version matchVersion) {
+    this.matchVersion = matchVersion;
+  }
+
+  {@literal @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 new TokenStream API";
+    final String text = "This is a demo of the TokenStream API";
     
-    MyAnalyzer analyzer = new MyAnalyzer();
+    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);
 
-    stream.reset();
+    try {
+      stream.reset();
     
-    // print all tokens until stream is exhausted
-    while (stream.incrementToken()) {
-      System.out.println(termAtt.toString());
-    }
+      // print all tokens until stream is exhausted
+      while (stream.incrementToken()) {
+        System.out.println(termAtt.toString());
+      }
     
-    stream.end()
-    stream.close();
+      stream.end()
+    } finally {
+      stream.close();
+    }
   }
 }
 </pre>
@@ -377,13 +501,15 @@ TokenStream
 API
 </pre>
 <h4>Adding a LengthFilter</h4>
-We want to suppress all tokens that have 2 or less characters. We can do that easily by adding a LengthFilter 
-to the chain. Only the tokenStream() method in our analyzer needs to be changed:
+We want to suppress all tokens that have 2 or less characters. We can do that
+easily by adding a LengthFilter to the chain. Only the
+<code>createComponents()</code> method in our analyzer needs to be changed:
 <pre class="prettyprint">
-  public TokenStream tokenStream(String fieldName, Reader reader) {
-    TokenStream stream = new WhitespaceTokenizer(reader);
-    stream = new LengthFilter(stream, 3, Integer.MAX_VALUE);
-    return stream;
+  {@literal @Override}
+  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
+    final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
+    TokenStream result = new LengthFilter(source, 3, Integer.MAX_VALUE);
+    return new TokenStreamComponents(source, result);
   }
 </pre>
 Note how now only words with 3 or more characters are contained in the output:
@@ -395,53 +521,119 @@ new
 TokenStream
 API
 </pre>
-Now let's take a look how the LengthFilter is implemented (it is part of Lucene's core):
+Now let's take a look how the LengthFilter is implemented:
 <pre class="prettyprint">
-public final class LengthFilter extends TokenFilter {
+public final class LengthFilter extends FilteringTokenFilter {
 
-  final int min;
-  final int max;
+  private final int min;
+  private final int max;
   
-  private CharTermAttribute termAtt;
+  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(TokenStream in, int min, int max)
-  {
-    super(in);
+  public LengthFilter(boolean enablePositionIncrements, TokenStream in, int min, int max) {
+    super(enablePositionIncrements, in);
     this.min = min;
     this.max = max;
-    termAtt = addAttribute(CharTermAttribute.class);
   }
   
-  /**
-   * Returns the next input Token whose term() is the right len
-   */
-  public final boolean incrementToken() throws IOException
-  {
-    assert termAtt != null;
-    // return the first non-stop word found
-    while (input.incrementToken()) {
-      int len = termAtt.length();
-      if (len >= min && len <= max) {
+  {@literal @Override}
+  public boolean accept() throws IOException {
+    final int len = termAtt.length();
+    return (len >= min && len <= max);
+  }
+}
+</pre>
+<p>
+  In LengthFilter, the CharTermAttribute is added and stored in the instance
+  variable <code>termAtt</code>.  Remember that there can only be a single
+  instance of CharTermAttribute in the chain, so in our example the
+  <code>addAttribute()</code> call in LengthFilter returns the
+  CharTermAttribute that the WhitespaceTokenizer already added.
+</p>
+<p>
+  The tokens are retrieved from the input stream in FilteringTokenFilter's 
+  <code>incrementToken()</code> method (see below), which calls LengthFilter's
+  <code>accept()</code> 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 how
+  <code>accept()</code> can efficiently access the instance variable; no 
+  attribute lookup is neccessary. The same is true for the consumer, which can
+  simply use local references to the Attributes.
+</p>
+<p>
+  LengthFilter extends FilteringTokenFilter:
+</p>
+
+<pre class="prettyprint">
+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 {@literal {@link #incrementToken}}. */
+  protected abstract boolean accept() throws IOException;
+
+  {@literal @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;
+        }
       }
-      // note: else we ignore it but should we index each part of it?
     }
-    // reached EOS -- return null
+    // reached EOS -- return false
     return false;
   }
+
+  /**
+   * {@literal @see #setEnablePositionIncrements(boolean)}
+   */
+  public boolean getEnablePositionIncrements() {
+    return enablePositionIncrements;
+  }
+
+  /**
+   * If <code>true</code>, this TokenFilter will preserve
+   * positions of the incoming tokens (ie, accumulate and
+   * set position increments of the removed tokens).
+   * Generally, <code>true</code> is best as it does not
+   * lose information (positions of the original tokens)
+   * during indexing.
+   * 
+   * <p> When set, when a token is stopped
+   * (omitted), the position increment of the following
+   * token is incremented.
+   *
+   * <p> <b>NOTE</b>: 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;
+  }
 }
 </pre>
-The CharTermAttribute is added in the constructor and stored in the instance variable <code>termAtt</code>.
-Remember that there can only be a single instance of CharTermAttribute in the chain, so in our example the 
-<code>addAttribute()</code> call in LengthFilter returns the TermAttribute that the WhitespaceTokenizer already added. The tokens
-are retrieved from the input stream in the <code>incrementToken()</code> method. By looking at the term text
-in the CharTermAttribute the length of the term can be determined and too short or too long tokens are skipped. 
-Note how <code>incrementToken()</code> can efficiently access the instance variable; no attribute lookup
-is neccessary. The same is true for the consumer, which can simply use local references to the Attributes.
 
 <h4>Adding a custom Attribute</h4>
 Now we're going to implement our own custom Attribute for part-of-speech tagging and call it consequently 
@@ -457,20 +649,23 @@ Now we're going to implement our own cus
     public PartOfSpeech getPartOfSpeech();
   }
 </pre>
-
-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 postfix 'Impl'. In this example, we would
-consequently call the implementing class <code>PartOfSpeechAttributeImpl</code>. <br/>
-This should be the usual behavior. However, there is also an expert-API that allows changing these naming conventions:
-{@link org.apache.lucene.util.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. <br/><br/>
-
-Now here is the actual class that implements our new Attribute. Notice that the class has to extend
-{@link org.apache.lucene.util.AttributeImpl}:
-
+<p>
+  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 <code>PartOfSpeechAttributeImpl</code>.
+</p>
+<p>
+  This should be the usual behavior. However, there is also an expert-API that allows changing these naming conventions:
+  {@link org.apache.lucene.util.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.
+</p>
+<p>
+  Now here is the actual class that implements our new Attribute. Notice that the class has to extend
+  {@link org.apache.lucene.util.AttributeImpl}:
+</p>
 <pre class="prettyprint">
 public final class PartOfSpeechAttributeImpl extends AttributeImpl 
-                            implements PartOfSpeechAttribute{
+                                  implements PartOfSpeechAttribute {
   
   private PartOfSpeech pos = PartOfSpeech.Unknown;
   
@@ -482,44 +677,33 @@ public final class PartOfSpeechAttribute
     return pos;
   }
 
+  {@literal @Override}
   public void clear() {
     pos = PartOfSpeech.Unknown;
   }
 
+  {@literal @Override}
   public void copyTo(AttributeImpl target) {
-    ((PartOfSpeechAttributeImpl) target).pos = pos;
-  }
-
-  public boolean equals(Object other) {
-    if (other == this) {
-      return true;
-    }
-    
-    if (other instanceof PartOfSpeechAttributeImpl) {
-      return pos == ((PartOfSpeechAttributeImpl) other).pos;
-    }
- 
-    return false;
-  }
-
-  public int hashCode() {
-    return pos.ordinal();
+    ((PartOfSpeechAttribute) target).setPartOfSpeech(pos);
   }
 }
 </pre>
-This is a simple Attribute implementation has only a single variable that stores the part-of-speech of a token. It extends the
-new <code>AttributeImpl</code> class and therefore implements its abstract methods <code>clear(), copyTo(), equals(), hashCode()</code>.
-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'.
+<p>
+  This is a simple Attribute implementation has only a single variable that
+  stores the part-of-speech of a token. It extends the
+  <code>AttributeImpl</code> class and therefore implements its abstract methods
+  <code>clear()</code> and <code>copyTo()</code>. 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'.
+</p>
 <pre class="prettyprint">
   public static class PartOfSpeechTaggingFilter extends TokenFilter {
-    PartOfSpeechAttribute posAtt;
-    CharTermAttribute termAtt;
+    PartOfSpeechAttribute posAtt = addAttribute(PartOfSpeechAttribute.class);
+    CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
     
     protected PartOfSpeechTaggingFilter(TokenStream input) {
       super(input);
-      posAtt = addAttribute(PartOfSpeechAttribute.class);
-      termAtt = addAttribute(CharTermAttribute.class);
     }
     
     public boolean incrementToken() throws IOException {
@@ -538,16 +722,20 @@ that tags every word with a leading uppe
     }
   }
 </pre>
-Just like the LengthFilter, this new filter accesses the attributes it needs in the constructor and
-stores references in instance variables. Notice how you only need to pass in the interface of the new
-Attribute and instantiating the correct class is automatically been taken care of.
-Now we need to add the filter to the chain:
+<p>
+  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.
+</p>
+<p>Now we need to add the filter to the chain in MyAnalyzer:</p>
 <pre class="prettyprint">
-  public TokenStream tokenStream(String fieldName, Reader reader) {
-    TokenStream stream = new WhitespaceTokenizer(reader);
-    stream = new LengthFilter(stream, 3, Integer.MAX_VALUE);
-    stream = new PartOfSpeechTaggingFilter(stream);
-    return stream;
+  {@literal @Override}
+  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
+    final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
+    TokenStream result = new LengthFilter(source, 3, Integer.MAX_VALUE);
+    result = new PartOfSpeechTaggingFilter(result);
+    return new TokenStreamComponents(source, result);
   }
 </pre>
 Now let's look at the output:
@@ -565,7 +753,7 @@ to make use of the new PartOfSpeechAttri
 <pre class="prettyprint">
   public static void main(String[] args) throws IOException {
     // text to tokenize
-    final String text = "This is a demo of the new TokenStream API";
+    final String text = "This is a demo of the TokenStream API";
     
     MyAnalyzer analyzer = new MyAnalyzer();
     TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
@@ -575,16 +763,19 @@ to make use of the new PartOfSpeechAttri
     
     // get the PartOfSpeechAttribute from the TokenStream
     PartOfSpeechAttribute posAtt = stream.addAttribute(PartOfSpeechAttribute.class);
-    
-    stream.reset();
 
-    // print all tokens until stream is exhausted
-    while (stream.incrementToken()) {
-      System.out.println(termAtt.toString() + ": " + posAtt.getPartOfSpeech());
-    }
+    try {
+      stream.reset();
+
+      // print all tokens until stream is exhausted
+      while (stream.incrementToken()) {
+        System.out.println(termAtt.toString() + ": " + posAtt.getPartOfSpeech());
+      }
     
-    stream.end();
-    stream.close();
+      stream.end();
+    } finally {
+      stream.close();
+    }
   }
 </pre>
 The change that was made is to get the PartOfSpeechAttribute from the TokenStream and print out its contents in
@@ -605,8 +796,8 @@ of a sentence or not. Then the PartOfSpe
 as nouns if not the first word of a sentence (we know, this is still not a correct behavior, but hey, it's a good exercise). 
 As a small hint, this is how the new Attribute class could begin:
 <pre class="prettyprint">
-  public class FirstTokenOfSentenceAttributeImpl extends Attribute
-                   implements FirstTokenOfSentenceAttribute {
+  public class FirstTokenOfSentenceAttributeImpl extends AttributeImpl
+                              implements FirstTokenOfSentenceAttribute {
     
     private boolean firstToken;
     
@@ -618,6 +809,7 @@ As a small hint, this is how the new Att
       return firstToken;
     }
 
+    {@literal @Override}
     public void clear() {
       firstToken = false;
     }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTermsReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTermsReader.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTermsReader.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTermsReader.java Wed Jan 18 22:28:07 2012
@@ -697,16 +697,20 @@ public class BlockTermsReader extends Fi
       }
 
       @Override
-      public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse) throws IOException {
-        //System.out.println("BTR.d&p this=" + this);
-        decodeMetaData();
-        if (fieldInfo.indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
+      public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, boolean needsOffsets) throws IOException {
+        if (fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
+          // Positions were not indexed:
           return null;
-        } else {
-          DocsAndPositionsEnum dpe = postingsReader.docsAndPositions(fieldInfo, state, liveDocs, reuse);
-          //System.out.println("  return d&pe=" + dpe);
-          return dpe;
         }
+
+        if (needsOffsets &&
+            fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
+          // Offsets were not indexed:
+          return null;
+        }
+
+        decodeMetaData();
+        return postingsReader.docsAndPositions(fieldInfo, state, liveDocs, reuse, needsOffsets);
       }
 
       @Override

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsReader.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsReader.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsReader.java Wed Jan 18 22:28:07 2012
@@ -881,13 +881,20 @@ public class BlockTreeTermsReader extend
       }
 
       @Override
-      public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse) throws IOException {
-        if (fieldInfo.indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
+      public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, boolean needsOffsets) throws IOException {
+        if (fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
+          // Positions were not indexed:
+          return null;
+        }
+
+        if (needsOffsets &&
+            fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
+          // Offsets were not indexed:
           return null;
-        } else {
-          currentFrame.decodeMetaData();
-          return postingsReader.docsAndPositions(fieldInfo, currentFrame.termState, skipDocs, reuse);
         }
+
+        currentFrame.decodeMetaData();
+        return postingsReader.docsAndPositions(fieldInfo, currentFrame.termState, skipDocs, reuse, needsOffsets);
       }
 
       private int getState() {
@@ -1216,8 +1223,9 @@ public class BlockTreeTermsReader extend
         //System.out.println();
         // computeBlockStats().print(System.out);
       }
-
-      private void initIndexInput() {
+      
+      // Not private to avoid synthetic access$NNN methods
+      void initIndexInput() {
         if (this.in == null) {
           this.in = (IndexInput) BlockTreeTermsReader.this.in.clone();
         }
@@ -2095,17 +2103,21 @@ public class BlockTreeTermsReader extend
       }
 
       @Override
-      public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse) throws IOException {
-        assert !eof;
-        //System.out.println("BTR.d&p this=" + this);
-        if (fieldInfo.indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
+      public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, boolean needsOffsets) throws IOException {
+        if (fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
+          // Positions were not indexed:
+          return null;
+        }
+
+        if (needsOffsets &&
+            fieldInfo.indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
+          // Offsets were not indexed:
           return null;
-        } else {
-          currentFrame.decodeMetaData();
-          DocsAndPositionsEnum dpe = postingsReader.docsAndPositions(fieldInfo, currentFrame.state, skipDocs, reuse);
-          //System.out.println("  return d&pe=" + dpe);
-          return dpe;
         }
+
+        assert !eof;
+        currentFrame.decodeMetaData();
+        return postingsReader.docsAndPositions(fieldInfo, currentFrame.state, skipDocs, reuse, needsOffsets);
       }
 
       @Override

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsWriter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsWriter.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsWriter.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/BlockTreeTermsWriter.java Wed Jan 18 22:28:07 2012
@@ -22,8 +22,8 @@ import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.List;
 
-import org.apache.lucene.index.FieldInfo;
 import org.apache.lucene.index.FieldInfo.IndexOptions;
+import org.apache.lucene.index.FieldInfo;
 import org.apache.lucene.index.FieldInfos;
 import org.apache.lucene.index.IndexFileNames;
 import org.apache.lucene.index.SegmentWriteState;
@@ -39,6 +39,7 @@ import org.apache.lucene.util.fst.ByteSe
 import org.apache.lucene.util.fst.BytesRefFSTEnum;
 import org.apache.lucene.util.fst.FST;
 import org.apache.lucene.util.fst.NoOutputs;
+import org.apache.lucene.util.fst.Util;
 
 /*
   TODO:
@@ -244,6 +245,7 @@ public class BlockTreeTermsWriter extend
     public final boolean hasTerms;
     public final boolean isFloor;
     public final int floorLeadByte;
+    private final IntsRef scratchIntsRef = new IntsRef();
 
     public PendingBlock(BytesRef prefix, long fp, boolean hasTerms, boolean isFloor, int floorLeadByte, List<FST<BytesRef>> subIndices) {
       super(false);
@@ -294,7 +296,7 @@ public class BlockTreeTermsWriter extend
       final byte[] bytes = new byte[(int) scratchBytes.getFilePointer()];
       assert bytes.length > 0;
       scratchBytes.writeTo(bytes, 0);
-      indexBuilder.add(prefix, new BytesRef(bytes, 0, bytes.length));
+      indexBuilder.add(Util.toIntsRef(prefix, scratchIntsRef), new BytesRef(bytes, 0, bytes.length));
       scratchBytes.reset();
 
       // Copy over index for all sub-blocks
@@ -337,7 +339,7 @@ public class BlockTreeTermsWriter extend
         //if (DEBUG) {
         //  System.out.println("      add sub=" + indexEnt.input + " " + indexEnt.input + " output=" + indexEnt.output);
         //}
-        builder.add(indexEnt.input, indexEnt.output);
+        builder.add(Util.toIntsRef(indexEnt.input, scratchIntsRef), indexEnt.output);
       }
     }
   }
@@ -853,13 +855,15 @@ public class BlockTreeTermsWriter extend
       return postingsWriter;
     }
 
+    private final IntsRef scratchIntsRef = new IntsRef();
+
     @Override
     public void finishTerm(BytesRef text, TermStats stats) throws IOException {
 
       assert stats.docFreq > 0;
       //if (DEBUG) System.out.println("BTTW.finishTerm term=" + fieldInfo.name + ":" + toString(text) + " seg=" + segment + " df=" + stats.docFreq);
 
-      blockBuilder.add(text, noOutputs.getNoOutput());
+      blockBuilder.add(Util.toIntsRef(text, scratchIntsRef), noOutputs.getNoOutput());
       pending.add(new PendingTerm(BytesRef.deepCopyOf(text), stats));
       postingsWriter.finishTerm(stats);
       numTerms++;

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/DocValuesConsumer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/DocValuesConsumer.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/DocValuesConsumer.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/DocValuesConsumer.java Wed Jan 18 22:28:07 2012
@@ -19,51 +19,50 @@ package org.apache.lucene.codecs;
 import java.io.IOException;
 
 import org.apache.lucene.codecs.lucene40.values.Writer;
-import org.apache.lucene.index.DocValues;
+import org.apache.lucene.document.DocValuesField;
+import org.apache.lucene.document.Field;
 import org.apache.lucene.index.DocValues.Source;
-import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.DocValues;
+import org.apache.lucene.index.IndexableField;
 import org.apache.lucene.index.MergeState;
-import org.apache.lucene.index.DocValue;
 import org.apache.lucene.util.Bits;
 import org.apache.lucene.util.BytesRef;
 
 /**
- * Abstract API that consumes {@link DocValue}s.
+ * Abstract API that consumes {@link IndexableField}s.
  * {@link DocValuesConsumer} are always associated with a specific field and
  * segments. Concrete implementations of this API write the given
- * {@link DocValue} into a implementation specific format depending on
+ * {@link IndexableField} into a implementation specific format depending on
  * the fields meta-data.
  * 
  * @lucene.experimental
  */
 public abstract class DocValuesConsumer {
 
-  protected Source currentMergeSource;
   protected final BytesRef spare = new BytesRef();
 
   /**
-   * Adds the given {@link DocValue} instance to this
+   * Adds the given {@link IndexableField} instance to this
    * {@link DocValuesConsumer}
    * 
    * @param docID
    *          the document ID to add the value for. The docID must always
    *          increase or be <tt>0</tt> if it is the first call to this method.
-   * @param docValue
+   * @param value
    *          the value to add
    * @throws IOException
    *           if an {@link IOException} occurs
    */
-  public abstract void add(int docID, DocValue docValue)
+  public abstract void add(int docID, IndexableField value)
       throws IOException;
 
   /**
-   * Called when the consumer of this API is doc with adding
-   * {@link DocValue} to this {@link DocValuesConsumer}
+   * Called when the consumer of this API is done adding values.
    * 
    * @param docCount
    *          the total number of documents in this {@link DocValuesConsumer}.
    *          Must be greater than or equal the last given docID to
-   *          {@link #add(int, DocValue)}.
+   *          {@link #add(int, IndexableField)}.
    * @throws IOException
    */
   public abstract void finish(int docCount) throws IOException;
@@ -87,8 +86,8 @@ public abstract class DocValuesConsumer 
       final org.apache.lucene.index.MergeState.IndexReaderAndLiveDocs reader = mergeState.readers.get(readerIDX);
       if (docValues[readerIDX] != null) {
         hasMerged = true;
-        merge(new SingleSubMergeState(docValues[readerIDX], mergeState.docBase[readerIDX], reader.reader.maxDoc(),
-                                    reader.liveDocs));
+        merge(docValues[readerIDX], mergeState.docBase[readerIDX],
+              reader.reader.maxDoc(), reader.liveDocs);
         mergeState.checkAbort.work(reader.reader.maxDoc());
       }
     }
@@ -99,73 +98,56 @@ public abstract class DocValuesConsumer 
   }
 
   /**
-   * Merges the given {@link SingleSubMergeState} into this {@link DocValuesConsumer}.
+   * Merges the given {@link DocValues} into this {@link DocValuesConsumer}.
    * 
-   * @param state
-   *          the {@link SingleSubMergeState} to merge
    * @throws IOException
    *           if an {@link IOException} occurs
    */
-  protected void merge(SingleSubMergeState state) throws IOException {
+  protected void merge(DocValues reader, int docBase, int docCount, Bits liveDocs) throws IOException {
     // This enables bulk copies in subclasses per MergeState, subclasses can
     // simply override this and decide if they want to merge
     // segments using this generic implementation or if a bulk merge is possible
     // / feasible.
-    final Source source = state.reader.getDirectSource();
+    final Source source = reader.getDirectSource();
     assert source != null;
-    setNextMergeSource(source); // set the current enum we are working on - the
-    // impl. will get the correct reference for the type
-    // it supports
-    int docID = state.docBase;
-    final Bits liveDocs = state.liveDocs;
-    final int docCount = state.docCount;
+    int docID = docBase;
+    final DocValues.Type type = reader.type();
+    final Field scratchField;
+    switch(type) {
+    case VAR_INTS:
+    case FIXED_INTS_16:
+    case FIXED_INTS_32:
+    case FIXED_INTS_64:
+    case FIXED_INTS_8:
+      scratchField = new DocValuesField("", (long) 0, type);
+      break;
+    case FLOAT_32:
+    case FLOAT_64:
+      scratchField = new DocValuesField("", (double) 0, type);
+      break;
+    case BYTES_FIXED_STRAIGHT:
+    case BYTES_FIXED_DEREF:
+    case BYTES_FIXED_SORTED:
+    case BYTES_VAR_STRAIGHT:
+    case BYTES_VAR_DEREF:
+    case BYTES_VAR_SORTED:
+      scratchField = new DocValuesField("", new BytesRef(), type);
+      break;
+    default:
+      assert false;
+      scratchField = null;
+    }
     for (int i = 0; i < docCount; i++) {
       if (liveDocs == null || liveDocs.get(i)) {
-        mergeDoc(docID++, i);
+        mergeDoc(scratchField, source, docID++, i);
       }
     }
   }
 
   /**
-   * Records the specified <tt>long</tt> value for the docID or throws an
-   * {@link UnsupportedOperationException} if this {@link Writer} doesn't record
-   * <tt>long</tt> values.
-   * 
-   * @throws UnsupportedOperationException
-   *           if this writer doesn't record <tt>long</tt> values
-   */
-  protected void add(int docID, long value) throws IOException {
-    throw new UnsupportedOperationException("override this method to support integer types");
-  }
-
-  /**
-   * Records the specified <tt>double</tt> value for the docID or throws an
-   * {@link UnsupportedOperationException} if this {@link Writer} doesn't record
-   * <tt>double</tt> values.
-   * 
-   * @throws UnsupportedOperationException
-   *           if this writer doesn't record <tt>double</tt> values
-   */
-  protected void add(int docID, double value) throws IOException {
-    throw new UnsupportedOperationException("override this method to support floating point types");
-  }
-
-  /**
-   * Records the specified {@link BytesRef} value for the docID or throws an
-   * {@link UnsupportedOperationException} if this {@link Writer} doesn't record
-   * {@link BytesRef} values.
-   * 
-   * @throws UnsupportedOperationException
-   *           if this writer doesn't record {@link BytesRef} values
-   */
-  protected void add(int docID, BytesRef value) throws IOException {
-    throw new UnsupportedOperationException("override this method to support byte types");
-  }
-
-  /**
    * Merges a document with the given <code>docID</code>. The methods
    * implementation obtains the value for the <i>sourceDoc</i> id from the
-   * current {@link Source} set to <i>setNextMergeSource(Source)</i>.
+   * current {@link Source}.
    * <p>
    * This method is used during merging to provide implementation agnostic
    * default merge implementation.
@@ -177,67 +159,29 @@ public abstract class DocValuesConsumer 
    * ID must always be greater than the previous ID or <tt>0</tt> if called the
    * first time.
    */
-  protected void mergeDoc(int docID, int sourceDoc)
+  protected void mergeDoc(Field scratchField, Source source, int docID, int sourceDoc)
       throws IOException {
-    switch(currentMergeSource.type()) {
+    switch(source.type()) {
     case BYTES_FIXED_DEREF:
     case BYTES_FIXED_SORTED:
     case BYTES_FIXED_STRAIGHT:
     case BYTES_VAR_DEREF:
     case BYTES_VAR_SORTED:
     case BYTES_VAR_STRAIGHT:
-      add(docID, currentMergeSource.getBytes(sourceDoc, spare));
+      scratchField.setValue(source.getBytes(sourceDoc, spare));
       break;
     case FIXED_INTS_16:
     case FIXED_INTS_32:
     case FIXED_INTS_64:
     case FIXED_INTS_8:
     case VAR_INTS:
-      add(docID, currentMergeSource.getInt(sourceDoc));
+      scratchField.setValue(source.getInt(sourceDoc));
       break;
     case FLOAT_32:
     case FLOAT_64:
-      add(docID, currentMergeSource.getFloat(sourceDoc));
+      scratchField.setValue(source.getFloat(sourceDoc));
       break;
     }
-  }
-  
-  /**
-   * Sets the next {@link Source} to consume values from on calls to
-   * {@link #mergeDoc(int, int)}
-   * 
-   * @param mergeSource
-   *          the next {@link Source}, this must not be null
-   */
-  protected final void setNextMergeSource(Source mergeSource) {
-    currentMergeSource = mergeSource;
-  }
-
-  /**
-   * Specialized auxiliary MergeState is necessary since we don't want to
-   * exploit internals up to the codecs consumer. An instance of this class is
-   * created for each merged low level {@link IndexReader} we are merging to
-   * support low level bulk copies.
-   */
-  public static class SingleSubMergeState {
-    /**
-     * the source reader for this MergeState - merged values should be read from
-     * this instance
-     */
-    public final DocValues reader;
-    /** the absolute docBase for this MergeState within the resulting segment */
-    public final int docBase;
-    /** the number of documents in this MergeState */
-    public final int docCount;
-    /** the not deleted bits for this MergeState */
-    public final Bits liveDocs;
-
-    public SingleSubMergeState(DocValues reader, int docBase, int docCount, Bits liveDocs) {
-      assert reader != null;
-      this.reader = reader;
-      this.docBase = docBase;
-      this.docCount = docCount;
-      this.liveDocs = liveDocs;
-    }
+    add(docID, scratchField);
   }
 }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/MappingMultiDocsAndPositionsEnum.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/MappingMultiDocsAndPositionsEnum.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/MappingMultiDocsAndPositionsEnum.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/MappingMultiDocsAndPositionsEnum.java Wed Jan 18 22:28:07 2012
@@ -102,6 +102,16 @@ public final class MappingMultiDocsAndPo
   public int nextPosition() throws IOException {
     return current.nextPosition();
   }
+
+  @Override
+  public int startOffset() throws IOException {
+    return current.startOffset();
+  }
+  
+  @Override
+  public int endOffset() throws IOException {
+    return current.endOffset();
+  }
   
   @Override
   public BytesRef getPayload() throws IOException {

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PerDocConsumer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PerDocConsumer.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PerDocConsumer.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PerDocConsumer.java Wed Jan 18 22:28:07 2012
@@ -52,7 +52,10 @@ public abstract class PerDocConsumer imp
         for (int i = 0; i < docValues.length; i++) {
           docValues[i] = getDocValuesForMerge(mergeState.readers.get(i).reader, fieldInfo);
         }
-        final DocValuesConsumer docValuesConsumer = addValuesField(getDocValuesType(fieldInfo), fieldInfo);
+        Type docValuesType = getDocValuesType(fieldInfo);
+        assert docValuesType != null;
+        
+        final DocValuesConsumer docValuesConsumer = addValuesField(docValuesType, fieldInfo);
         assert docValuesConsumer != null;
         docValuesConsumer.merge(mergeState, docValues);
       }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsConsumer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsConsumer.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsConsumer.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsConsumer.java Wed Jan 18 22:28:07 2012
@@ -44,12 +44,12 @@ public abstract class PostingsConsumer {
     int docBase;
   }
 
-  /** Add a new position & payload.  A null payload means no
-   *  payload; a non-null payload with zero length also
-   *  means no payload.  Caller may reuse the {@link
-   *  BytesRef} for the payload between calls (method must
-   *  fully consume the payload). */
-  public abstract void addPosition(int position, BytesRef payload) throws IOException;
+  /** Add a new position & payload, and start/end offset.  A
+   *  null payload means no payload; a non-null payload with
+   *  zero length also means no payload.  Caller may reuse
+   *  the {@link BytesRef} for the payload between calls
+   *  (method must fully consume the payload). */
+  public abstract void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException;
 
   /** Called when we are done adding positions & payloads
    *  for each doc.  Not called  when the field omits term
@@ -88,7 +88,32 @@ public abstract class PostingsConsumer {
         df++;
         totTF += freq;
       }
+    } else if (mergeState.fieldInfo.indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
+      final DocsAndPositionsEnum postingsEnum = (DocsAndPositionsEnum) postings;
+      while(true) {
+        final int doc = postingsEnum.nextDoc();
+        if (doc == DocIdSetIterator.NO_MORE_DOCS) {
+          break;
+        }
+        visitedDocs.set(doc);
+        final int freq = postingsEnum.freq();
+        this.startDoc(doc, freq);
+        totTF += freq;
+        for(int i=0;i<freq;i++) {
+          final int position = postingsEnum.nextPosition();
+          final BytesRef payload;
+          if (postingsEnum.hasPayload()) {
+            payload = postingsEnum.getPayload();
+          } else {
+            payload = null;
+          }
+          this.addPosition(position, payload, -1, -1);
+        }
+        this.finishDoc();
+        df++;
+      }
     } else {
+      assert mergeState.fieldInfo.indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
       final DocsAndPositionsEnum postingsEnum = (DocsAndPositionsEnum) postings;
       while(true) {
         final int doc = postingsEnum.nextDoc();
@@ -107,7 +132,7 @@ public abstract class PostingsConsumer {
           } else {
             payload = null;
           }
-          this.addPosition(position, payload);
+          this.addPosition(position, payload, postingsEnum.startOffset(), postingsEnum.endOffset());
         }
         this.finishDoc();
         df++;

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsReaderBase.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsReaderBase.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsReaderBase.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/PostingsReaderBase.java Wed Jan 18 22:28:07 2012
@@ -55,7 +55,8 @@ public abstract class PostingsReaderBase
 
   /** Must fully consume state, since after this call that
    *  TermState may be reused. */
-  public abstract DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState state, Bits skipDocs, DocsAndPositionsEnum reuse) throws IOException;
+  public abstract DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState state, Bits skipDocs, DocsAndPositionsEnum reuse,
+                                                        boolean needsOffsets) throws IOException;
 
   public abstract void close() throws IOException;
 

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermVectorsWriter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermVectorsWriter.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermVectorsWriter.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermVectorsWriter.java Wed Jan 18 22:28:07 2012
@@ -19,8 +19,8 @@ package org.apache.lucene.codecs;
 
 import java.io.Closeable;
 import java.io.IOException;
+import java.util.Comparator;
 
-import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
 import org.apache.lucene.index.DocsAndPositionsEnum;
 import org.apache.lucene.index.DocsEnum;
 import org.apache.lucene.index.FieldInfo;
@@ -185,7 +185,6 @@ public abstract class TermVectorsWriter 
     String lastFieldName = null;
 
     while((fieldName = fieldsEnum.next()) != null) {
-      
       final FieldInfo fieldInfo = fieldInfos.fieldInfo(fieldName);
 
       assert lastFieldName == null || fieldName.compareTo(lastFieldName) > 0: "lastFieldName=" + lastFieldName + " fieldName=" + fieldName;
@@ -200,79 +199,83 @@ public abstract class TermVectorsWriter 
       if (numTerms == -1) {
         throw new IllegalStateException("vector.getUniqueTermCount() must be implemented (it returned -1)");
       }
-
-      final boolean positions;
-
-      OffsetAttribute offsetAtt;
-
       final TermsEnum termsEnum = terms.iterator(null);
 
       DocsAndPositionsEnum docsAndPositionsEnum = null;
 
-      if (termsEnum.next() != null) {
-        assert numTerms > 0;
-        docsAndPositionsEnum = termsEnum.docsAndPositions(null, null);
-        if (docsAndPositionsEnum != null) {
-          // has positions
-          positions = true;
-          if (docsAndPositionsEnum.attributes().hasAttribute(OffsetAttribute.class)) {
-            offsetAtt = docsAndPositionsEnum.attributes().getAttribute(OffsetAttribute.class);
-          } else {
-            offsetAtt = null;
-          }
-        } else {
-          positions = false;
-          offsetAtt = null;
-        }
-      } else {
-        // no terms in this field (hmm why is field present
-        // then...?)
-        assert numTerms == 0;
-        positions = false;
-        offsetAtt = null;
-      }
-      
-      startField(fieldInfo, numTerms, positions, offsetAtt != null);
+      boolean startedField = false;
 
-      int termCount = 1;
+      // NOTE: this is tricky, because TermVectors allow
+      // indexing offsets but NOT positions.  So we must
+      // lazily init the field by checking whether first
+      // position we see is -1 or not.
+
+      int termCount = 0;
+      while(termsEnum.next() != null) {
+        termCount++;
 
-      // NOTE: we already .next()'d the TermsEnum above, to
-      // peek @ first term to see if positions/offsets are
-      // present
-      while(true) {
         final int freq = (int) termsEnum.totalTermFreq();
-        startTerm(termsEnum.term(), freq);
 
-        if (positions || offsetAtt != null) {
-          DocsAndPositionsEnum dp = termsEnum.docsAndPositions(null, docsAndPositionsEnum);
-          // TODO: add startOffset()/endOffset() to d&pEnum... this is insanity
-          if (dp != docsAndPositionsEnum) {
-            // producer didnt reuse, must re-pull attributes
-            if (offsetAtt != null) {
-              assert dp.attributes().hasAttribute(OffsetAttribute.class);
-              offsetAtt = dp.attributes().getAttribute(OffsetAttribute.class);
-            }
-          }
-          docsAndPositionsEnum = dp;
+        if (startedField) {
+          startTerm(termsEnum.term(), freq);
+        }
+
+        // TODO: we need a "query" API where we can ask (via
+        // flex API) what this term was indexed with...
+        // Both positions & offsets:
+        docsAndPositionsEnum = termsEnum.docsAndPositions(null, null, true);
+        final boolean hasOffsets;
+        boolean hasPositions = false;
+        if (docsAndPositionsEnum == null) {
+          // Fallback: no offsets
+          docsAndPositionsEnum = termsEnum.docsAndPositions(null, null, false);
+          hasOffsets = false;
+        } else {
+          hasOffsets = true;
+        }
+
+        if (docsAndPositionsEnum != null) {
           final int docID = docsAndPositionsEnum.nextDoc();
           assert docID != DocsEnum.NO_MORE_DOCS;
           assert docsAndPositionsEnum.freq() == freq;
 
           for(int posUpto=0; posUpto<freq; posUpto++) {
             final int pos = docsAndPositionsEnum.nextPosition();
-            final int startOffset = offsetAtt == null ? -1 : offsetAtt.startOffset();
-            final int endOffset = offsetAtt == null ? -1 : offsetAtt.endOffset();
-            
+            if (!startedField) {
+              assert numTerms > 0;
+              hasPositions = pos != -1;
+              startField(fieldInfo, numTerms, hasPositions, hasOffsets);
+              startTerm(termsEnum.term(), freq);
+              startedField = true;
+            }
+            final int startOffset;
+            final int endOffset;
+            if (hasOffsets) {
+              startOffset = docsAndPositionsEnum.startOffset();
+              endOffset = docsAndPositionsEnum.endOffset();
+              assert startOffset != -1;
+              assert endOffset != -1;
+            } else {
+              startOffset = -1;
+              endOffset = -1;
+            }
+            assert !hasPositions || pos >= 0;
             addPosition(pos, startOffset, endOffset);
           }
+        } else {
+          if (!startedField) {
+            assert numTerms > 0;
+            startField(fieldInfo, numTerms, hasPositions, hasOffsets);
+            startTerm(termsEnum.term(), freq);
+            startedField = true;
+          }
         }
-        
-        if (termsEnum.next() == null) {
-          assert termCount == numTerms;
-          break;
-        }
-        termCount++;
       }
+      assert termCount == numTerms;
     }
   }
+  
+  /** Return the BytesRef Comparator used to sort terms
+   *  before feeding to this API. */
+  public abstract Comparator<BytesRef> getComparator() throws IOException;
 }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermsConsumer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermsConsumer.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermsConsumer.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/TermsConsumer.java Wed Jan 18 22:28:07 2012
@@ -119,8 +119,41 @@ public abstract class TermsConsumer {
           }
         }
       }
+    } else if (mergeState.fieldInfo.indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
+      if (postingsEnum == null) {
+        postingsEnum = new MappingMultiDocsAndPositionsEnum();
+      }
+      postingsEnum.setMergeState(mergeState);
+      MultiDocsAndPositionsEnum postingsEnumIn = null;
+      while((term = termsEnum.next()) != null) {
+        // We can pass null for liveDocs, because the
+        // mapping enum will skip the non-live docs:
+        postingsEnumIn = (MultiDocsAndPositionsEnum) termsEnum.docsAndPositions(null, postingsEnumIn, false);
+        assert postingsEnumIn != null;
+        postingsEnum.reset(postingsEnumIn);
+        // set PayloadProcessor
+        if (mergeState.payloadProcessorProvider != null) {
+          for (int i = 0; i < mergeState.readers.size(); i++) {
+            if (mergeState.dirPayloadProcessor[i] != null) {
+              mergeState.currentPayloadProcessor[i] = mergeState.dirPayloadProcessor[i].getProcessor(mergeState.fieldInfo.name, term);
+            }
+          }
+        }
+        final PostingsConsumer postingsConsumer = startTerm(term);
+        final TermStats stats = postingsConsumer.merge(mergeState, postingsEnum, visitedDocs);
+        if (stats.docFreq > 0) {
+          finishTerm(term, stats);
+          sumTotalTermFreq += stats.totalTermFreq;
+          sumDFsinceLastAbortCheck += stats.docFreq;
+          sumDocFreq += stats.docFreq;
+          if (sumDFsinceLastAbortCheck > 60000) {
+            mergeState.checkAbort.work(sumDFsinceLastAbortCheck/5.0);
+            sumDFsinceLastAbortCheck = 0;
+          }
+        }
+      }
     } else {
-      assert mergeState.fieldInfo.indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
+      assert mergeState.fieldInfo.indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
       if (postingsEnum == null) {
         postingsEnum = new MappingMultiDocsAndPositionsEnum();
       }
@@ -129,7 +162,7 @@ public abstract class TermsConsumer {
       while((term = termsEnum.next()) != null) {
         // We can pass null for liveDocs, because the
         // mapping enum will skip the non-live docs:
-        postingsEnumIn = (MultiDocsAndPositionsEnum) termsEnum.docsAndPositions(null, postingsEnumIn);
+        postingsEnumIn = (MultiDocsAndPositionsEnum) termsEnum.docsAndPositions(null, postingsEnumIn, true);
         assert postingsEnumIn != null;
         postingsEnum.reset(postingsEnumIn);
         // set PayloadProcessor
@@ -154,7 +187,6 @@ public abstract class TermsConsumer {
         }
       }
     }
-
     finish(sumTotalTermFreq, sumDocFreq, visitedDocs.cardinality());
   }
 }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexReader.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexReader.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexReader.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexReader.java Wed Jan 18 22:28:07 2012
@@ -33,6 +33,7 @@ import org.apache.lucene.store.IOContext
 import org.apache.lucene.store.IndexInput;
 import org.apache.lucene.util.BytesRef;
 import org.apache.lucene.util.CodecUtil;
+import org.apache.lucene.util.IntsRef;
 import org.apache.lucene.util.fst.Builder;
 import org.apache.lucene.util.fst.BytesRefFSTEnum;
 import org.apache.lucene.util.fst.FST;
@@ -187,6 +188,7 @@ public class VariableGapTermsIndexReader
 
         if (indexDivisor > 1) {
           // subsample
+          final IntsRef scratchIntsRef = new IntsRef();
           final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton(true);
           final Builder<Long> builder = new Builder<Long>(FST.INPUT_TYPE.BYTE1, outputs);
           final BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<Long>(fst);
@@ -194,7 +196,7 @@ public class VariableGapTermsIndexReader
           int count = indexDivisor;
           while((result = fstEnum.next()) != null) {
             if (count == indexDivisor) {
-              builder.add(result.input, result.output);
+              builder.add(Util.toIntsRef(result.input, scratchIntsRef), result.output);
               count = 0;
             }
             count++;

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexWriter.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexWriter.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexWriter.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/VariableGapTermsIndexWriter.java Wed Jan 18 22:28:07 2012
@@ -29,9 +29,11 @@ import org.apache.lucene.store.IndexOutp
 import org.apache.lucene.util.BytesRef;
 import org.apache.lucene.util.CodecUtil;
 import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.IntsRef;
 import org.apache.lucene.util.fst.Builder;
 import org.apache.lucene.util.fst.FST;
 import org.apache.lucene.util.fst.PositiveIntOutputs;
+import org.apache.lucene.util.fst.Util;
 
 /**
  * Selects index terms according to provided pluggable
@@ -227,7 +229,7 @@ public class VariableGapTermsIndexWriter
       ////System.out.println("VGW: field=" + fieldInfo.name);
 
       // Always put empty string in
-      fstBuilder.add(new BytesRef(), fstOutputs.get(termsFilePointer));
+      fstBuilder.add(new IntsRef(), fstOutputs.get(termsFilePointer));
       startTermsFilePointer = termsFilePointer;
     }
 
@@ -246,6 +248,8 @@ public class VariableGapTermsIndexWriter
       }
     }
 
+    private final IntsRef scratchIntsRef = new IntsRef();
+
     @Override
     public void add(BytesRef text, TermStats stats, long termsFilePointer) throws IOException {
       if (text.length == 0) {
@@ -256,7 +260,7 @@ public class VariableGapTermsIndexWriter
       final int lengthSave = text.length;
       text.length = indexedTermPrefixLength(lastTerm, text);
       try {
-        fstBuilder.add(text, fstOutputs.get(termsFilePointer));
+        fstBuilder.add(Util.toIntsRef(text, scratchIntsRef), fstOutputs.get(termsFilePointer));
       } finally {
         text.length = lengthSave;
       }

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xCodec.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xCodec.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xCodec.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xCodec.java Wed Jan 18 22:28:07 2012
@@ -30,7 +30,6 @@ import org.apache.lucene.codecs.Postings
 import org.apache.lucene.codecs.SegmentInfosFormat;
 import org.apache.lucene.codecs.StoredFieldsFormat;
 import org.apache.lucene.codecs.TermVectorsFormat;
-import org.apache.lucene.codecs.lucene40.Lucene40FieldInfosFormat;
 import org.apache.lucene.codecs.lucene40.Lucene40SegmentInfosFormat;
 import org.apache.lucene.codecs.lucene40.Lucene40StoredFieldsFormat;
 import org.apache.lucene.codecs.lucene40.Lucene40TermVectorsFormat;
@@ -52,11 +51,9 @@ public class Lucene3xCodec extends Codec
   // TODO: this should really be a different impl
   private final StoredFieldsFormat fieldsFormat = new Lucene40StoredFieldsFormat();
   
-  // TODO: this should really be a different impl
-  private final TermVectorsFormat vectorsFormat = new Lucene40TermVectorsFormat();
+  private final TermVectorsFormat vectorsFormat = new Lucene3xTermVectorsFormat();
   
-  // TODO: this should really be a different impl
-  private final FieldInfosFormat fieldInfosFormat = new Lucene40FieldInfosFormat();
+  private final FieldInfosFormat fieldInfosFormat = new Lucene3xFieldInfosFormat();
 
   // TODO: this should really be a different impl
   // also if we want preflex to *really* be read-only it should throw exception for the writer?

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xFields.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xFields.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xFields.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xFields.java Wed Jan 18 22:28:07 2012
@@ -966,7 +966,12 @@ public class Lucene3xFields extends Fiel
     }
 
     @Override
-    public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse) throws IOException {
+    public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, boolean needsOffsets) throws IOException {
+      if (needsOffsets) {
+        // Pre-4.0 indices never have offsets:
+        return null;
+      }
+
       PreDocsAndPositionsEnum docsPosEnum;
       if (fieldInfo.indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
         return null;
@@ -1082,6 +1087,16 @@ public class Lucene3xFields extends Fiel
     }
 
     @Override
+    public int startOffset() throws IOException {
+      return -1;
+    }
+
+    @Override
+    public int endOffset() throws IOException {
+      return -1;
+    }
+
+    @Override
     public boolean hasPayload() {
       assert docID != NO_MORE_DOCS;
       return pos.isPayloadAvailable();

Modified: lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xNormsProducer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xNormsProducer.java?rev=1233096&r1=1233095&r2=1233096&view=diff
==============================================================================
--- lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xNormsProducer.java (original)
+++ lucene/dev/branches/solrcloud/lucene/src/java/org/apache/lucene/codecs/lucene3x/Lucene3xNormsProducer.java Wed Jan 18 22:28:07 2012
@@ -75,7 +75,7 @@ class Lucene3xNormsProducer extends PerD
     try {
       long nextNormSeek = NORMS_HEADER.length; //skip header (header unused for now)
       for (FieldInfo fi : fields) {
-        if (fi.isIndexed && !fi.omitNorms) {
+        if (fi.normsPresent()) {
           String fileName = getNormFilename(segmentName, normGen, fi.number);
           Directory d = hasSeparateNorms(normGen, fi.number) ? separateNormsDir : dir;
         
@@ -161,7 +161,7 @@ class Lucene3xNormsProducer extends PerD
   
   static final class NormSource extends Source {
     protected NormSource(byte[] bytes) {
-      super(Type.BYTES_FIXED_STRAIGHT);
+      super(Type.FIXED_INTS_8);
       this.bytes = bytes;
     }
 
@@ -176,6 +176,11 @@ class Lucene3xNormsProducer extends PerD
     }
 
     @Override
+    public long getInt(int docID) {
+      return bytes[docID];
+    }
+
+    @Override
     public boolean hasArray() {
       return true;
     }
@@ -192,6 +197,7 @@ class Lucene3xNormsProducer extends PerD
     // like first FI that has norms but doesn't have separate norms?
     final String normsFileName = IndexFileNames.segmentFileName(info.name, "", NORMS_EXTENSION);
     if (dir.fileExists(normsFileName)) {
+      // only needed to do this in 3x - 4x can decide if the norms are present
       files.add(normsFileName);
     }
   }
@@ -231,7 +237,7 @@ class Lucene3xNormsProducer extends PerD
 
     @Override
     public Type type() {
-      return Type.BYTES_FIXED_STRAIGHT;
+      return Type.FIXED_INTS_8;
     }
     
     byte[] bytes() throws IOException {