Apache Lucene open-source search software
LUCENE-2380: hard cutover of all preflex APIs to flex
Michael McCandlessc91bddb26b12
diff --git a/lucene/MIGRATE.txt b/lucene/MIGRATE.txtindex 67cb13a77f5..846be62895a 100644--- a/lucene/MIGRATE.txt+++ b/lucene/MIGRATE.txt@@ -1,5 +1,5 @@-LUCENE-2380+LUCENE-2380: FieldCache.getStrings/Index --> FieldCache.getDocTerms/Index* The field values returned when sorting by SortField.STRING are nowBytesRef. You can call value.utf8ToString() to convert back to@@ -43,3 +43,171 @@ LUCENE-2380String. You can call the .utf8ToString() method on the BytesRefinstances, if necessary.+++LUCENE-1458, LUCENE-2111: Flexible Indexing++ Flexible indexing changed the low level fields/terms/docs/positions+ enumeration APIs. Here are the major changes:++ * Terms are now binary in nature (arbitrary byte[]), represented+ by the BytesRef class (which provides an offset + length "slice"+ into an existing byte[]).++ * Fields are separately enumerated (FieldsEnum) from the terms+ within each field (TermEnum). So instead of this:++ TermEnum termsEnum = ...;+ while(termsEnum.next()) {+ Term t = termsEnum.term();+ System.out.println("field=" + t.field() + "; text=" + t.text());+ }++ Do this:++ FieldsEnum fieldsEnum = ...;+ String field;+ while((field = fieldsEnum.next()) != null) {+ TermsEnum termsEnum = fieldsEnum.terms();+ BytesRef text;+ while((text = termsEnum.next()) != null) {+ System.out.println("field=" + field + "; text=" + text.utf8ToString());+ }++ * TermDocs is renamed to DocsEnum. Instead of this:++ while(td.next()) {+ int doc = td.doc();+ ...+ }++ do this:++ int doc;+ while((doc = td.next()) != DocsEnum.NO_MORE_DOCS) {+ ...+ }++ Instead of this:++ if (td.skipTo(target)) {+ int doc = td.doc();+ ...+ }++ do this:++ if ((doc=td.skipTo(target)) != DocsEnum.NO_MORE_DOCS) {+ ...+ }++ * TermPositions is renamed to DocsAndPositionsEnum, and no longer+ extends the docs only enumerator (DocsEnum).++ * Deleted docs are no longer implicitly filtered from+ docs/positions enums. Instead, you pass a Bits+ skipDocs (set bits are skipped) when obtaining the enums. Also,+ you can now ask a reader for its deleted docs.++ * The docs/positions enums cannot seek to a term. Instead,+ TermsEnum is able to seek, and then you request the+ docs/positions enum from that TermsEnum.++ * TermsEnum's seek method returns more information. So instead of+ this:++ Term t;+ TermEnum termEnum = reader.terms(t);+ if (t.equals(termEnum.term())) {+ ...+ }++ do this:++ TermsEnum termsEnum = ...;+ BytesRef text;+ if (termsEnum.seek(text) == TermsEnum.SeekStatus.FOUND) {+ ...+ }++ SeekStatus also contains END (enumerator is done) and NOT_FOUND+ (term was not found but enumerator is now positioned to the next+ term).++ * TermsEnum has an ord() method, returning the long numeric+ ordinal (ie, first term is 0, next is 1, and so on) for the term+ it's not positioned to. There is also a corresponding seek(long+ ord) method. Note that these methods are optional; in+ particular the MultiFields TermsEnum does not implement them.+++ How you obtain the enums has changed. The primary entry point is+ the Fields class. If you know your reader is a single segment+ reader, do this:++ Fields fields = reader.Fields();+ if (fields != null) {+ ...+ }++ If the reader might be multi-segment, you must do this:++ Fields fields = MultiFields.getFields(reader);+ if (fields != null) {+ ...+ }++ The fields may be null (eg if the reader has no fields).++ Note that the MultiFields approach entails a performance hit on+ MultiReaders, as it must merge terms/docs/positions on the fly. It's+ generally better to instead get the sequential readers (use+ oal.util.ReaderUtil) and then step through those readers yourself,+ if you can (this is how Lucene drives searches).++ If you pass a SegmentReader to MultiFields.fiels it will simply+ return reader.fields(), so there is no performance hit in that+ case.++ Once you have a non-null Fields you can do this:++ Terms terms = fields.terms("field");+ if (terms != null) {+ ...+ }++ The terms may be null (eg if the field does not exist).++ Once you have a non-null terms you can get an enum like this:++ TermsEnum termsEnum = terms.iterator();++ The returned TermsEnum will not be null.++ You can then .next() through the TermsEnum, or seek. If you want a+ DocsEnum, do this:++ Bits skipDocs = MultiFields.getDeletedDocs(reader);+ DocsEnum docsEnum = null;++ docsEnum = termsEnum.docs(skipDocs, docsEnum);++ You can pass in a prior DocsEnum and it will be reused if possible.++ Likewise for DocsAndPositionsEnum.++ IndexReader has several sugar methods (which just go through the+ above steps, under the hood). Instead of:++ Term t;+ TermDocs termDocs = reader.termDocs();+ termDocs.seek(t);++ do this:++ String field;+ BytesRef text;+ DocsEnum docsEnum = reader.termDocsEnum(reader.getDeletedDocs(), field, text);++ Likewise for DocsAndPositionsEnum.+diff --git a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteByPercentTask.java b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteByPercentTask.javaindex a801ceed696..7fa6002c661 100644--- a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteByPercentTask.java+++ b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteByPercentTask.java@@ -21,7 +21,8 @@ import java.util.Random;import org.apache.lucene.benchmark.byTask.PerfRunData;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.util.Bits;/*** Deletes a percentage of documents from an index randomly@@ -49,11 +50,6 @@ public class DeleteByPercentTask extends PerfTask {random = new Random(runData.getConfig().get("delete.percent.rand.seed", 1717));}- @Override- public void setup() throws Exception {- super.setup();- }-@Overridepublic void setParams(String params) {super.setParams(params);@@ -78,14 +74,14 @@ public class DeleteByPercentTask extends PerfTask {}while (numDeleted < numToDelete) {double delRate = ((double) (numToDelete-numDeleted))/r.numDocs();- TermDocs termDocs = r.termDocs(null);- while (termDocs.next() && numDeleted < numToDelete) {- if (random.nextDouble() <= delRate) {- r.deleteDocument(termDocs.doc());+ Bits delDocs = MultiFields.getDeletedDocs(r);+ int doc = 0;+ while (doc < maxDoc && numDeleted < numToDelete) {+ if (!delDocs.get(doc) && random.nextDouble() <= delRate) {+ r.deleteDocument(doc);numDeleted++;}}- termDocs.close();}System.out.println("--> processed (delete) " + numDeleted + " docs");r.decRef();diff --git a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/quality/utils/QualityQueriesFinder.java b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/quality/utils/QualityQueriesFinder.javaindex 263d33954f8..228b7fbb057 100755--- a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/quality/utils/QualityQueriesFinder.java+++ b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/quality/utils/QualityQueriesFinder.java@@ -20,8 +20,9 @@ import java.io.File;import java.io.IOException;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.PriorityQueue;@@ -88,15 +89,15 @@ public class QualityQueriesFinder {IndexReader ir = IndexReader.open(dir, true);try {int threshold = ir.maxDoc() / 10; // ignore words too common.- TermEnum terms = ir.terms(new Term(field,""));- while (terms.next()) {- if (!field.equals(terms.term().field())) {- break;- }- int df = terms.docFreq();- if (df<threshold) {- String ttxt = terms.term().text();- pq.insertWithOverflow(new TermDf(ttxt,df));+ Terms terms = MultiFields.getTerms(ir, field);+ if (terms != null) {+ TermsEnum termsEnum = terms.iterator();+ while (termsEnum.next() != null) {+ int df = termsEnum.docFreq();+ if (df<threshold) {+ String ttxt = termsEnum.term().utf8ToString();+ pq.insertWithOverflow(new TermDf(ttxt,df));+ }}}} finally {diff --git a/lucene/contrib/demo/src/java/org/apache/lucene/demo/IndexHTML.java b/lucene/contrib/demo/src/java/org/apache/lucene/demo/IndexHTML.javaindex 8e5543d692c..07c18cbe3fd 100644--- a/lucene/contrib/demo/src/java/org/apache/lucene/demo/IndexHTML.java+++ b/lucene/contrib/demo/src/java/org/apache/lucene/demo/IndexHTML.java@@ -23,10 +23,13 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;+import org.apache.lucene.util.BytesRef;import java.io.File;import java.util.Date;@@ -39,7 +42,7 @@ public class IndexHTML {private static boolean deleting = false; // true during deletion passprivate static IndexReader reader; // existing indexprivate static IndexWriter writer; // new index being built- private static TermEnum uidIter; // document id iterator+ private static TermsEnum uidIter; // document id iterator/** Indexer for HTML files.*/public static void main(String[] argv) {@@ -110,21 +113,24 @@ public class IndexHTML {if (!create) { // incrementally updatereader = IndexReader.open(FSDirectory.open(index), false); // open existing index- uidIter = reader.terms(new Term("uid", "")); // init uid iterator+ Terms terms = MultiFields.getTerms(reader, "uid");+ if (terms != null) {+ uidIter = terms.iterator();- indexDocs(file);+ indexDocs(file);- if (deleting) { // delete rest of stale docs- while (uidIter.term() != null && uidIter.term().field() == "uid") {- System.out.println("deleting " +- HTMLDocument.uid2url(uidIter.term().text()));- reader.deleteDocuments(uidIter.term());- uidIter.next();+ if (deleting) { // delete rest of stale docs+ BytesRef text;+ while ((text=uidIter.next()) != null) {+ String termText = text.utf8ToString();+ System.out.println("deleting " ++ HTMLDocument.uid2url(termText));+ reader.deleteDocuments(new Term("uid", termText));+ }+ deleting = false;}- deleting = false;}- uidIter.close(); // close uid iteratorreader.close(); // close existing index} else // don't have exisiting@@ -145,17 +151,21 @@ public class IndexHTML {if (uidIter != null) {String uid = HTMLDocument.uid(file); // construct uid for doc- while (uidIter.term() != null && uidIter.term().field() == "uid" &&- uidIter.term().text().compareTo(uid) < 0) {- if (deleting) { // delete stale docs- System.out.println("deleting " +- HTMLDocument.uid2url(uidIter.term().text()));- reader.deleteDocuments(uidIter.term());+ BytesRef text;+ while((text = uidIter.next()) != null) {+ String termText = text.utf8ToString();+ if (termText.compareTo(uid) < 0) {+ if (deleting) { // delete stale docs+ System.out.println("deleting " ++ HTMLDocument.uid2url(termText));+ reader.deleteDocuments(new Term("uid", termText));+ }+ } else {+ break;}- uidIter.next();}- if (uidIter.term() != null && uidIter.term().field() == "uid" &&- uidIter.term().text().compareTo(uid) == 0) {+ if (text != null &&+ text.utf8ToString().compareTo(uid) == 0) {uidIter.next(); // keep matching docs} else if (!deleting) { // add new docsDocument doc = HTMLDocument.Document(file);diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedAllTermDocs.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedAllTermDocs.javadeleted file mode 100644index 24d8cca12d1..00000000000--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedAllTermDocs.java+++ /dev/null@@ -1,35 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.lucene.store.instantiated;--import org.apache.lucene.index.AbstractAllTermDocs;--class InstantiatedAllTermDocs extends AbstractAllTermDocs {-- private InstantiatedIndexReader reader;-- InstantiatedAllTermDocs(InstantiatedIndexReader reader) {- super(reader.maxDoc());- this.reader = reader;- }-- @Override- public boolean isDeleted(int doc) {- return reader.isDeleted(doc);- }-}diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedDocsEnum.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedDocsEnum.javaindex 123393f27ef..4bd43cb4027 100644--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedDocsEnum.java+++ b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedDocsEnum.java@@ -54,7 +54,7 @@ public class InstantiatedDocsEnum extends DocsEnum {@Overridepublic int advance(int target) {- if (currentDoc.getDocument().getDocumentNumber() >= target) {+ if (currentDoc != null && currentDoc.getDocument().getDocumentNumber() >= target) {return nextDoc();}diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndex.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndex.javaindex fc24e7427d8..8f2a3046ae8 100644--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndex.java+++ b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndex.java@@ -31,10 +31,15 @@ import org.apache.lucene.document.Document;import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Fields;+import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.TermPositionVector;-import org.apache.lucene.index.TermPositions;+import org.apache.lucene.index.DocsAndPositionsEnum;import org.apache.lucene.util.BitVector;+import org.apache.lucene.util.BytesRef;/*** Represented as a coupled graph of class instances, this@@ -220,34 +225,46 @@ public class InstantiatedIndex}}List<InstantiatedTerm> terms = new ArrayList<InstantiatedTerm>(5000 * getTermsByFieldAndText().size());- TermEnum termEnum = sourceIndexReader.terms();- while (termEnum.next()) {- if (fields == null || fields.contains(termEnum.term().field())) { // todo skipto if not using field- InstantiatedTerm instantiatedTerm = new InstantiatedTerm(termEnum.term().field(), termEnum.term().text());- getTermsByFieldAndText().get(termEnum.term().field()).put(termEnum.term().text(), instantiatedTerm);- instantiatedTerm.setTermIndex(terms.size());- terms.add(instantiatedTerm);- instantiatedTerm.setAssociatedDocuments(new InstantiatedTermDocumentInformation[termEnum.docFreq()]);+ Fields fieldsC = MultiFields.getFields(sourceIndexReader);+ if (fieldsC != null) {+ FieldsEnum fieldsEnum = fieldsC.iterator();+ String field;+ while((field = fieldsEnum.next()) != null) {+ if (fields == null || fields.contains(field)) {+ TermsEnum termsEnum = fieldsEnum.terms();+ BytesRef text;+ while((text = termsEnum.next()) != null) {+ String termText = text.utf8ToString();+ InstantiatedTerm instantiatedTerm = new InstantiatedTerm(field, termText);+ getTermsByFieldAndText().get(field).put(termText, instantiatedTerm);+ instantiatedTerm.setTermIndex(terms.size());+ terms.add(instantiatedTerm);+ instantiatedTerm.setAssociatedDocuments(new InstantiatedTermDocumentInformation[termsEnum.docFreq()]);+ }+ }}}- termEnum.close();orderedTerms = terms.toArray(new InstantiatedTerm[terms.size()]);// create term-document informationsfor (InstantiatedTerm term : orderedTerms) {- TermPositions termPositions = sourceIndexReader.termPositions(term.getTerm());+ DocsAndPositionsEnum termPositions = MultiFields.getTermPositionsEnum(sourceIndexReader,+ MultiFields.getDeletedDocs(sourceIndexReader),+ term.getTerm().field(),+ new BytesRef(term.getTerm().text()));int position = 0;- while (termPositions.next()) {- InstantiatedDocument document = documentsByNumber[termPositions.doc()];+ while (termPositions.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ InstantiatedDocument document = documentsByNumber[termPositions.docID()];byte[][] payloads = new byte[termPositions.freq()][];int[] positions = new int[termPositions.freq()];for (int i = 0; i < termPositions.freq(); i++) {positions[i] = termPositions.nextPosition();- if (termPositions.isPayloadAvailable()) {- payloads[i] = new byte[termPositions.getPayloadLength()];- termPositions.getPayload(payloads[i], 0);+ if (termPositions.hasPayload()) {+ BytesRef br = termPositions.getPayload();+ payloads[i] = new byte[br.length];+ System.arraycopy(br.bytes, br.offset, payloads[i], 0, br.length);}}diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.javaindex b20e5dccde0..6dac1cfb88d 100644--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java+++ b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java@@ -370,49 +370,11 @@ public class InstantiatedIndexReader extends IndexReader {}}- @Override- public TermEnum terms() throws IOException {- return new InstantiatedTermEnum(this);- }-- @Override- public TermEnum terms(Term t) throws IOException {- InstantiatedTerm it = getIndex().findTerm(t);- if (it != null) {- return new InstantiatedTermEnum(this, it.getTermIndex());- } else {- int startPos = Arrays.binarySearch(index.getOrderedTerms(), t, InstantiatedTerm.termComparator);- if (startPos < 0) {- startPos = -1 - startPos;- }- return new InstantiatedTermEnum(this, startPos);- }- }-- @Override- public TermDocs termDocs() throws IOException {- return new InstantiatedTermDocs(this);- }--- @Override- public TermDocs termDocs(Term term) throws IOException {- if (term == null) {- return new InstantiatedAllTermDocs(this);- } else {- InstantiatedTermDocs termDocs = new InstantiatedTermDocs(this);- termDocs.seek(term);- return termDocs;- }- }-- @Override- public TermPositions termPositions() throws IOException {- return new InstantiatedTermPositions(this);- }-@Overridepublic Fields fields() {+ if (getIndex().getOrderedTerms().length == 0) {+ return null;+ }return new Fields() {@Overridediff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermDocs.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermDocs.javadeleted file mode 100644index 850b4f1ac51..00000000000--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermDocs.java+++ /dev/null@@ -1,136 +0,0 @@-package org.apache.lucene.store.instantiated;--/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;--/**- * A {@link org.apache.lucene.index.TermDocs} navigating an {@link InstantiatedIndexReader}.- */-public class InstantiatedTermDocs- implements TermDocs {-- private final InstantiatedIndexReader reader;-- public InstantiatedTermDocs(InstantiatedIndexReader reader) {- this.reader = reader;- }-- private int currentDocumentIndex;- protected InstantiatedTermDocumentInformation currentDocumentInformation;- protected InstantiatedTerm currentTerm;--- public void seek(Term term) {- currentTerm = reader.getIndex().findTerm(term);- currentDocumentIndex = -1;- }-- public void seek(org.apache.lucene.index.TermEnum termEnum) {- seek(termEnum.term());- }--- public int doc() {- return currentDocumentInformation.getDocument().getDocumentNumber();- }-- public int freq() {- return currentDocumentInformation.getTermPositions().length;- }--- public boolean next() {- if (currentTerm != null) {- currentDocumentIndex++;- if (currentDocumentIndex < currentTerm.getAssociatedDocuments().length) {- currentDocumentInformation = currentTerm.getAssociatedDocuments()[currentDocumentIndex];- if (reader.isDeleted(currentDocumentInformation.getDocument().getDocumentNumber())) {- return next();- } else {- return true;- }- } else {- // mimic SegmentTermDocs- currentDocumentIndex = currentTerm.getAssociatedDocuments().length -1;- }- }- return false;- }--- public int read(int[] docs, int[] freqs) {- int i;- for (i = 0; i < docs.length; i++) {- if (!next()) {- break;- }- docs[i] = doc();- freqs[i] = freq();- }- return i;- }-- /**- * Skips entries to the first beyond the current whose document number is- * greater than or equal to <i>target</i>. <p>Returns true if there is such- * an entry. <p>Behaves as if written: <pre>- * boolean skipTo(int target) {- * do {- * if (!next())- * return false;- * } while (target > doc());- * return true;- * }- * </pre>- * This implementation is considerably more efficient than that.- *- */- public boolean skipTo(int target) {- if (currentTerm == null) {- return false;- }-- if (currentDocumentIndex >= target) {- return next();- }-- int startOffset = currentDocumentIndex >= 0 ? currentDocumentIndex : 0;- int pos = currentTerm.seekCeilingDocumentInformationIndex(target, startOffset);-- if (pos == -1) {- // mimic SegmentTermDocs that positions at the last index- currentDocumentIndex = currentTerm.getAssociatedDocuments().length -1;- return false;- }-- currentDocumentInformation = currentTerm.getAssociatedDocuments()[pos];- currentDocumentIndex = pos;- if (reader.hasDeletions() && reader.isDeleted(currentDocumentInformation.getDocument().getDocumentNumber())) {- return next();- } else {- return true;- }- }-- /**- * Does nothing- */- public void close() {- }-}diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermEnum.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermEnum.javadeleted file mode 100644index 91154c1b69b..00000000000--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermEnum.java+++ /dev/null@@ -1,83 +0,0 @@-package org.apache.lucene.store.instantiated;--/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;--/**- * A {@link org.apache.lucene.index.TermEnum} navigating an {@link org.apache.lucene.store.instantiated.InstantiatedIndexReader}.- */-public class InstantiatedTermEnum extends TermEnum {-- private final InstantiatedIndexReader reader;-- public InstantiatedTermEnum(InstantiatedIndexReader reader) {- this.nextTermIndex = 0;- this.reader = reader;- }-- public InstantiatedTermEnum(InstantiatedIndexReader reader, int startPosition) {- this.reader = reader;- this.nextTermIndex = startPosition;- next();- }-- private int nextTermIndex;- private InstantiatedTerm term;-- /**- * Increments the enumeration to the next element. True if one exists.- */- @Override- public boolean next() {- if (reader.getIndex().getOrderedTerms().length <= nextTermIndex) {- return false;- } else {- term = reader.getIndex().getOrderedTerms()[nextTermIndex];- nextTermIndex++;- return true;- }- }-- /**- * Returns the current Term in the enumeration.- */- @Override- public Term term() {- return term == null ? null : term.getTerm();- }-- /**- * Returns the docFreq of the current Term in the enumeration.- */- @Override- public int docFreq() {- return term.getAssociatedDocuments().length;- }-- /**- * Closes the enumeration to further activity, freeing resources.- */- @Override- public void close() {- }--}---diff --git a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermPositions.java b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermPositions.javadeleted file mode 100644index 73ebb1c47b7..00000000000--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedTermPositions.java+++ /dev/null@@ -1,100 +0,0 @@-package org.apache.lucene.store.instantiated;--/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.index.TermPositions;--import java.io.IOException;--/**- * A {@link org.apache.lucene.index.TermPositions} navigating an {@link InstantiatedIndexReader}.- */-public class InstantiatedTermPositions- extends InstantiatedTermDocs- implements TermPositions {-- public int getPayloadLength() {- return currentDocumentInformation.getPayloads()[currentTermPositionIndex].length;- }-- public byte[] getPayload(byte[] data, int offset) throws IOException {- byte[] payloads = currentDocumentInformation.getPayloads()[currentTermPositionIndex];-- // read payloads lazily- if (data == null || data.length - offset < getPayloadLength()) {- // the array is too small to store the payload data,- return payloads;- } else {- System.arraycopy(payloads, 0, data, offset, payloads.length);- return data;- }- }-- public boolean isPayloadAvailable() {- return currentDocumentInformation.getPayloads()[currentTermPositionIndex] != null;- }-- public InstantiatedTermPositions(InstantiatedIndexReader reader) {- super(reader);- }-- /**- * Returns next position in the current document. It is an error to call- * this more than {@link #freq()} times- * without calling {@link #next()}<p> This is- * invalid until {@link #next()} is called for- * the first time.- */- public int nextPosition() {- currentTermPositionIndex++;- // if you get an array out of index exception here,- // it might be due to currentDocumentInformation.getIndexFromTerm not being set!!- return currentDocumentInformation.getTermPositions()[currentTermPositionIndex];- }-- private int currentTermPositionIndex;-- /**- * Moves to the next pair in the enumeration.- * <p> Returns true if there is such a next pair in the enumeration.- */- @Override- public boolean next() {- currentTermPositionIndex = -1;- return super.next();- }-- /**- * Skips entries to the first beyond the current whose document number is- * greater than or equal to <currentTermPositionIndex>target</currentTermPositionIndex>. <p>Returns true iff there is such- * an entry. <p>Behaves as if written: <pre>- * boolean skipTo(int target) {- * do {- * if (!next())- * return false;- * } while (target > doc());- * return true;- * }- * </pre>- * Some implementations are considerably more efficient than that.- */- @Override- public boolean skipTo(int target) {- currentTermPositionIndex = -1;- return super.skipTo(target);- }-}diff --git a/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestEmptyIndex.java b/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestEmptyIndex.javaindex eead8c7f772..c103c66423a 100644--- a/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestEmptyIndex.java+++ b/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestEmptyIndex.java@@ -23,8 +23,8 @@ import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;@@ -84,11 +84,11 @@ public class TestEmptyIndex extends LuceneTestCase {}}- public void testTermEnum() throws Exception {+ public void testTermsEnum() throws Exception {InstantiatedIndex ii = new InstantiatedIndex();IndexReader r = new InstantiatedIndexReader(ii);- termEnumTest(r);+ termsEnumTest(r);r.close();ii.close();@@ -97,17 +97,13 @@ public class TestEmptyIndex extends LuceneTestCase {Directory d = new RAMDirectory();new IndexWriter(d, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer())).close();r = IndexReader.open(d, false);- termEnumTest(r);+ termsEnumTest(r);r.close();d.close();}- public void termEnumTest(IndexReader r) throws Exception {- TermEnum terms = r.terms();-- assertNull(terms.term());- assertFalse(terms.next());-+ public void termsEnumTest(IndexReader r) throws Exception {+ assertNull(MultiFields.getFields(r));}}diff --git a/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestIndicesEquals.java b/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestIndicesEquals.javaindex ebb66c8d5a4..10a4fba0209 100644--- a/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestIndicesEquals.java+++ b/lucene/contrib/instantiated/src/test/org/apache/lucene/store/instantiated/TestIndicesEquals.java@@ -33,15 +33,18 @@ import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Payload;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.FieldsEnum;import org.apache.lucene.index.TermFreqVector;import org.apache.lucene.index.TermPositionVector;-import org.apache.lucene.index.TermPositions;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.AttributeImpl;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;/*** Asserts equality of content and behaviour of two index readers.@@ -120,131 +123,69 @@ public class TestIndicesEquals extends LuceneTestCase {// test seekTerm t = new Term("c", "danny");- TermEnum aprioriTermEnum = aprioriReader.terms(t);- TermEnum testTermEnum = testReader.terms(t);-+ TermsEnum aprioriTermEnum = MultiFields.getTerms(aprioriReader, t.field()).iterator();+ aprioriTermEnum.seek(new BytesRef(t.text()));+ TermsEnum testTermEnum = MultiFields.getTerms(testReader, t.field()).iterator();+ testTermEnum.seek(new BytesRef(t.text()));assertEquals(aprioriTermEnum.term(), testTermEnum.term());- t = aprioriTermEnum.term();-- aprioriTermEnum.close();- testTermEnum.close();+ DocsEnum aprioriTermDocs = aprioriTermEnum.docs(MultiFields.getDeletedDocs(aprioriReader), null);+ DocsEnum testTermDocs = testTermEnum.docs(MultiFields.getDeletedDocs(testReader), null);- TermDocs aprioriTermDocs = aprioriReader.termDocs(t);- TermDocs testTermDocs = testReader.termDocs(t);-- assertEquals(aprioriTermDocs.next(), testTermDocs.next());+ assertEquals(aprioriTermDocs.nextDoc(), testTermDocs.nextDoc());assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- if (aprioriTermDocs.skipTo(4)) {- assertTrue(testTermDocs.skipTo(4));+ if (aprioriTermDocs.advance(4) != DocsEnum.NO_MORE_DOCS) {+ assertTrue(testTermDocs.advance(4) != DocsEnum.NO_MORE_DOCS);assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());} else {- assertFalse(testTermDocs.skipTo(4));+ assertEquals(DocsEnum.NO_MORE_DOCS, testTermDocs.advance(4));}- if (aprioriTermDocs.next()) {- assertTrue(testTermDocs.next());+ if (aprioriTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ assertTrue(testTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());} else {- assertFalse(testTermDocs.next());+ assertEquals(DocsEnum.NO_MORE_DOCS, testTermDocs.nextDoc());}// beyond this point all next and skipto will return false- if (aprioriTermDocs.skipTo(100)) {- assertTrue(testTermDocs.skipTo(100));- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- } else {- assertFalse(testTermDocs.skipTo(100));- }--- if (aprioriTermDocs.next()) {- assertTrue(testTermDocs.next());- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- } else {- assertFalse(testTermDocs.next());- }-- if (aprioriTermDocs.skipTo(110)) {- assertTrue(testTermDocs.skipTo(110));- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- } else {- assertFalse(testTermDocs.skipTo(110));- }-- if (aprioriTermDocs.skipTo(10)) {- assertTrue(testTermDocs.skipTo(10));- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- } else {- assertFalse(testTermDocs.skipTo(10));- }--- if (aprioriTermDocs.skipTo(210)) {- assertTrue(testTermDocs.skipTo(210));+ if (aprioriTermDocs.advance(100) != DocsEnum.NO_MORE_DOCS) {+ assertTrue(testTermDocs.advance(100) != DocsEnum.NO_MORE_DOCS);assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());} else {- assertFalse(testTermDocs.skipTo(210));+ assertEquals(DocsEnum.NO_MORE_DOCS, testTermDocs.advance(100));}- aprioriTermDocs.close();- testTermDocs.close();---- // test seek null (AllTermDocs)- aprioriTermDocs = aprioriReader.termDocs(null);- testTermDocs = testReader.termDocs(null);-- while (aprioriTermDocs.next()) {- assertTrue(testTermDocs.next());- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- }- assertFalse(testTermDocs.next());--- aprioriTermDocs.close();- testTermDocs.close();--- // test seek default- aprioriTermDocs = aprioriReader.termDocs();- testTermDocs = testReader.termDocs();-- // this is invalid use of the API,- // but if the response differs then it's an indication that something might have changed.- // in 2.9 and 3.0 the two TermDocs-implementations returned different values at this point.-// assertEquals("Descripency during invalid use of the TermDocs API, see comments in test code for details.",-// aprioriTermDocs.next(), testTermDocs.next());-// start using the API the way one is supposed to use itt = new Term("", "");- aprioriTermDocs.seek(t);- testTermDocs.seek(t);-- while (aprioriTermDocs.next()) {- assertTrue(testTermDocs.next());+ FieldsEnum apFieldsEnum = MultiFields.getFields(aprioriReader).iterator();+ String apFirstField = apFieldsEnum.next();++ FieldsEnum testFieldsEnum = MultiFields.getFields(testReader).iterator();+ String testFirstField = testFieldsEnum.next();+ assertEquals(apFirstField, testFirstField);++ aprioriTermEnum = apFieldsEnum.terms();+ testTermEnum = testFieldsEnum.terms();++ assertEquals(aprioriTermEnum.next(), testTermEnum.next());++ aprioriTermDocs = aprioriTermEnum.docs(MultiFields.getDeletedDocs(aprioriReader), aprioriTermDocs);+ testTermDocs = testTermEnum.docs(MultiFields.getDeletedDocs(testReader), testTermDocs);++ while (aprioriTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ assertTrue(testTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());}- assertFalse(testTermDocs.next());-- aprioriTermDocs.close();- testTermDocs.close();-+ assertEquals(DocsEnum.NO_MORE_DOCS, testTermDocs.nextDoc());// clean upaprioriReader.close();@@ -443,98 +384,85 @@ public class TestIndicesEquals extends LuceneTestCase {// compare term enumeration stepping- TermEnum aprioriTermEnum = aprioriReader.terms();- TermEnum testTermEnum = testReader.terms();+ FieldsEnum aprioriFieldsEnum = MultiFields.getFields(aprioriReader).iterator();+ FieldsEnum testFieldsEnum = MultiFields.getFields(testReader).iterator();+ String aprioriField;+ while((aprioriField = aprioriFieldsEnum.next()) != null) {+ String testField = testFieldsEnum.next();+ assertEquals(aprioriField, testField);- while (true) {-- if (!aprioriTermEnum.next()) {- assertFalse(testTermEnum.next());- break;- }- assertTrue(testTermEnum.next());+ TermsEnum aprioriTermEnum = aprioriFieldsEnum.terms();+ TermsEnum testTermEnum = testFieldsEnum.terms();- assertEquals(aprioriTermEnum.term(), testTermEnum.term());- assertTrue(aprioriTermEnum.docFreq() == testTermEnum.docFreq());+ BytesRef aprioriText;+ while((aprioriText = aprioriTermEnum.next()) != null) {+ assertEquals(aprioriText, testTermEnum.next());- // compare termDocs seeking+ assertTrue(aprioriTermEnum.docFreq() == testTermEnum.docFreq());- TermDocs aprioriTermDocsSeeker = aprioriReader.termDocs(aprioriTermEnum.term());- TermDocs testTermDocsSeeker = testReader.termDocs(testTermEnum.term());+ // compare termDocs seeking- while (aprioriTermDocsSeeker.next()) {- assertTrue(testTermDocsSeeker.skipTo(aprioriTermDocsSeeker.doc()));- assertEquals(aprioriTermDocsSeeker.doc(), testTermDocsSeeker.doc());- }-- aprioriTermDocsSeeker.close();- testTermDocsSeeker.close();-- // compare documents per term-- assertEquals(aprioriReader.docFreq(aprioriTermEnum.term()), testReader.docFreq(testTermEnum.term()));-- TermDocs aprioriTermDocs = aprioriReader.termDocs(aprioriTermEnum.term());- TermDocs testTermDocs = testReader.termDocs(testTermEnum.term());-- while (true) {- if (!aprioriTermDocs.next()) {- assertFalse(testTermDocs.next());- break;+ DocsEnum aprioriTermDocs = aprioriTermEnum.docs(MultiFields.getDeletedDocs(aprioriReader), null);+ DocsEnum testTermDocs = testTermEnum.docs(MultiFields.getDeletedDocs(testReader), null);++ while (aprioriTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ assertTrue(testTermDocs.advance(aprioriTermDocs.docID()) != DocsEnum.NO_MORE_DOCS);+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());}- assertTrue(testTermDocs.next());-- assertEquals(aprioriTermDocs.doc(), testTermDocs.doc());- assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());- }++ // compare documents per term++ assertEquals(aprioriReader.docFreq(aprioriField, aprioriTermEnum.term()), testReader.docFreq(aprioriField, testTermEnum.term()));- aprioriTermDocs.close();- testTermDocs.close();+ aprioriTermDocs = aprioriTermEnum.docs(MultiFields.getDeletedDocs(aprioriReader), aprioriTermDocs);+ testTermDocs = testTermEnum.docs(MultiFields.getDeletedDocs(testReader), testTermDocs);- // compare term positions+ while (true) {+ if (aprioriTermDocs.nextDoc() == DocsEnum.NO_MORE_DOCS) {+ assertEquals(DocsEnum.NO_MORE_DOCS, testTermDocs.nextDoc());+ break;+ }+ assertTrue(testTermDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);- TermPositions testTermPositions = testReader.termPositions(testTermEnum.term());- TermPositions aprioriTermPositions = aprioriReader.termPositions(aprioriTermEnum.term());+ assertEquals(aprioriTermDocs.docID(), testTermDocs.docID());+ assertEquals(aprioriTermDocs.freq(), testTermDocs.freq());+ }- if (aprioriTermPositions != null) {+ // compare term positions- for (int docIndex = 0; docIndex < aprioriReader.maxDoc(); docIndex++) {- boolean hasNext = aprioriTermPositions.next();- if (hasNext) {- assertTrue(testTermPositions.next());+ DocsAndPositionsEnum aprioriTermPositions = aprioriTermEnum.docsAndPositions(MultiFields.getDeletedDocs(aprioriReader), null);+ DocsAndPositionsEnum testTermPositions = testTermEnum.docsAndPositions(MultiFields.getDeletedDocs(testReader), null);- assertEquals(aprioriTermPositions.freq(), testTermPositions.freq());+ if (aprioriTermPositions != null) {+ for (int docIndex = 0; docIndex < aprioriReader.maxDoc(); docIndex++) {+ boolean hasNext = aprioriTermPositions.nextDoc() != DocsEnum.NO_MORE_DOCS;+ if (hasNext) {+ assertTrue(testTermPositions.nextDoc() != DocsEnum.NO_MORE_DOCS);++ assertEquals(aprioriTermPositions.freq(), testTermPositions.freq());- for (int termPositionIndex = 0; termPositionIndex < aprioriTermPositions.freq(); termPositionIndex++) {- int aprioriPos = aprioriTermPositions.nextPosition();- int testPos = testTermPositions.nextPosition();+ for (int termPositionIndex = 0; termPositionIndex < aprioriTermPositions.freq(); termPositionIndex++) {+ int aprioriPos = aprioriTermPositions.nextPosition();+ int testPos = testTermPositions.nextPosition();- if (aprioriPos != testPos) {assertEquals(aprioriPos, testPos);- }-- assertEquals(aprioriTermPositions.isPayloadAvailable(), testTermPositions.isPayloadAvailable());- if (aprioriTermPositions.isPayloadAvailable()) {- assertEquals(aprioriTermPositions.getPayloadLength(), testTermPositions.getPayloadLength());- byte[] aprioriPayloads = aprioriTermPositions.getPayload(new byte[aprioriTermPositions.getPayloadLength()], 0);- byte[] testPayloads = testTermPositions.getPayload(new byte[testTermPositions.getPayloadLength()], 0);- for (int i = 0; i < aprioriPayloads.length; i++) {- assertEquals(aprioriPayloads[i], testPayloads[i]);+ assertEquals(aprioriTermPositions.hasPayload(), testTermPositions.hasPayload());+ if (aprioriTermPositions.hasPayload()) {+ BytesRef apPayload = aprioriTermPositions.getPayload();+ BytesRef testPayload = testTermPositions.getPayload();+ assertEquals(apPayload, testPayload);}}-}}}-- aprioriTermPositions.close();- testTermPositions.close();-}+ assertNull(testTermEnum.next());}+ assertNull(testFieldsEnum.next());// compare term vectors and position vectors@@ -589,12 +517,8 @@ public class TestIndicesEquals extends LuceneTestCase {}}-}- aprioriTermEnum.close();- testTermEnum.close();-aprioriReader.close();testReader.close();}diff --git a/lucene/contrib/lucli/src/java/lucli/LuceneMethods.java b/lucene/contrib/lucli/src/java/lucli/LuceneMethods.javaindex 5671f476848..3b351d8e517 100644--- a/lucene/contrib/lucli/src/java/lucli/LuceneMethods.java+++ b/lucene/contrib/lucli/src/java/lucli/LuceneMethods.java@@ -43,8 +43,10 @@ import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.Fields;+import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.IndexReader.FieldOption;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.queryParser.MultiFieldQueryParser;@@ -58,6 +60,7 @@ import org.apache.lucene.search.Scorer;import org.apache.lucene.search.Searcher;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;+import org.apache.lucene.util.BytesRef;/*** Various methods that interact with Lucene and provide info about the@@ -342,13 +345,21 @@ class LuceneMethods {public void terms(String field) throws IOException {TreeMap<String,Integer> termMap = new TreeMap<String,Integer>();IndexReader indexReader = IndexReader.open(indexName, true);- TermEnum terms = indexReader.terms();- while (terms.next()) {- Term term = terms.term();- //message(term.field() + ":" + term.text() + " freq:" + terms.docFreq());- //if we're either not looking by field or we're matching the specific field- if ((field == null) || field.equals(term.field()))- termMap.put(term.field() + ":" + term.text(), Integer.valueOf((terms.docFreq())));+ Fields fields = MultiFields.getFields(indexReader);+ if (fields != null) {+ FieldsEnum fieldsEnum = fields.iterator();+ String curField;+ while((curField = fieldsEnum.next()) != null) {+ TermsEnum terms = fieldsEnum.terms();+ BytesRef text;+ while ((text = terms.next()) != null) {+ //message(term.field() + ":" + term.text() + " freq:" + terms.docFreq());+ //if we're either not looking by field or we're matching the specific field+ if ((field == null) || field.equals(curField)) {+ termMap.put(curField + ":" + text.utf8ToString(), Integer.valueOf((terms.docFreq())));+ }+ }+ }}Iterator<String> termIterator = termMap.keySet().iterator();diff --git a/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java b/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.javaindex 9aa0a6ca9c3..39834075ced 100644--- a/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java+++ b/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java@@ -44,11 +44,8 @@ import org.apache.lucene.index.FieldsEnum;import org.apache.lucene.index.DocsEnum;import org.apache.lucene.index.DocsAndPositionsEnum;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;import org.apache.lucene.index.TermFreqVector;import org.apache.lucene.index.TermPositionVector;-import org.apache.lucene.index.TermPositions;import org.apache.lucene.index.TermVectorMapper;import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.search.Collector;@@ -732,7 +729,6 @@ public class MemoryIndex implements Serializable {///////////////////////////////////////////////////////////////////////////////// Nested classes:///////////////////////////////////////////////////////////////////////////////- private static final Term MATCH_ALL_TERM = new Term("");/*** Search support for Lucene framework integration; implements all methods@@ -768,12 +764,6 @@ public class MemoryIndex implements Serializable {return freq;}- @Override- public TermEnum terms() {- if (DEBUG) System.err.println("MemoryIndexReader.terms()");- return terms(MATCH_ALL_TERM);- }-@Overridepublic Fields fields() {@@ -1010,202 +1000,6 @@ public class MemoryIndex implements Serializable {}}- @Override- public TermEnum terms(Term term) {- if (DEBUG) System.err.println("MemoryIndexReader.terms: " + term);-- int i; // index into info.sortedTerms- int j; // index into sortedFields-- sortFields();- if (sortedFields.length == 1 && sortedFields[0].getKey() == term.field()) {- j = 0; // fast path- } else {- j = Arrays.binarySearch(sortedFields, term.field(), termComparator);- }-- if (j < 0) { // not found; choose successor- j = -j -1;- i = 0;- if (j < sortedFields.length) getInfo(j).sortTerms();- } else { // found- Info info = getInfo(j);- info.sortTerms();- i = Arrays.binarySearch(info.sortedTerms, term.text(), termComparator);- if (i < 0) { // not found; choose successor- i = -i -1;- if (i >= info.sortedTerms.length) { // move to next successor- j++;- i = 0;- if (j < sortedFields.length) getInfo(j).sortTerms();- }- }- }- final int ix = i;- final int jx = j;-- return new TermEnum() {-- private int srtTermsIdx = ix; // index into info.sortedTerms- private int srtFldsIdx = jx; // index into sortedFields-- @Override- public boolean next() {- if (DEBUG) System.err.println("TermEnum.next");- if (srtFldsIdx >= sortedFields.length) return false;- Info info = getInfo(srtFldsIdx);- if (++srtTermsIdx < info.sortedTerms.length) return true;-- // move to successor- srtFldsIdx++;- srtTermsIdx = 0;- if (srtFldsIdx >= sortedFields.length) return false;- getInfo(srtFldsIdx).sortTerms();- return true;- }-- @Override- public Term term() {- if (DEBUG) System.err.println("TermEnum.term: " + srtTermsIdx);- if (srtFldsIdx >= sortedFields.length) return null;- Info info = getInfo(srtFldsIdx);- if (srtTermsIdx >= info.sortedTerms.length) return null;-// if (DEBUG) System.err.println("TermEnum.term: " + i + ", " + info.sortedTerms[i].getKey());- return createTerm(info, srtFldsIdx, info.sortedTerms[srtTermsIdx].getKey());- }-- @Override- public int docFreq() {- if (DEBUG) System.err.println("TermEnum.docFreq");- if (srtFldsIdx >= sortedFields.length) return 0;- Info info = getInfo(srtFldsIdx);- if (srtTermsIdx >= info.sortedTerms.length) return 0;- return numPositions(info.getPositions(srtTermsIdx));- }-- @Override- public void close() {- if (DEBUG) System.err.println("TermEnum.close");- }-- /** Returns a new Term object, minimizing String.intern() overheads. */- private Term createTerm(Info info, int pos, String text) {- // Assertion: sortFields has already been called before- Term template = info.template;- if (template == null) { // not yet cached?- String fieldName = sortedFields[pos].getKey();- template = new Term(fieldName);- info.template = template;- }-- return template.createTerm(text);- }-- };- }-- @Override- public TermPositions termPositions() {- if (DEBUG) System.err.println("MemoryIndexReader.termPositions");-- return new TermPositions() {-- private boolean hasNext;- private int cursor = 0;- private ArrayIntList current;- private Term term;-- public void seek(Term term) {- this.term = term;- if (DEBUG) System.err.println(".seek: " + term);- if (term == null) {- hasNext = true; // term==null means match all docs- } else {- Info info = getInfo(term.field());- current = info == null ? null : info.getPositions(term.text());- hasNext = (current != null);- cursor = 0;- }- }-- public void seek(TermEnum termEnum) {- if (DEBUG) System.err.println(".seekEnum");- seek(termEnum.term());- }-- public int doc() {- if (DEBUG) System.err.println(".doc");- return 0;- }-- public int freq() {- int freq = current != null ? numPositions(current) : (term == null ? 1 : 0);- if (DEBUG) System.err.println(".freq: " + freq);- return freq;- }-- public boolean next() {- if (DEBUG) System.err.println(".next: " + current + ", oldHasNext=" + hasNext);- boolean next = hasNext;- hasNext = false;- return next;- }-- public int read(int[] docs, int[] freqs) {- if (DEBUG) System.err.println(".read: " + docs.length);- if (!hasNext) return 0;- hasNext = false;- docs[0] = 0;- freqs[0] = freq();- return 1;- }-- public boolean skipTo(int target) {- if (DEBUG) System.err.println(".skipTo: " + target);- return next();- }-- public void close() {- if (DEBUG) System.err.println(".close");- }-- public int nextPosition() { // implements TermPositions- int pos = current.get(cursor);- cursor += stride;- if (DEBUG) System.err.println(".nextPosition: " + pos);- return pos;- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public int getPayloadLength() {- throw new UnsupportedOperationException();- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public byte[] getPayload(byte[] data, int offset) throws IOException {- throw new UnsupportedOperationException();- }-- public boolean isPayloadAvailable() {- // unsuported- return false;- }-- };- }-- @Override- public TermDocs termDocs() {- if (DEBUG) System.err.println("MemoryIndexReader.termDocs");- return termPositions();- }-@Overridepublic TermFreqVector[] getTermFreqVectors(int docNumber) {if (DEBUG) System.err.println("MemoryIndexReader.getTermFreqVectors");diff --git a/lucene/contrib/misc/src/java/org/apache/lucene/misc/LengthNormModifier.java b/lucene/contrib/misc/src/java/org/apache/lucene/misc/LengthNormModifier.javaindex d75043d94cd..8e2c7290f34 100644--- a/lucene/contrib/misc/src/java/org/apache/lucene/misc/LengthNormModifier.java+++ b/lucene/contrib/misc/src/java/org/apache/lucene/misc/LengthNormModifier.java@@ -16,14 +16,16 @@ package org.apache.lucene.misc;* limitations under the License.*/-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.index.TermDocs;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.DocsEnum;import org.apache.lucene.search.Similarity;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.Bits;import java.io.File;import java.io.IOException;@@ -109,37 +111,25 @@ public class LengthNormModifier {String fieldName = StringHelper.intern(field);int[] termCounts = new int[0];- IndexReader reader = null;- TermEnum termEnum = null;- TermDocs termDocs = null;+ IndexReader reader = IndexReader.open(dir, false);try {- reader = IndexReader.open(dir, false);+termCounts = new int[reader.maxDoc()];- try {- termEnum = reader.terms(new Term(field));- try {- termDocs = reader.termDocs();- do {- Term term = termEnum.term();- if (term != null && term.field().equals(fieldName)) {- termDocs.seek(termEnum.term());- while (termDocs.next()) {- termCounts[termDocs.doc()] += termDocs.freq();- }- }- } while (termEnum.next());- } finally {- if (null != termDocs) termDocs.close();+ Bits delDocs = MultiFields.getDeletedDocs(reader);+ DocsEnum docs = null;++ Terms terms = MultiFields.getTerms(reader, field);+ if (terms != null) {+ TermsEnum termsEnum = terms.iterator();+ while(termsEnum.next() != null) {+ docs = termsEnum.docs(delDocs, docs);+ int doc;+ while ((doc = docs.nextDoc()) != DocsEnum.NO_MORE_DOCS) {+ termCounts[doc] += docs.freq();+ }}- } finally {- if (null != termEnum) termEnum.close();}- } finally {- if (null != reader) reader.close();- }-- try {- reader = IndexReader.open(dir, false);+for (int d = 0; d < termCounts.length; d++) {if (! reader.isDeleted(d)) {byte norm = Similarity.encodeNorm(sim.lengthNorm(fieldName, termCounts[d]));@@ -147,7 +137,7 @@ public class LengthNormModifier {}}} finally {- if (null != reader) reader.close();+ reader.close();}}diff --git a/lucene/contrib/misc/src/test/org/apache/lucene/index/TestMultiPassIndexSplitter.java b/lucene/contrib/misc/src/test/org/apache/lucene/index/TestMultiPassIndexSplitter.javaindex 8e470925022..e9bc8027996 100644--- a/lucene/contrib/misc/src/test/org/apache/lucene/index/TestMultiPassIndexSplitter.java+++ b/lucene/contrib/misc/src/test/org/apache/lucene/index/TestMultiPassIndexSplitter.java@@ -22,6 +22,7 @@ import org.apache.lucene.document.Field;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;public class TestMultiPassIndexSplitter extends LuceneTestCase {IndexReader input;@@ -62,30 +63,30 @@ public class TestMultiPassIndexSplitter extends LuceneTestCase {assertTrue(ir.numDocs() - NUM_DOCS / 3 <= 1); // rounding errorDocument doc = ir.document(0);assertEquals("0", doc.get("id"));- Term t;- TermEnum te;- t = new Term("id", "1");- te = ir.terms(t);- assertNotSame(t, te.term());+ TermsEnum te = MultiFields.getTerms(ir, "id").iterator();+ assertEquals(TermsEnum.SeekStatus.NOT_FOUND, te.seek(new BytesRef("1")));+ assertNotSame("1", te.term().utf8ToString());ir.close();ir = IndexReader.open(dirs[1], true);assertTrue(ir.numDocs() - NUM_DOCS / 3 <= 1);doc = ir.document(0);assertEquals("1", doc.get("id"));- t = new Term("id", "0");- te = ir.terms(t);- assertNotSame(t, te.term());+ te = MultiFields.getTerms(ir, "id").iterator();+ assertEquals(TermsEnum.SeekStatus.NOT_FOUND, te.seek(new BytesRef("0")));++ assertNotSame("0", te.term().utf8ToString());ir.close();ir = IndexReader.open(dirs[2], true);assertTrue(ir.numDocs() - NUM_DOCS / 3 <= 1);doc = ir.document(0);assertEquals("2", doc.get("id"));- t = new Term("id", "1");- te = ir.terms(t);- assertNotSame(t, te.term());- t = new Term("id", "0");- te = ir.terms(t);- assertNotSame(t, te.term());++ te = MultiFields.getTerms(ir, "id").iterator();+ assertEquals(TermsEnum.SeekStatus.NOT_FOUND, te.seek(new BytesRef("1")));+ assertNotSame("1", te.term());++ assertEquals(TermsEnum.SeekStatus.NOT_FOUND, te.seek(new BytesRef("0")));+ assertNotSame("0", te.term().utf8ToString());}/**@@ -117,10 +118,9 @@ public class TestMultiPassIndexSplitter extends LuceneTestCase {doc = ir.document(0);assertEquals(start + "", doc.get("id"));// make sure the deleted doc is not here- Term t;- TermEnum te;- t = new Term("id", (NUM_DOCS - 1) + "");- te = ir.terms(t);- assertNotSame(t, te.term());+ TermsEnum te = MultiFields.getTerms(ir, "id").iterator();+ Term t = new Term("id", (NUM_DOCS - 1) + "");+ assertEquals(TermsEnum.SeekStatus.NOT_FOUND, te.seek(new BytesRef(t.text())));+ assertNotSame(t.text(), te.term().utf8ToString());}}diff --git a/lucene/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java b/lucene/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.javaindex d476023d235..642de6df390 100644--- a/lucene/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java+++ b/lucene/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java@@ -24,8 +24,14 @@ import java.util.TreeSet;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.index.Fields;import org.apache.lucene.util.OpenBitSet;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.Bits;/*** Constructs a filter for docs matching any of the terms added to this class.@@ -52,28 +58,37 @@ public class TermsFilter extends Filter* @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.IndexReader)*/@Override- public DocIdSet getDocIdSet(IndexReader reader) throws IOException- {+ public DocIdSet getDocIdSet(IndexReader reader) throws IOException {OpenBitSet result=new OpenBitSet(reader.maxDoc());- TermDocs td = reader.termDocs();- try- {- for (Iterator<Term> iter = terms.iterator(); iter.hasNext();)- {- Term term = iter.next();- td.seek(term);- while (td.next())- {- result.set(td.doc());- }- }+ Fields fields = MultiFields.getFields(reader);+ BytesRef br = new BytesRef();+ Bits delDocs = MultiFields.getDeletedDocs(reader);+ if (fields != null) {+ String lastField = null;+ Terms termsC = null;+ TermsEnum termsEnum = null;+ DocsEnum docs = null;+ for (Iterator<Term> iter = terms.iterator(); iter.hasNext();) {+ Term term = iter.next();+ if (term.field() != lastField) {+ termsC = fields.terms(term.field());+ termsEnum = termsC.iterator();+ lastField = term.field();}- finally- {- td.close();++ if (terms != null) {+ br.copy(term.text());+ if (termsEnum.seek(br) == TermsEnum.SeekStatus.FOUND) {+ docs = termsEnum.docs(delDocs, docs);+ while(docs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ result.set(docs.docID());+ }+ }}- return result;- }+ }+ }+ return result;+ }@Overridepublic boolean equals(Object obj)diff --git a/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexQuery.java b/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexQuery.javaindex 54d62b598a0..e15221d13ec 100644--- a/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexQuery.java+++ b/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexQuery.java@@ -18,7 +18,7 @@ package org.apache.lucene.search.regex;*/import org.apache.lucene.search.MultiTermQuery;-import org.apache.lucene.search.FilteredTermEnum;+import org.apache.lucene.search.FilteredTermsEnum;import org.apache.lucene.index.Term;import org.apache.lucene.index.IndexReader;import org.apache.lucene.util.ToStringUtils;@@ -60,8 +60,8 @@ public class RegexQuery extends MultiTermQuery implements RegexQueryCapable {}@Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new RegexTermEnum(reader, term, regexImpl);+ protected FilteredTermsEnum getTermsEnum(IndexReader reader) throws IOException {+ return new RegexTermsEnum(reader, term, regexImpl);}@Overridediff --git a/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermEnum.java b/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermsEnum.javasimilarity index 59%rename from lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermEnum.javarename to lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermsEnum.javaindex ae814aafb5f..fa04921ed9f 100644--- a/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermEnum.java+++ b/lucene/contrib/queries/src/java/org/apache/lucene/search/regex/RegexTermsEnum.java@@ -17,9 +17,10 @@ package org.apache.lucene.search.regex;* limitations under the License.*/-import org.apache.lucene.search.FilteredTermEnum;+import org.apache.lucene.search.FilteredTermsEnum;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;+import org.apache.lucene.util.BytesRef;import java.io.IOException;@@ -32,52 +33,32 @@ import java.io.IOException;* the enumeration is greater than all that precede it.*/-public class RegexTermEnum extends FilteredTermEnum {- private String field = "";- private String pre = "";- private boolean endEnum = false;+public class RegexTermsEnum extends FilteredTermsEnum {private RegexCapabilities regexImpl;+ private final BytesRef prefixRef;- public RegexTermEnum(IndexReader reader, Term term, RegexCapabilities regexImpl) throws IOException {- super();- field = term.field();+ public RegexTermsEnum(IndexReader reader, Term term, RegexCapabilities regexImpl) throws IOException {+ super(reader, term.field());String text = term.text();this.regexImpl = regexImpl;regexImpl.compile(text);- pre = regexImpl.prefix();+ String pre = regexImpl.prefix();if (pre == null) pre = "";- setEnum(reader.terms(new Term(term.field(), pre)));+ setInitialSeekTerm(prefixRef = new BytesRef(pre));}@Override- protected final boolean termCompare(Term term) {- if (field == term.field()) {- String searchText = term.text();- if (searchText.startsWith(pre)) {- return regexImpl.match(searchText);- }+ protected AcceptStatus accept(BytesRef term) {+ if (term.startsWith(prefixRef)) {+ // TODO: set BoostAttr based on distance of+ // searchTerm.text() and term().text()+ String text = term.utf8ToString();+ return regexImpl.match(text) ? AcceptStatus.YES : AcceptStatus.NO;+ } else {+ return AcceptStatus.NO;}- endEnum = true;- return false;- }-- @Override- public final float difference() {-// TODO: adjust difference based on distance of searchTerm.text() and term().text()- return 1.0f;- }-- @Override- public final boolean endEnum() {- return endEnum;- }-- @Override- public void close() throws IOException {- super.close();- field = null;}}diff --git a/lucene/contrib/queries/src/test/org/apache/lucene/search/DuplicateFilterTest.java b/lucene/contrib/queries/src/test/org/apache/lucene/search/DuplicateFilterTest.javaindex a2e701920b9..7cfe74b02af 100644--- a/lucene/contrib/queries/src/test/org/apache/lucene/search/DuplicateFilterTest.java+++ b/lucene/contrib/queries/src/test/org/apache/lucene/search/DuplicateFilterTest.java@@ -27,9 +27,11 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;public class DuplicateFilterTest extends LuceneTestCase {private static final String KEY_FIELD = "url";@@ -134,11 +136,14 @@ public class DuplicateFilterTest extends LuceneTestCase {{Document d=searcher.doc(hits[i].doc);String url=d.get(KEY_FIELD);- TermDocs td = reader.termDocs(new Term(KEY_FIELD,url));+ DocsEnum td = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ KEY_FIELD,+ new BytesRef(url));int lastDoc=0;- while(td.next())+ while(td.nextDoc() != DocsEnum.NO_MORE_DOCS){- lastDoc=td.doc();+ lastDoc=td.docID();}assertEquals("Duplicate urls should return last doc",lastDoc, hits[i].doc);}@@ -155,10 +160,13 @@ public class DuplicateFilterTest extends LuceneTestCase {{Document d=searcher.doc(hits[i].doc);String url=d.get(KEY_FIELD);- TermDocs td = reader.termDocs(new Term(KEY_FIELD,url));+ DocsEnum td = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ KEY_FIELD,+ new BytesRef(url));int lastDoc=0;- td.next();- lastDoc=td.doc();+ td.nextDoc();+ lastDoc=td.docID();assertEquals("Duplicate urls should return first doc",lastDoc, hits[i].doc);}}diff --git a/lucene/contrib/queries/src/test/org/apache/lucene/search/regex/TestRegexQuery.java b/lucene/contrib/queries/src/test/org/apache/lucene/search/regex/TestRegexQuery.javaindex de1ad10fb7b..36a4473b894 100644--- a/lucene/contrib/queries/src/test/org/apache/lucene/search/regex/TestRegexQuery.java+++ b/lucene/contrib/queries/src/test/org/apache/lucene/search/regex/TestRegexQuery.java@@ -25,7 +25,7 @@ import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;import org.apache.lucene.search.spans.SpanNearQuery;import org.apache.lucene.search.spans.SpanQuery;@@ -80,10 +80,9 @@ public class TestRegexQuery extends LuceneTestCase {}public void testMatchAll() throws Exception {- TermEnum terms = new RegexQuery(new Term(FN, "jum.")).getEnum(searcher.getIndexReader());+ TermsEnum terms = new RegexQuery(new Term(FN, "jum.")).getTermsEnum(searcher.getIndexReader());// no term should match- assertNull(terms.term());- assertFalse(terms.next());+ assertNull(terms.next());}public void testRegex1() throws Exception {diff --git a/lucene/contrib/queryparser/src/java/org/apache/lucene/queryParser/surround/query/SpanNearClauseFactory.java b/lucene/contrib/queryparser/src/java/org/apache/lucene/queryParser/surround/query/SpanNearClauseFactory.javaindex 045974c0515..4aa56f3151e 100644--- a/lucene/contrib/queryparser/src/java/org/apache/lucene/queryParser/surround/query/SpanNearClauseFactory.java+++ b/lucene/contrib/queryparser/src/java/org/apache/lucene/queryParser/surround/query/SpanNearClauseFactory.java@@ -58,7 +58,10 @@ import java.util.Iterator;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.search.Query;import org.apache.lucene.search.spans.SpanNearQuery;import org.apache.lucene.search.spans.SpanOrQuery;@@ -84,8 +87,15 @@ public class SpanNearClauseFactory {public BasicQueryFactory getBasicQueryFactory() {return qf;}- public TermEnum getTermEnum(String termText) throws IOException {- return getIndexReader().terms(new Term(getFieldName(), termText));+ public TermsEnum getTermsEnum(String termText) throws IOException {+ Terms terms = MultiFields.getTerms(getIndexReader(), getFieldName());+ if (terms != null) {+ TermsEnum termsEnum = terms.iterator();+ termsEnum.seek(new BytesRef(termText));+ return termsEnum;+ } else {+ return null;+ }}public int size() {return weightBySpanQuery.size();}diff --git a/lucene/src/java/org/apache/lucene/analysis/Token.java b/lucene/src/java/org/apache/lucene/analysis/Token.javaindex f1a77731111..6be3a764218 100644--- a/lucene/src/java/org/apache/lucene/analysis/Token.java+++ b/lucene/src/java/org/apache/lucene/analysis/Token.java@@ -24,7 +24,7 @@ import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;import org.apache.lucene.analysis.tokenattributes.TypeAttribute;import org.apache.lucene.index.Payload;-import org.apache.lucene.index.TermPositions; // for javadoc+import org.apache.lucene.index.DocsAndPositionsEnum; // for javadocimport org.apache.lucene.util.Attribute;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.AttributeImpl;@@ -45,8 +45,8 @@ import org.apache.lucene.util.AttributeImpl;with type "eos". The default token type is "word".<p>A Token can optionally have metadata (a.k.a. Payload) in the form of a variable- length byte array. Use {@link TermPositions#getPayloadLength()} and- {@link TermPositions#getPayload(byte[], int)} to retrieve the payloads from the index.+ length byte array. Use {@link DocsAndPositionsEnum#getPayloadLength()} and+ {@link DocsAndPositionsEnum#getPayload(byte[], int)} to retrieve the payloads from the index.<br><br>diff --git a/lucene/src/java/org/apache/lucene/index/AbstractAllTermDocs.java b/lucene/src/java/org/apache/lucene/index/AbstractAllTermDocs.javadeleted file mode 100644index 0a521c9cbfe..00000000000--- a/lucene/src/java/org/apache/lucene/index/AbstractAllTermDocs.java+++ /dev/null@@ -1,92 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.lucene.index;--import java.io.IOException;--/** Base class for enumerating all but deleted docs.- *- * <p>NOTE: this class is meant only to be used internally- * by Lucene; it's only public so it can be shared across- * packages. This means the API is freely subject to- * change, and, the class could be removed entirely, in any- * Lucene release. Use directly at your own risk! */-@Deprecated-public abstract class AbstractAllTermDocs implements TermDocs {-- protected int maxDoc;- protected int doc = -1;-- protected AbstractAllTermDocs(int maxDoc) {- this.maxDoc = maxDoc;- }-- public void seek(Term term) throws IOException {- if (term==null) {- doc = -1;- } else {- throw new UnsupportedOperationException();- }- }-- public void seek(TermEnum termEnum) throws IOException {- throw new UnsupportedOperationException();- }-- public int doc() {- return doc;- }-- public int freq() {- return 1;- }-- public boolean next() throws IOException {- return skipTo(doc+1);- }-- public int read(int[] docs, int[] freqs) throws IOException {- final int length = docs.length;- int i = 0;- while (i < length && doc < maxDoc) {- if (!isDeleted(doc)) {- docs[i] = doc;- freqs[i] = 1;- ++i;- }- doc++;- }- return i;- }-- public boolean skipTo(int target) throws IOException {- doc = target;- while (doc < maxDoc) {- if (!isDeleted(doc)) {- return true;- }- doc++;- }- return false;- }-- public void close() throws IOException {- }-- public abstract boolean isDeleted(int doc);-}\ No newline at end of filediff --git a/lucene/src/java/org/apache/lucene/index/AllDocsEnum.java b/lucene/src/java/org/apache/lucene/index/AllDocsEnum.javadeleted file mode 100644index 733dfbd4cae..00000000000--- a/lucene/src/java/org/apache/lucene/index/AllDocsEnum.java+++ /dev/null@@ -1,78 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.lucene.index;--import org.apache.lucene.util.Bits;-import java.io.IOException;--class AllDocsEnum extends DocsEnum {- protected final Bits skipDocs;- protected final int maxDoc;- protected final IndexReader reader;- protected int doc = -1;-- protected AllDocsEnum(IndexReader reader, Bits skipDocs) {- this.skipDocs = skipDocs;- this.maxDoc = reader.maxDoc();- this.reader = reader;- }-- @Override- public int freq() {- return 1;- }-- @Override- public int docID() {- return doc;- }-- @Override- public int nextDoc() throws IOException {- return advance(doc+1);- }-- @Override- public int read() throws IOException {- final int[] docs = bulkResult.docs.ints;- final int[] freqs = bulkResult.freqs.ints;- int i = 0;- while (i < docs.length && doc < maxDoc) {- if (skipDocs == null || !skipDocs.get(doc)) {- docs[i] = doc;- freqs[i] = 1;- ++i;- }- doc++;- }- return i;- }-- @Override- public int advance(int target) throws IOException {- doc = target;- while (doc < maxDoc) {- if (skipDocs == null || !skipDocs.get(doc)) {- return doc;- }- doc++;- }- doc = NO_MORE_DOCS;- return doc;- }-}diff --git a/lucene/src/java/org/apache/lucene/index/AllTermDocs.java b/lucene/src/java/org/apache/lucene/index/AllTermDocs.javadeleted file mode 100644index 95e4f7ea9bf..00000000000--- a/lucene/src/java/org/apache/lucene/index/AllTermDocs.java+++ /dev/null@@ -1,39 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.lucene.index;--import org.apache.lucene.util.BitVector;--/** @deprecated Switch to AllDocsEnum */-@Deprecated-class AllTermDocs extends AbstractAllTermDocs {-- protected BitVector deletedDocs;-- protected AllTermDocs(SegmentReader parent) {- super(parent.maxDoc());- synchronized (parent) {- this.deletedDocs = parent.deletedDocs;- }- }-- @Override- public boolean isDeleted(int doc) {- return deletedDocs != null && deletedDocs.get(doc);- }-}diff --git a/lucene/src/java/org/apache/lucene/index/DirectoryReader.java b/lucene/src/java/org/apache/lucene/index/DirectoryReader.javaindex 9062d30ca50..9fcbc002ea5 100644--- a/lucene/src/java/org/apache/lucene/index/DirectoryReader.java+++ b/lucene/src/java/org/apache/lucene/index/DirectoryReader.java@@ -685,28 +685,6 @@ class DirectoryReader extends IndexReader implements Cloneable {subReaders[i].setNorm(n-starts[i], field, value); // dispatch}- @Override- public TermEnum terms() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].terms();- } else {- return new MultiTermEnum(this, subReaders, starts, null);- }- }-- @Override- public TermEnum terms(Term term) throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].terms(term);- } else {- return new MultiTermEnum(this, subReaders, starts, term);- }- }-@Overridepublic int docFreq(Term t) throws IOException {ensureOpen();@@ -726,44 +704,11 @@ class DirectoryReader extends IndexReader implements Cloneable {return total;}- @Override- public TermDocs termDocs() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termDocs();- } else {- return new MultiTermDocs(this, subReaders, starts);- }- }-- @Override- public TermDocs termDocs(Term term) throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termDocs(term);- } else {- return super.termDocs(term);- }- }-@Overridepublic Fields fields() throws IOException {throw new UnsupportedOperationException("please use MultiFields.getFields if you really need a top level Fields (NOTE that it's usually better to work per segment instead)");}- @Override- public TermPositions termPositions() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termPositions();- } else {- return new MultiTermPositions(this, subReaders, starts);- }- }-/*** Tries to acquire the WriteLock on this directory. this method is only valid if this IndexReader is directory* owner.@@ -1122,280 +1067,4 @@ class DirectoryReader extends IndexReader implements Cloneable {throw new UnsupportedOperationException("This IndexCommit does not support deletions");}}-- // @deprecated This is pre-flex API- // Exposes pre-flex API by doing on-the-fly merging- // pre-flex API to each segment- static class MultiTermEnum extends TermEnum {- IndexReader topReader; // used for matching TermEnum to TermDocs- private LegacySegmentMergeQueue queue;-- private Term term;- private int docFreq;- final LegacySegmentMergeInfo[] matchingSegments; // null terminated array of matching segments-- public MultiTermEnum(IndexReader topReader, IndexReader[] readers, int[] starts, Term t)- throws IOException {- this.topReader = topReader;- queue = new LegacySegmentMergeQueue(readers.length);- matchingSegments = new LegacySegmentMergeInfo[readers.length+1];- for (int i = 0; i < readers.length; i++) {- IndexReader reader = readers[i];- TermEnum termEnum;-- if (t != null) {- termEnum = reader.terms(t);- } else {- termEnum = reader.terms();- }-- LegacySegmentMergeInfo smi = new LegacySegmentMergeInfo(starts[i], termEnum, reader);- smi.ord = i;- if (t == null ? smi.next() : termEnum.term() != null)- queue.add(smi); // initialize queue- else- smi.close();- }-- if (t != null && queue.size() > 0) {- next();- }- }-- @Override- public boolean next() throws IOException {- for (int i=0; i<matchingSegments.length; i++) {- LegacySegmentMergeInfo smi = matchingSegments[i];- if (smi==null) break;- if (smi.next())- queue.add(smi);- else- smi.close(); // done with segment- }-- int numMatchingSegments = 0;- matchingSegments[0] = null;-- LegacySegmentMergeInfo top = queue.top();-- if (top == null) {- term = null;- return false;- }-- term = top.term;- docFreq = 0;-- while (top != null && term.compareTo(top.term) == 0) {- matchingSegments[numMatchingSegments++] = top;- queue.pop();- docFreq += top.termEnum.docFreq(); // increment freq- top = queue.top();- }-- matchingSegments[numMatchingSegments] = null;- return true;- }-- @Override- public Term term() {- return term;- }-- @Override- public int docFreq() {- return docFreq;- }-- @Override- public void close() throws IOException {- queue.close();- }- }-- // @deprecated This is pre-flex API- // Exposes pre-flex API by doing on-the-fly merging- // pre-flex API to each segment- static class MultiTermDocs implements TermDocs {- IndexReader topReader; // used for matching TermEnum to TermDocs- protected IndexReader[] readers;- protected int[] starts;- protected Term term;-- protected int base = 0;- protected int pointer = 0;-- private TermDocs[] readerTermDocs;- protected TermDocs current; // == readerTermDocs[pointer]-- private MultiTermEnum tenum; // the term enum used for seeking... can be null- int matchingSegmentPos; // position into the matching segments from tenum- LegacySegmentMergeInfo smi; // current segment mere info... can be null-- public MultiTermDocs(IndexReader topReader, IndexReader[] r, int[] s) {- this.topReader = topReader;- readers = r;- starts = s;-- readerTermDocs = new TermDocs[r.length];- }-- public int doc() {- return base + current.doc();- }- public int freq() {- return current.freq();- }-- public void seek(Term term) {- this.term = term;- this.base = 0;- this.pointer = 0;- this.current = null;- this.tenum = null;- this.smi = null;- this.matchingSegmentPos = 0;- }-- public void seek(TermEnum termEnum) throws IOException {- seek(termEnum.term());- if (termEnum instanceof MultiTermEnum) {- tenum = (MultiTermEnum)termEnum;- if (topReader != tenum.topReader)- tenum = null;- }- }-- public boolean next() throws IOException {- for(;;) {- if (current!=null && current.next()) {- return true;- }- else if (pointer < readers.length) {- if (tenum != null) {- smi = tenum.matchingSegments[matchingSegmentPos++];- if (smi==null) {- pointer = readers.length;- return false;- }- pointer = smi.ord;- }- base = starts[pointer];- current = termDocs(pointer++);- } else {- return false;- }- }- }-- /** Optimized implementation. */- public int read(final int[] docs, final int[] freqs) throws IOException {- while (true) {- while (current == null) {- if (pointer < readers.length) { // try next segment- if (tenum != null) {- smi = tenum.matchingSegments[matchingSegmentPos++];- if (smi==null) {- pointer = readers.length;- return 0;- }- pointer = smi.ord;- }- base = starts[pointer];- current = termDocs(pointer++);- } else {- return 0;- }- }- int end = current.read(docs, freqs);- if (end == 0) { // none left in segment- current = null;- } else { // got some- final int b = base; // adjust doc numbers- for (int i = 0; i < end; i++)- docs[i] += b;- return end;- }- }- }-- /* A Possible future optimization could skip entire segments */- public boolean skipTo(int target) throws IOException {- for(;;) {- if (current != null && current.skipTo(target-base)) {- return true;- } else if (pointer < readers.length) {- if (tenum != null) {- LegacySegmentMergeInfo smi = tenum.matchingSegments[matchingSegmentPos++];- if (smi==null) {- pointer = readers.length;- return false;- }- pointer = smi.ord;- }- base = starts[pointer];- current = termDocs(pointer++);- } else- return false;- }- }-- private TermDocs termDocs(int i) throws IOException {- TermDocs result = readerTermDocs[i];- if (result == null)- result = readerTermDocs[i] = termDocs(readers[i]);- if (smi != null) {- assert(smi.ord == i);- assert(smi.termEnum.term().equals(term));- result.seek(smi.termEnum);- } else {- result.seek(term);- }- return result;- }-- protected TermDocs termDocs(IndexReader reader)- throws IOException {- return term==null ? reader.termDocs(null) : reader.termDocs();- }-- public void close() throws IOException {- for (int i = 0; i < readerTermDocs.length; i++) {- if (readerTermDocs[i] != null)- readerTermDocs[i].close();- }- }- }-- // @deprecated This is pre-flex API- // Exposes pre-flex API by doing on-the-fly merging- // pre-flex API to each segment- static class MultiTermPositions extends MultiTermDocs implements TermPositions {- public MultiTermPositions(IndexReader topReader, IndexReader[] r, int[] s) {- super(topReader,r,s);- }-- @Override- protected TermDocs termDocs(IndexReader reader) throws IOException {- return reader.termPositions();- }-- public int nextPosition() throws IOException {- return ((TermPositions)current).nextPosition();- }-- public int getPayloadLength() throws IOException {- return ((TermPositions)current).getPayloadLength();- }-- public byte[] getPayload(byte[] data, int offset) throws IOException {- return ((TermPositions)current).getPayload(data, offset);- }--- // TODO: Remove warning after API has been finalized- public boolean isPayloadAvailable() {- return ((TermPositions) current).isPayloadAvailable();- }- }}diff --git a/lucene/src/java/org/apache/lucene/index/DocsAndPositionsEnum.java b/lucene/src/java/org/apache/lucene/index/DocsAndPositionsEnum.javaindex 247737e4130..551216e577c 100644--- a/lucene/src/java/org/apache/lucene/index/DocsAndPositionsEnum.java+++ b/lucene/src/java/org/apache/lucene/index/DocsAndPositionsEnum.java@@ -30,7 +30,8 @@ public abstract class DocsAndPositionsEnum extends DocsEnum {public abstract int nextPosition() throws IOException;/** Returns the payload at this position, or null if no- * payload was indexed. */+ * payload was indexed. Only call this once per+ * position. */public abstract BytesRef getPayload() throws IOException;public abstract boolean hasPayload();diff --git a/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java b/lucene/src/java/org/apache/lucene/index/FilterIndexReader.javaindex 11ba2e72d03..0648ef655d8 100644--- a/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java@@ -361,20 +361,6 @@ public class FilterIndexReader extends IndexReader {in.setNorm(d, f, b);}- // final to force subclass to impl flex APIs, instead- @Override- public final TermEnum terms() throws IOException {- ensureOpen();- return in.terms();- }-- // final to force subclass to impl flex APIs, instead- @Override- public final TermEnum terms(Term t) throws IOException {- ensureOpen();- return in.terms(t);- }-@Overridepublic int docFreq(Term t) throws IOException {ensureOpen();@@ -387,27 +373,6 @@ public class FilterIndexReader extends IndexReader {return in.docFreq(field, t);}- // final to force subclass to impl flex APIs, instead- @Override- public final TermDocs termDocs() throws IOException {- ensureOpen();- return in.termDocs();- }-- // final to force subclass to impl flex APIs, instead- @Override- public final TermDocs termDocs(Term term) throws IOException {- ensureOpen();- return in.termDocs(term);- }-- // final to force subclass to impl flex APIs, instead- @Override- public final TermPositions termPositions() throws IOException {- ensureOpen();- return in.termPositions();- }-@Overrideprotected void doDelete(int n) throws CorruptIndexException, IOException { in.deleteDocument(n); }diff --git a/lucene/src/java/org/apache/lucene/index/IndexReader.java b/lucene/src/java/org/apache/lucene/index/IndexReader.javaindex 5a8e1ea30aa..05e09b6772d 100644--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java@@ -868,18 +868,6 @@ public abstract class IndexReader implements Cloneable,Closeable {setNorm(doc, field, Similarity.getDefault().encodeNormValue(value));}- /** Returns an enumeration of all the terms in the index. The- * enumeration is ordered by Term.compareTo(). Each term is greater- * than all that precede it in the enumeration. Note that after- * calling terms(), {@link TermEnum#next()} must be called- * on the resulting enumeration before calling other methods such as- * {@link TermEnum#term()}.- * @deprecated Use the new flex API ({@link #fields()}) instead.- * @throws IOException if there is a low-level IO error- */- @Deprecated- public abstract TermEnum terms() throws IOException;-/** Flex API: returns {@link Fields} for this reader.* This method may return null if the reader has no* postings.@@ -893,24 +881,10 @@ public abstract class IndexReader implements Cloneable,Closeable {* using {@link ReaderUtil#gatherSubReaders} and iterate* through them yourself. */public abstract Fields fields() throws IOException;-- /** Returns an enumeration of all terms starting at a given term. If- * the given term does not exist, the enumeration is positioned at the- * first term greater than the supplied term. The enumeration is- * ordered by Term.compareTo(). Each term is greater than all that- * precede it in the enumeration.- * @deprecated Use the new flex API ({@link #fields()}) instead.- * @throws IOException if there is a low-level IO error- */- @Deprecated- public abstract TermEnum terms(Term t) throws IOException;- /** Returns the number of documents containing the term <code>t</code>.- * @throws IOException if there is a low-level IO error- * @deprecated Use {@link #docFreq(String,BytesRef)} instead.- */- @Deprecated- public abstract int docFreq(Term t) throws IOException;+ public int docFreq(Term term) throws IOException {+ return docFreq(term.field(), new BytesRef(term.text()));+ }/** Returns the number of documents containing the term* <code>t</code>. This method returns 0 if the term or@@ -929,28 +903,6 @@ public abstract class IndexReader implements Cloneable,Closeable {return terms.docFreq(term);}- /** Returns an enumeration of all the documents which contain- * <code>term</code>. For each document, the document number, the frequency of- * the term in that document is also provided, for use in- * search scoring. If term is null, then all non-deleted- * docs are returned with freq=1.- * Thus, this method implements the mapping:- * <p><ul>- * Term => <docNum, freq><sup>*</sup>- * </ul>- * <p>The enumeration is ordered by document number. Each document number- * is greater than all that precede it in the enumeration.- * @deprecated Use the new flex API ({@link #termDocsEnum}) instead.- * @throws IOException if there is a low-level IO error- */- @Deprecated- public TermDocs termDocs(Term term) throws IOException {- ensureOpen();- TermDocs termDocs = termDocs();- termDocs.seek(term);- return termDocs;- }-/** This may return null if the field does not exist.*/public Terms terms(String field) throws IOException {final Fields fields = fields();@@ -997,50 +949,6 @@ public abstract class IndexReader implements Cloneable,Closeable {}}- /** Returns an unpositioned {@link TermDocs} enumerator.- * @deprecated Use the new flex API ({@link #fields()}) instead.- * @throws IOException if there is a low-level IO error- */- @Deprecated- public abstract TermDocs termDocs() throws IOException;-- /** Returns an enumeration of all the documents which contain- * <code>term</code>. For each document, in addition to the document number- * and frequency of the term in that document, a list of all of the ordinal- * positions of the term in the document is available. Thus, this method- * implements the mapping:- *- * <p><ul>- * Term => <docNum, freq,- * <pos<sub>1</sub>, pos<sub>2</sub>, ...- * pos<sub>freq-1</sub>>- * ><sup>*</sup>- * </ul>- * <p> This positional information facilitates phrase and proximity searching.- * <p>The enumeration is ordered by document number. Each document number is- * greater than all that precede it in the enumeration.- * @deprecated Please switch the flex API ({@link- * #termDocsEnum}) instead- * @throws IOException if there is a low-level IO error- */- @Deprecated- public TermPositions termPositions(Term term) throws IOException {- ensureOpen();- TermPositions termPositions = termPositions();- termPositions.seek(term);- return termPositions;- }-- /** Returns an unpositioned {@link TermPositions} enumerator.- * @deprecated Please switch the flex API ({@link- * #termDocsEnum}) instead- * @throws IOException if there is a low-level IO error- */- @Deprecated- public abstract TermPositions termPositions() throws IOException;---/** Deletes the document numbered <code>docNum</code>. Once a document is* deleted it will not appear in TermDocs or TermPositions enumerations.* Attempts to read its field with the {@link #document}@@ -1089,16 +997,16 @@ public abstract class IndexReader implements Cloneable,Closeable {*/public int deleteDocuments(Term term) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {ensureOpen();- TermDocs docs = termDocs(term);+ DocsEnum docs = MultiFields.getTermDocsEnum(this,+ MultiFields.getDeletedDocs(this),+ term.field(),+ new BytesRef(term.text()));if (docs == null) return 0;int n = 0;- try {- while (docs.next()) {- deleteDocument(docs.doc());- n++;- }- } finally {- docs.close();+ int doc;+ while ((doc = docs.nextDoc()) != docs.NO_MORE_DOCS) {+ deleteDocument(doc);+ n++;}return n;}diff --git a/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeInfo.java b/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeInfo.javadeleted file mode 100644index de97259b81e..00000000000--- a/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeInfo.java+++ /dev/null@@ -1,86 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--// @deprecated This is pre-flex API-final class LegacySegmentMergeInfo {- Term term;- int base;- int ord; // the position of the segment in a MultiReader- TermEnum termEnum;- IndexReader reader;- int delCount;- private TermPositions postings; // use getPositions()- private int[] docMap; // use getDocMap()-- LegacySegmentMergeInfo(int b, TermEnum te, IndexReader r)- throws IOException {- base = b;- reader = r;- termEnum = te;- term = te.term();- }-- // maps around deleted docs- int[] getDocMap() {- if (docMap == null) {- delCount = 0;- // build array which maps document numbers around deletions- if (reader.hasDeletions()) {- int maxDoc = reader.maxDoc();- docMap = new int[maxDoc];- int j = 0;- for (int i = 0; i < maxDoc; i++) {- if (reader.isDeleted(i)) {- delCount++;- docMap[i] = -1;- } else- docMap[i] = j++;- }- }- }- return docMap;- }-- TermPositions getPositions() throws IOException {- if (postings == null) {- postings = reader.termPositions();- }- return postings;- }-- final boolean next() throws IOException {- if (termEnum.next()) {- term = termEnum.term();- return true;- } else {- term = null;- return false;- }- }-- final void close() throws IOException {- termEnum.close();- if (postings != null) {- postings.close();- }-}-}-diff --git a/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeQueue.java b/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeQueue.javadeleted file mode 100644index 8cecb6c85df..00000000000--- a/lucene/src/java/org/apache/lucene/index/LegacySegmentMergeQueue.java+++ /dev/null@@ -1,42 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import org.apache.lucene.util.PriorityQueue;--final class LegacySegmentMergeQueue extends PriorityQueue<LegacySegmentMergeInfo> {- LegacySegmentMergeQueue(int size) {- initialize(size);- }-- @Override- protected final boolean lessThan(LegacySegmentMergeInfo a, LegacySegmentMergeInfo b) {- int comparison = a.term.compareTo(b.term);- if (comparison == 0)- return a.base < b.base;- else- return comparison < 0;- }-- final void close() throws IOException {- while (top() != null)- ((LegacySegmentMergeInfo)pop()).close();- }--}diff --git a/lucene/src/java/org/apache/lucene/index/MultiReader.java b/lucene/src/java/org/apache/lucene/index/MultiReader.javaindex 3c830b73d24..e6c8116919c 100644--- a/lucene/src/java/org/apache/lucene/index/MultiReader.java+++ b/lucene/src/java/org/apache/lucene/index/MultiReader.java@@ -25,9 +25,6 @@ import java.util.Map;import org.apache.lucene.document.Document;import org.apache.lucene.document.FieldSelector;-import org.apache.lucene.index.DirectoryReader.MultiTermDocs; // deprecated-import org.apache.lucene.index.DirectoryReader.MultiTermEnum; // deprecated-import org.apache.lucene.index.DirectoryReader.MultiTermPositions; // deprecatedimport org.apache.lucene.search.Similarity;import org.apache.lucene.search.FieldCache; // not great (circular); used only to purge FieldCache entry on closeimport org.apache.lucene.util.Bits;@@ -369,28 +366,6 @@ public class MultiReader extends IndexReader implements Cloneable {subReaders[i].setNorm(n-starts[i], field, value); // dispatch}- @Override- public TermEnum terms() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].terms();- } else {- return new MultiTermEnum(this, subReaders, starts, null);- }- }-- @Override- public TermEnum terms(Term term) throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].terms(term);- } else {- return new MultiTermEnum(this, subReaders, starts, term);- }- }-@Overridepublic int docFreq(Term t) throws IOException {ensureOpen();@@ -410,39 +385,6 @@ public class MultiReader extends IndexReader implements Cloneable {return total;}- @Override- public TermDocs termDocs() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termDocs();- } else {- return new MultiTermDocs(this, subReaders, starts);- }- }-- @Override- public TermDocs termDocs(Term term) throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termDocs(term);- } else {- return super.termDocs(term);- }- }-- @Override- public TermPositions termPositions() throws IOException {- ensureOpen();- if (subReaders.length == 1) {- // Optimize single segment case:- return subReaders[0].termPositions();- } else {- return new MultiTermPositions(this, subReaders, starts);- }- }-@Overrideprotected void doCommit(Map<String,String> commitUserData) throws IOException {for (int i = 0; i < subReaders.length; i++)diff --git a/lucene/src/java/org/apache/lucene/index/MultipleTermPositions.java b/lucene/src/java/org/apache/lucene/index/MultipleTermPositions.javadeleted file mode 100644index 0a819c34b21..00000000000--- a/lucene/src/java/org/apache/lucene/index/MultipleTermPositions.java+++ /dev/null@@ -1,218 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.Arrays;-import java.util.LinkedList;-import java.util.List;--import org.apache.lucene.util.PriorityQueue;-import org.apache.lucene.util.ArrayUtil;--/**- * Allows you to iterate over the {@link TermPositions} for multiple {@link Term}s as- * a single {@link TermPositions}.- * @deprecated This class is being replaced by the package- * private MultiDocsEnum on org.apache.lucene.search.- */-@Deprecated-public class MultipleTermPositions implements TermPositions {-- private static final class TermPositionsQueue extends PriorityQueue<TermPositions> {- TermPositionsQueue(List<TermPositions> termPositions) throws IOException {- initialize(termPositions.size());-- for (TermPositions tp : termPositions) {- if (tp.next())- add(tp);- }- }-- final TermPositions peek() {- return top();- }-- @Override- public final boolean lessThan(TermPositions a, TermPositions b) {- return a.doc() < b.doc();- }- }-- private static final class IntQueue {- private int _arraySize = 16;- private int _index = 0;- private int _lastIndex = 0;- private int[] _array = new int[_arraySize];-- final void add(int i) {- if (_lastIndex == _arraySize)- growArray();-- _array[_lastIndex++] = i;- }-- final int next() {- return _array[_index++];- }-- final void sort() {- Arrays.sort(_array, _index, _lastIndex);- }-- final void clear() {- _index = 0;- _lastIndex = 0;- }-- final int size() {- return (_lastIndex - _index);- }-- private void growArray() {- _array = ArrayUtil.grow(_array, _arraySize+1);- _arraySize = _array.length;- }- }-- private int _doc;- private int _freq;- private TermPositionsQueue _termPositionsQueue;- private IntQueue _posList;-- /**- * Creates a new <code>MultipleTermPositions</code> instance.- *- * @exception IOException- */- public MultipleTermPositions(IndexReader indexReader, Term[] terms) throws IOException {- List<TermPositions> termPositions = new LinkedList<TermPositions>();-- for (int i = 0; i < terms.length; i++)- termPositions.add(indexReader.termPositions(terms[i]));-- _termPositionsQueue = new TermPositionsQueue(termPositions);- _posList = new IntQueue();- }-- public final boolean next() throws IOException {- if (_termPositionsQueue.size() == 0)- return false;-- _posList.clear();- _doc = _termPositionsQueue.peek().doc();-- TermPositions tp;- do {- tp = _termPositionsQueue.peek();-- for (int i = 0; i < tp.freq(); i++)- _posList.add(tp.nextPosition());-- if (tp.next())- _termPositionsQueue.updateTop();- else {- _termPositionsQueue.pop();- tp.close();- }- } while (_termPositionsQueue.size() > 0 && _termPositionsQueue.peek().doc() == _doc);-- _posList.sort();- _freq = _posList.size();-- return true;- }-- public final int nextPosition() {- return _posList.next();- }-- public final boolean skipTo(int target) throws IOException {- while (_termPositionsQueue.peek() != null && target > _termPositionsQueue.peek().doc()) {- TermPositions tp = _termPositionsQueue.pop();- if (tp.skipTo(target))- _termPositionsQueue.add(tp);- else- tp.close();- }- return next();- }-- public final int doc() {- return _doc;- }-- public final int freq() {- return _freq;- }-- public final void close() throws IOException {- while (_termPositionsQueue.size() > 0)- _termPositionsQueue.pop().close();- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public void seek(Term arg0) throws IOException {- throw new UnsupportedOperationException();- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public void seek(TermEnum termEnum) throws IOException {- throw new UnsupportedOperationException();- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public int read(int[] arg0, int[] arg1) throws IOException {- throw new UnsupportedOperationException();- }--- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public int getPayloadLength() {- throw new UnsupportedOperationException();- }-- /**- * Not implemented.- * @throws UnsupportedOperationException- */- public byte[] getPayload(byte[] data, int offset) throws IOException {- throw new UnsupportedOperationException();- }-- /**- *- * @return false- */- // TODO: Remove warning after API has been finalized- public boolean isPayloadAvailable() {- return false;- }-}diff --git a/lucene/src/java/org/apache/lucene/index/ParallelReader.java b/lucene/src/java/org/apache/lucene/index/ParallelReader.javaindex c30de55bc71..e13775b97da 100644--- a/lucene/src/java/org/apache/lucene/index/ParallelReader.java+++ b/lucene/src/java/org/apache/lucene/index/ParallelReader.java@@ -451,18 +451,6 @@ public class ParallelReader extends IndexReader {reader.doSetNorm(n, field, value);}- @Override- public TermEnum terms() throws IOException {- ensureOpen();- return new ParallelTermEnum();- }-- @Override- public TermEnum terms(Term term) throws IOException {- ensureOpen();- return new ParallelTermEnum(term);- }-@Overridepublic int docFreq(Term term) throws IOException {ensureOpen();@@ -477,30 +465,6 @@ public class ParallelReader extends IndexReader {return reader == null? 0 : reader.docFreq(field, term);}- @Override- public TermDocs termDocs(Term term) throws IOException {- ensureOpen();- return new ParallelTermDocs(term);- }-- @Override- public TermDocs termDocs() throws IOException {- ensureOpen();- return new ParallelTermDocs();- }-- @Override- public TermPositions termPositions(Term term) throws IOException {- ensureOpen();- return new ParallelTermPositions(term);- }-- @Override- public TermPositions termPositions() throws IOException {- ensureOpen();- return new ParallelTermPositions();- }-/*** Checks recursively if all subreaders are up to date.*/@@ -574,168 +538,6 @@ public class ParallelReader extends IndexReader {}return fieldSet;}-- @Deprecated- private class ParallelTermEnum extends TermEnum {- private String field;- private Iterator<String> fieldIterator;- private TermEnum termEnum;-- public ParallelTermEnum() throws IOException {- try {- field = fieldToReader.firstKey();- } catch(NoSuchElementException e) {- // No fields, so keep field == null, termEnum == null- return;- }- if (field != null)- termEnum = fieldToReader.get(field).terms();- }-- public ParallelTermEnum(Term term) throws IOException {- field = term.field();- IndexReader reader = fieldToReader.get(field);- if (reader!=null)- termEnum = reader.terms(term);- }-- @Override- public boolean next() throws IOException {- if (termEnum==null)- return false;-- // another term in this field?- if (termEnum.next() && termEnum.term().field()==field)- return true; // yes, keep going-- termEnum.close(); // close old termEnum-- // find the next field with terms, if any- if (fieldIterator==null) {- fieldIterator = fieldToReader.tailMap(field).keySet().iterator();- fieldIterator.next(); // Skip field to get next one- }- while (fieldIterator.hasNext()) {- field = fieldIterator.next();- termEnum = fieldToReader.get(field).terms(new Term(field));- Term term = termEnum.term();- if (term!=null && term.field()==field)- return true;- else- termEnum.close();- }-- return false; // no more fields- }-- @Override- public Term term() {- if (termEnum==null)- return null;-- return termEnum.term();- }-- @Override- public int docFreq() {- if (termEnum==null)- return 0;-- return termEnum.docFreq();- }-- @Override- public void close() throws IOException {- if (termEnum!=null)- termEnum.close();- }-- }-- // wrap a TermDocs in order to support seek(Term)- private class ParallelTermDocs implements TermDocs {- protected TermDocs termDocs;-- public ParallelTermDocs() {}- public ParallelTermDocs(Term term) throws IOException {- if (term == null)- termDocs = readers.isEmpty() ? null : readers.get(0).termDocs(null);- else- seek(term);- }-- public int doc() { return termDocs.doc(); }- public int freq() { return termDocs.freq(); }-- public void seek(Term term) throws IOException {- IndexReader reader = fieldToReader.get(term.field());- termDocs = reader!=null ? reader.termDocs(term) : null;- }-- public void seek(TermEnum termEnum) throws IOException {- seek(termEnum.term());- }-- public boolean next() throws IOException {- if (termDocs==null)- return false;-- return termDocs.next();- }-- public int read(final int[] docs, final int[] freqs) throws IOException {- if (termDocs==null)- return 0;-- return termDocs.read(docs, freqs);- }-- public boolean skipTo(int target) throws IOException {- if (termDocs==null)- return false;-- return termDocs.skipTo(target);- }-- public void close() throws IOException {- if (termDocs!=null)- termDocs.close();- }-- }-- private class ParallelTermPositions- extends ParallelTermDocs implements TermPositions {-- public ParallelTermPositions() {}- public ParallelTermPositions(Term term) throws IOException { seek(term); }-- @Override- public void seek(Term term) throws IOException {- IndexReader reader = fieldToReader.get(term.field());- termDocs = reader!=null ? reader.termPositions(term) : null;- }-- public int nextPosition() throws IOException {- // It is an error to call this if there is no next position, e.g. if termDocs==null- return ((TermPositions)termDocs).nextPosition();- }-- public int getPayloadLength() throws IOException {- return ((TermPositions)termDocs).getPayloadLength();- }-- public byte[] getPayload(byte[] data, int offset) throws IOException {- return ((TermPositions)termDocs).getPayload(data, offset);- }--- // TODO: Remove warning after API has been finalized- public boolean isPayloadAvailable() {- return ((TermPositions) termDocs).isPayloadAvailable();- }- }-}diff --git a/lucene/src/java/org/apache/lucene/index/SegmentReader.java b/lucene/src/java/org/apache/lucene/index/SegmentReader.javaindex fbc4254fdd6..b216cd976e9 100644--- a/lucene/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentReader.java@@ -39,11 +39,7 @@ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.Bits;import org.apache.lucene.util.CloseableThreadLocal;-import org.apache.lucene.util.UnicodeUtil;import org.apache.lucene.index.codecs.CodecProvider;-import org.apache.lucene.index.codecs.preflex.PreFlexFields;-import org.apache.lucene.index.codecs.preflex.SegmentTermDocs;-import org.apache.lucene.index.codecs.preflex.SegmentTermPositions;import org.apache.lucene.index.codecs.FieldsProducer;import org.apache.lucene.search.FieldCache; // not great (circular); used only to purge FieldCache entry on closeimport org.apache.lucene.util.BytesRef;@@ -93,7 +89,6 @@ public class SegmentReader extends IndexReader implements Cloneable {final FieldInfos fieldInfos;final FieldsProducer fields;- final boolean isPreFlex;final CodecProvider codecs;final Directory dir;@@ -140,7 +135,6 @@ public class SegmentReader extends IndexReader implements Cloneable {fields = si.getCodec().fieldsProducer(new SegmentReadState(cfsDir, si, fieldInfos, readBufferSize, termsIndexDivisor));assert fields != null;- isPreFlex = fields instanceof PreFlexFields;success = true;} finally {if (!success) {@@ -824,37 +818,6 @@ public class SegmentReader extends IndexReader implements Cloneable {return new ArrayList<String>(si.files());}- @Override- public TermEnum terms() throws IOException {- ensureOpen();- if (core.isPreFlex) {- // For old API on an old segment, instead of- // converting old API -> new API -> old API, just give- // direct access to old:- return ((PreFlexFields) core.fields).tis.terms();- } else {- // Emulate pre-flex API on top of flex index- return new LegacyTermEnum(null);- }- }-- /** @deprecated Please switch to the flex API ({@link- * #fields}) instead. */- @Deprecated- @Override- public TermEnum terms(Term t) throws IOException {- ensureOpen();- if (core.isPreFlex) {- // For old API on an old segment, instead of- // converting old API -> new API -> old API, just give- // direct access to old:- return ((PreFlexFields) core.fields).tis.terms(t);- } else {- // Emulate pre-flex API on top of flex index- return new LegacyTermEnum(t);- }- }-FieldInfos fieldInfos() {return core.fieldInfos;}@@ -870,74 +833,11 @@ public class SegmentReader extends IndexReader implements Cloneable {return (deletedDocs != null && deletedDocs.get(n));}- /** @deprecated Switch to the flex API ({@link- * IndexReader#termDocsEnum}) instead. */- @Deprecated- @Override- public TermDocs termDocs(Term term) throws IOException {- if (term == null) {- return new AllTermDocs(this);- } else {- return super.termDocs(term);- }- }-@Overridepublic Fields fields() throws IOException {return core.fields;}- /** @deprecated Switch to the flex API {@link- * IndexReader#termDocsEnum} instead. */- @Deprecated- @Override- public TermDocs termDocs() throws IOException {- ensureOpen();- if (core.isPreFlex) {- // For old API on an old segment, instead of- // converting old API -> new API -> old API, just give- // direct access to old:- final PreFlexFields pre = (PreFlexFields) core.fields;- SegmentTermDocs std = new SegmentTermDocs(pre.freqStream, pre.tis, core.fieldInfos);- std.setSkipDocs(deletedDocs);- return std;- } else {- // Emulate old API- return new LegacyTermDocs();- }- }-- /** @deprecated Switch to the flex API {@link- * IndexReader#termDocsEnum} instead */- @Deprecated- @Override- public TermPositions termPositions() throws IOException {- ensureOpen();- if (core.isPreFlex) {- // For old API on an old segment, instead of- // converting old API -> new API -> old API, just give- // direct access to old:- final PreFlexFields pre = (PreFlexFields) core.fields;- SegmentTermPositions stp = new SegmentTermPositions(pre.freqStream, pre.proxStream, pre.tis, core.fieldInfos);- stp.setSkipDocs(deletedDocs);- return stp;- } else {- // Emulate old API- return new LegacyTermPositions();- }- }-- @Override- public int docFreq(Term t) throws IOException {- ensureOpen();- Terms terms = core.fields.terms(t.field);- if (terms != null) {- return terms.docFreq(new BytesRef(t.text));- } else {- return 0;- }- }-@Overridepublic int docFreq(String field, BytesRef term) throws IOException {ensureOpen();@@ -1328,393 +1228,4 @@ public class SegmentReader extends IndexReader implements Cloneable {public int getTermInfosIndexDivisor() {return core.termsIndexDivisor;}-- // Back compat: pre-flex TermEnum API over flex API- @Deprecated- final private class LegacyTermEnum extends TermEnum {- FieldsEnum fields;- TermsEnum terms;- boolean done;- String currentField;- BytesRef currentTerm;-- public LegacyTermEnum(Term t) throws IOException {- fields = core.fields.iterator();- currentField = fields.next();- if (currentField == null) {- // no fields- done = true;- } else if (t != null) {- // Pre-seek to this term-- while(currentField.compareTo(t.field) < 0) {- currentField = fields.next();- if (currentField == null) {- // Hit end of fields- done = true;- break;- }- }-- if (!done) {- // We found some field -- get its terms:- terms = fields.terms();-- if (currentField == t.field) {- // We found exactly the requested field; now- // seek the term text:- String text = t.text();-- // this is only for backwards compatibility.- // previously you could supply a term with unpaired surrogates,- // and it would return the next Term.- // if someone does this, tack on the lowest possible trail surrogate.- // this emulates the old behavior, and forms "valid UTF-8" unicode.- BytesRef tr = new BytesRef(UnicodeUtil.nextValidUTF16String(text));- TermsEnum.SeekStatus status = terms.seek(tr);-- if (status == TermsEnum.SeekStatus.END) {- // Rollover to the next field- terms = null;- next();- } else if (status == TermsEnum.SeekStatus.FOUND) {- // Found exactly the term- currentTerm = tr;- } else {- // Found another term, in this same field- currentTerm = terms.term();- }- } else {- // We didn't find exact field (we found the- // following field); advance to first term in- // this field- next();- }- }- } else {- terms = fields.terms();- }- }-- @Override- public boolean next() throws IOException {-- if (done) {- return false;- }-- while(true) {- if (terms == null) {- // Advance to the next field- currentField = fields.next();- if (currentField == null) {- done = true;- return false;- }- terms = fields.terms();- }- currentTerm = terms.next();- if (currentTerm != null) {- // This field still has terms- return true;- } else {- // Done producing terms from this field; advance- // to next field- terms = null;- }- }- }-- @Override- public Term term() {- if (!done && terms != null && currentTerm != null) {- return new Term(currentField, currentTerm.utf8ToString());- }- return null;- }-- @Override- public int docFreq() {- return terms == null ? 0 : terms.docFreq();- }-- @Override- public void close() {}- }-- // Back compat: emulates legacy TermDocs API on top of- // flex API- private class LegacyTermDocs implements TermDocs {-- String currentField;- final Fields fields;- TermsEnum terms;- DocsEnum docsEnum;- boolean any;-- LegacyTermDocs() throws IOException {- fields = core.fields;- }-- public void close() {}-- public void seek(TermEnum termEnum) throws IOException {- seek(termEnum.term());- }-- public boolean skipTo(int target) throws IOException {- if (!any) {- return false;- } else {- return docsEnum.advance(target) != docsEnum.NO_MORE_DOCS;- }- }-- public void seek(Term term) throws IOException {-- any = false;-- if (terms != null && !term.field.equals(currentField)) {- // new field- terms = null;- }-- if (terms == null) {- currentField = term.field;- Terms terms1 = fields.terms(currentField);- if (terms1 == null) {- // no such field- return;- } else {- terms = terms1.iterator();- }- }-- if (terms.seek(new BytesRef(term.text)) == TermsEnum.SeekStatus.FOUND) {- // Term exists- any = true;- pendingBulkResult = null;- docsEnum = terms.docs(deletedDocs, docsEnum);- }- }-- public int doc() {- if (!any) {- return 0;- } else {- return docsEnum.docID();- }- }-- private DocsEnum.BulkReadResult pendingBulkResult;- private int bulkCount;- private int pendingBulk;-- public int read(int[] docs, int[] freqs) throws IOException {- if (any && pendingBulkResult == null) {- pendingBulkResult = docsEnum.getBulkResult();- }- if (!any) {- return 0;- } else if (pendingBulk > 0) {- final int left = bulkCount - pendingBulk;- if (docs.length >= left) {- // read all pending- System.arraycopy(pendingBulkResult.docs.ints, pendingBulk, docs, 0, left);- System.arraycopy(pendingBulkResult.freqs.ints, pendingBulk, freqs, 0, left);- pendingBulk = 0;- return left;- } else {- // read only part of pending- System.arraycopy(pendingBulkResult.docs.ints, pendingBulk, docs, 0, docs.length);- System.arraycopy(pendingBulkResult.freqs.ints, pendingBulk, freqs, 0, docs.length);- pendingBulk += docs.length;- return docs.length;- }- } else {- // nothing pending- bulkCount = docsEnum.read();- if (docs.length >= bulkCount) {- System.arraycopy(pendingBulkResult.docs.ints, 0, docs, 0, bulkCount);- System.arraycopy(pendingBulkResult.freqs.ints, 0, freqs, 0, bulkCount);- return bulkCount;- } else {- System.arraycopy(pendingBulkResult.docs.ints, 0, docs, 0, docs.length);- System.arraycopy(pendingBulkResult.freqs.ints, 0, freqs, 0, docs.length);- pendingBulk = docs.length;- return docs.length;- }- }- }-- public int freq() {- if (!any) {- return 0;- } else {- return docsEnum.freq();- }- }-- public boolean next() throws IOException {- if (!any) {- return false;- } else {- return docsEnum.nextDoc() != DocsEnum.NO_MORE_DOCS;- }- }- }-- // Back compat: implements legacy TermPositions API on top- // of flex API- final private class LegacyTermPositions implements TermPositions {-- String currentField;- final Fields fields;- TermsEnum terms;- DocsAndPositionsEnum postingsEnum;- DocsEnum docsEnum;- boolean any;-- LegacyTermPositions() throws IOException {- fields = core.fields;- }-- public void close() {}-- public void seek(TermEnum termEnum) throws IOException {- seek(termEnum.term());- }-- public boolean skipTo(int target) throws IOException {- if (!any) {- return false;- } else {- return docsEnum.advance(target) != docsEnum.NO_MORE_DOCS;- }- }-- public void seek(Term term) throws IOException {-- any = false;-- if (terms != null && !term.field.equals(currentField)) {- // new field- terms = null;- }-- if (terms == null) {- currentField = term.field;- Terms terms1 = fields.terms(currentField);- if (terms1 == null) {- // no such field- return;- } else {- terms = terms1.iterator();- }- }-- if (terms.seek(new BytesRef(term.text)) == TermsEnum.SeekStatus.FOUND) {- // Term exists- any = true;- postingsEnum = terms.docsAndPositions(deletedDocs, postingsEnum);- if (postingsEnum == null) {- docsEnum = terms.docs(deletedDocs, postingsEnum);- } else {- docsEnum = postingsEnum;- }- }- }-- public int doc() {- if (!any) {- return 0;- } else {- return docsEnum.docID();- }- }-- public int freq() {- if (!any) {- return 0;- } else {- return docsEnum.freq();- }- }-- public boolean next() throws IOException {- if (!any) {- return false;- } else {- return docsEnum.nextDoc() != DocsEnum.NO_MORE_DOCS;- }- }-- public int read(int[] docs, int[] freqs) throws IOException {- throw new UnsupportedOperationException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead.");- }-- public int nextPosition() throws IOException {- pendingPayload = null;- if (!any || postingsEnum == null) {- return 0;- } else {- return postingsEnum.nextPosition();- }- }-- private BytesRef pendingPayload;-- public int getPayloadLength() throws IOException {- if (!any || postingsEnum == null) {- return 0;- } else {- if (pendingPayload == null) {- if (!postingsEnum.hasPayload()) {- return 0;- }- pendingPayload = postingsEnum.getPayload();- }- if (pendingPayload == null) {- return 0;- }- return pendingPayload.length;- }- }-- public byte[] getPayload(byte[] bytes, int offset) throws IOException {- if (!any || postingsEnum == null) {- return null;- }- if (pendingPayload == null) {- if (!postingsEnum.hasPayload()) {- return null;- }- pendingPayload = postingsEnum.getPayload();- }- if (pendingPayload == null) {- return null;- }-- // old API would always used passed in bytes if it- // "fits", else allocate new:- if (bytes != null && pendingPayload.length <= bytes.length - offset) {- System.arraycopy(pendingPayload.bytes, pendingPayload.offset, bytes, offset, pendingPayload.length);- return bytes;- } else if (pendingPayload.offset == 0 && pendingPayload.length == pendingPayload.bytes.length) {- return pendingPayload.bytes;- } else {- final byte[] retBytes = new byte[pendingPayload.length];- System.arraycopy(pendingPayload.bytes, pendingPayload.offset, retBytes, 0, pendingPayload.length);- return retBytes;- }- }-- public boolean isPayloadAvailable() {- if (!any || postingsEnum == null) {- return false;- } else {- return postingsEnum.hasPayload();- }- }- }}diff --git a/lucene/src/java/org/apache/lucene/index/TermDocs.java b/lucene/src/java/org/apache/lucene/index/TermDocs.javadeleted file mode 100644index e645d39bdcb..00000000000--- a/lucene/src/java/org/apache/lucene/index/TermDocs.java+++ /dev/null@@ -1,85 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.io.Closeable;--/** TermDocs provides an interface for enumerating <document, frequency>- pairs for a term. <p> The document portion names each document containing- the term. Documents are indicated by number. The frequency portion gives- the number of times the term occurred in each document. <p> The pairs are- ordered by document number.-- @see IndexReader#termDocs()- @deprecated Use {@link DocsEnum} instead-*/--@Deprecated-public interface TermDocs extends Closeable {- /** Sets this to the data for a term.- * The enumeration is reset to the start of the data for this term.- */- void seek(Term term) throws IOException;-- /** Sets this to the data for the current term in a {@link TermEnum}.- * This may be optimized in some implementations.- */- void seek(TermEnum termEnum) throws IOException;-- /** Returns the current document number. <p> This is invalid until {@link- #next()} is called for the first time.*/- int doc();-- /** Returns the frequency of the term within the current document. <p> This- is invalid until {@link #next()} is called for the first time.*/- int freq();-- /** Moves to the next pair in the enumeration. <p> Returns true iff there is- such a next pair in the enumeration. */- boolean next() throws IOException;-- /** Attempts to read multiple entries from the enumeration, up to length of- * <i>docs</i>. Document numbers are stored in <i>docs</i>, and term- * frequencies are stored in <i>freqs</i>. The <i>freqs</i> array must be as- * long as the <i>docs</i> array.- *- * <p>Returns the number of entries read. Zero is only returned when the- * stream has been exhausted. */- int read(int[] docs, int[] freqs) throws IOException;-- /** Skips entries to the first beyond the current whose document number is- * greater than or equal to <i>target</i>. <p>Returns true iff there is such- * an entry. <p>Behaves as if written: <pre>- * boolean skipTo(int target) {- * do {- * if (!next())- * return false;- * } while (target > doc());- * return true;- * }- * </pre>- * Some implementations are considerably more efficient than that.- */- boolean skipTo(int target) throws IOException;-- /** Frees associated resources. */- void close() throws IOException;-}--diff --git a/lucene/src/java/org/apache/lucene/index/TermEnum.java b/lucene/src/java/org/apache/lucene/index/TermEnum.javadeleted file mode 100644index ec39a7db592..00000000000--- a/lucene/src/java/org/apache/lucene/index/TermEnum.java+++ /dev/null@@ -1,42 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.io.Closeable;--/** Abstract class for enumerating terms.-- <p>Term enumerations are always ordered by Term.compareTo(). Each term in- the enumeration is greater than all that precede it.-* @deprecated Use TermsEnum instead */--@Deprecated-public abstract class TermEnum implements Closeable {- /** Increments the enumeration to the next element. True if one exists.*/- public abstract boolean next() throws IOException;-- /** Returns the current Term in the enumeration.*/- public abstract Term term();-- /** Returns the docFreq of the current Term in the enumeration.*/- public abstract int docFreq();-- /** Closes the enumeration to further activity, freeing resources. */- public abstract void close() throws IOException;-}diff --git a/lucene/src/java/org/apache/lucene/index/TermPositions.java b/lucene/src/java/org/apache/lucene/index/TermPositions.javadeleted file mode 100644index 6e5af8b79e4..00000000000--- a/lucene/src/java/org/apache/lucene/index/TermPositions.java+++ /dev/null@@ -1,80 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--/**- * TermPositions provides an interface for enumerating the <document,- * frequency, <position>* > tuples for a term. <p> The document and- * frequency are the same as for a TermDocs. The positions portion lists the ordinal- * positions of each occurrence of a term in a document.- *- * @see IndexReader#termPositions()- * @deprecated Use {@link DocsAndPositionsEnum} instead- */-@Deprecated-public interface TermPositions- extends TermDocs-{- /** Returns next position in the current document. It is an error to call- this more than {@link #freq()} times- without calling {@link #next()}<p> This is- invalid until {@link #next()} is called for- the first time.- */- int nextPosition() throws IOException;-- /**- * Returns the length of the payload at the current term position.- * This is invalid until {@link #nextPosition()} is called for- * the first time.<br>- * @return length of the current payload in number of bytes- */- int getPayloadLength() throws IOException;-- /**- * Returns the payload data at the current term position.- * This is invalid until {@link #nextPosition()} is called for- * the first time.- * This method must not be called more than once after each call- * of {@link #nextPosition()}. However, payloads are loaded lazily,- * so if the payload data for the current position is not needed,- * this method may not be called at all for performance reasons.<br>- *- * @param data the array into which the data of this payload is to be- * stored, if it is big enough; otherwise, a new byte[] array- * is allocated for this purpose.- * @param offset the offset in the array into which the data of this payload- * is to be stored.- * @return a byte[] array containing the data of this payload- * @throws IOException- */- byte[] getPayload(byte[] data, int offset) throws IOException;-- /**- * Checks if a payload can be loaded at this position.- * <p>- * Payloads can only be loaded once per call to- * {@link #nextPosition()}.- *- * @return true if there is a payload available at this position that can be loaded- */- public boolean isPayloadAvailable();--}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermDocs.java b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermDocs.javaindex 55cda817aa7..eba65b24279 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermDocs.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermDocs.java@@ -22,8 +22,6 @@ import java.io.IOException;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.FieldInfos;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;import org.apache.lucene.index.codecs.standard.DefaultSkipListReader;import org.apache.lucene.store.IndexInput;import org.apache.lucene.util.Bits;@@ -31,7 +29,7 @@ import org.apache.lucene.util.Bits;/** @deprecated* @lucene.experimental */@Deprecated-public class SegmentTermDocs implements TermDocs {+public class SegmentTermDocs {//protected SegmentReader parent;private final FieldInfos fieldInfos;private final TermInfosReader tis;@@ -84,17 +82,16 @@ public class SegmentTermDocs implements TermDocs {this.skipDocs = skipDocs;}- public void seek(TermEnum termEnum) throws IOException {+ public void seek(SegmentTermEnum segmentTermEnum) throws IOException {TermInfo ti;Term term;// use comparison of fieldinfos to verify that termEnum belongs to the same segment as this SegmentTermDocs- if (termEnum instanceof SegmentTermEnum && ((SegmentTermEnum) termEnum).fieldInfos == fieldInfos) { // optimized case- SegmentTermEnum segmentTermEnum = ((SegmentTermEnum) termEnum);+ if (segmentTermEnum.fieldInfos == fieldInfos) { // optimized caseterm = segmentTermEnum.term();ti = segmentTermEnum.termInfo();} else { // punt case- term = termEnum.term();+ term = segmentTermEnum.term();ti = tis.get(term);}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermEnum.java b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermEnum.javaindex 0b778d4e64b..bbf7f36fe14 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermEnum.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermEnum.java@@ -20,7 +20,6 @@ package org.apache.lucene.index.codecs.preflex;import java.io.IOException;import org.apache.lucene.store.IndexInput;import org.apache.lucene.index.FieldInfos;-import org.apache.lucene.index.TermEnum;import org.apache.lucene.index.Term;import org.apache.lucene.index.CorruptIndexException;@@ -30,7 +29,7 @@ import org.apache.lucene.index.CorruptIndexException;* @lucene.experimental */@Deprecated-public final class SegmentTermEnum extends TermEnum implements Cloneable {+public final class SegmentTermEnum implements Cloneable {private IndexInput input;FieldInfos fieldInfos;long size;@@ -128,7 +127,6 @@ public final class SegmentTermEnum extends TermEnum implements Cloneable {}/** Increments the enumeration to the next element. True if one exists.*/- @Overridepublic final boolean next() throws IOException {if (position++ >= size - 1) {prevBuffer.set(termBuffer);@@ -176,7 +174,6 @@ public final class SegmentTermEnum extends TermEnum implements Cloneable {/** Returns the current Term in the enumeration.Initially invalid, valid after next() called for the first time.*/- @Overridepublic final Term term() {return termBuffer.toTerm();}@@ -200,7 +197,6 @@ public final class SegmentTermEnum extends TermEnum implements Cloneable {/** Returns the docFreq from the current TermInfo in the enumeration.Initially invalid, valid after next() called for the first time.*/- @Overridepublic final int docFreq() {return termInfo.docFreq;}@@ -218,7 +214,6 @@ public final class SegmentTermEnum extends TermEnum implements Cloneable {}/** Closes the enumeration to further activity, freeing resources. */- @Overridepublic final void close() throws IOException {input.close();}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermPositions.java b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermPositions.javaindex 3f2c3ddcc6b..d7492df1e70 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermPositions.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/preflex/SegmentTermPositions.java@@ -21,12 +21,11 @@ import java.io.IOException;import org.apache.lucene.index.FieldInfos;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermPositions;import org.apache.lucene.store.IndexInput;/** @lucene.experimental */public final class SegmentTermPositions-extends SegmentTermDocs implements TermPositions {+extends SegmentTermDocs {private IndexInput proxStream;private IndexInput proxStreamOrig;private int proxCount;@@ -55,7 +54,6 @@ extends SegmentTermDocs implements TermPositions {this.proxStreamOrig = proxStream; // the proxStream will be cloned lazily when nextPosition() is called for the first time}- @Overridefinal void seek(TermInfo ti, Term term) throws IOException {super.seek(ti, term);if (ti != null)@@ -67,7 +65,6 @@ extends SegmentTermDocs implements TermPositions {needToLoadPayload = false;}- @Overridepublic final void close() throws IOException {super.close();if (proxStream != null) proxStream.close();@@ -99,13 +96,11 @@ extends SegmentTermDocs implements TermPositions {return delta;}- @Overrideprotected final void skippingDoc() throws IOException {// we remember to skip a document lazilylazySkipProxCount += freq;}- @Overridepublic final boolean next() throws IOException {// we remember to skip the remaining positions of the current// document lazily@@ -119,14 +114,12 @@ extends SegmentTermDocs implements TermPositions {return false;}- @Overridepublic final int read(final int[] docs, final int[] freqs) {throw new UnsupportedOperationException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead.");}/** Called by super.skipTo(). */- @Overrideprotected void skipProx(long proxPointer, int payloadLength) throws IOException {// we save the pointer, we might have to skip there lazilylazySkipPointer = proxPointer;diff --git a/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsReaderImpl.java b/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsReaderImpl.javaindex 4d4899d468c..e9ac3d7c627 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsReaderImpl.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsReaderImpl.java@@ -152,11 +152,19 @@ public class StandardPostingsReaderImpl extends StandardPostingsReader {@Overridepublic DocsEnum docs(FieldInfo fieldInfo, TermState termState, Bits skipDocs, DocsEnum reuse) throws IOException {- final SegmentDocsEnum docsEnum;+ SegmentDocsEnum docsEnum;if (reuse == null) {docsEnum = new SegmentDocsEnum(freqIn);+ } else if (!(reuse instanceof SegmentDocsEnum)) {+ docsEnum = new SegmentDocsEnum(freqIn);} else {docsEnum = (SegmentDocsEnum) reuse;+ if (docsEnum.freqIn != freqIn) {+ // If you are using ParellelReader, and pass in a+ // reused DocsEnum, it could have come from another+ // reader also using standard codec+ docsEnum = new SegmentDocsEnum(freqIn);+ }}return docsEnum.reset(fieldInfo, (DocTermState) termState, skipDocs);}diff --git a/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java b/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.javaindex 7456c8531fb..5112fcefe40 100644--- a/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java+++ b/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java@@ -22,7 +22,6 @@ import java.io.IOException;import org.apache.lucene.index.IndexReader;import org.apache.lucene.util.OpenBitSet;import org.apache.lucene.util.BytesRef;-import org.apache.lucene.index.TermDocs; // for javadocs/*** A {@link Filter} that only accepts documents whose single@@ -70,7 +69,7 @@ import org.apache.lucene.index.TermDocs; // for javadocs** In contrast, TermsFilter builds up an {@link OpenBitSet},* keyed by docID, every time it's created, by enumerating- * through all matching docs using {@link TermDocs} to seek+ * through all matching docs using {@link DocsEnum} to seek* and scan through each term's docID list. While there is* no linear scan of all docIDs, besides the allocation of* the underlying array in the {@link OpenBitSet}, thisdiff --git a/lucene/src/java/org/apache/lucene/search/FilteredTermEnum.java b/lucene/src/java/org/apache/lucene/search/FilteredTermEnum.javadeleted file mode 100644index 4933a903e88..00000000000--- a/lucene/src/java/org/apache/lucene/search/FilteredTermEnum.java+++ /dev/null@@ -1,115 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;--/** Abstract class for enumerating a subset of all terms.-- <p>Term enumerations are always ordered by Term.compareTo(). Each term in- the enumeration is greater than all that precede it.-- @deprecated Switch to {@link FilteredTermsEnum} instead.-*/-@Deprecated-public abstract class FilteredTermEnum extends TermEnum {- /** the current term */- protected Term currentTerm = null;-- /** the delegate enum - to set this member use {@link #setEnum} */- protected TermEnum actualEnum = null;-- public FilteredTermEnum() {}-- /** Equality compare on the term */- protected abstract boolean termCompare(Term term);-- /** Equality measure on the term, it is in reality a boost- * factor and used like so in {@link MultiTermQuery},- * so the name is wrong.- * @deprecated Use {@link MultiTermQuery.BoostAttribute}- * together with {@link FilteredTermsEnum}. For example- * see {@link FuzzyTermsEnum}- */- @Deprecated- public abstract float difference();-- /** Indicates the end of the enumeration has been reached */- protected abstract boolean endEnum();-- /**- * use this method to set the actual TermEnum (e.g. in ctor),- * it will be automatically positioned on the first matching term.- */- protected void setEnum(TermEnum actualEnum) throws IOException {- this.actualEnum = actualEnum;- // Find the first term that matches- Term term = actualEnum.term();- if (term != null && termCompare(term))- currentTerm = term;- else next();- }-- /**- * Returns the docFreq of the current Term in the enumeration.- * Returns -1 if no Term matches or all terms have been enumerated.- */- @Override- public int docFreq() {- if (currentTerm == null) return -1;- assert actualEnum != null;- return actualEnum.docFreq();- }-- /** Increments the enumeration to the next element. True if one exists. */- @Override- public boolean next() throws IOException {- if (actualEnum == null) return false; // the actual enumerator is not initialized!- currentTerm = null;- while (currentTerm == null) {- if (endEnum()) return false;- if (actualEnum.next()) {- Term term = actualEnum.term();- if (termCompare(term)) {- currentTerm = term;- return true;- }- }- else return false;- }- currentTerm = null;- return false;- }-- /** Returns the current Term in the enumeration.- * Returns null if no Term matches or all terms have been enumerated. */- @Override- public Term term() {- return currentTerm;- }-- /** Closes the enumeration to further activity, freeing resources. */- @Override- public void close() throws IOException {- if (actualEnum != null) actualEnum.close();- currentTerm = null;- actualEnum = null;- }-}diff --git a/lucene/src/java/org/apache/lucene/search/FuzzyQuery.java b/lucene/src/java/org/apache/lucene/search/FuzzyQuery.javaindex 0502ff88b8b..4e7fc1231e6 100644--- a/lucene/src/java/org/apache/lucene/search/FuzzyQuery.java+++ b/lucene/src/java/org/apache/lucene/search/FuzzyQuery.java@@ -130,14 +130,6 @@ public class FuzzyQuery extends MultiTermQuery {return prefixLength;}- @Override @Deprecated- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- if (!termLongEnough) { // can only match if it's exact- return new SingleTermEnum(reader, term);- }- return new FuzzyTermEnum(reader, getTerm(), minimumSimilarity, prefixLength);- }-@Overrideprotected TermsEnum getTermsEnum(IndexReader reader) throws IOException {if (!termLongEnough) { // can only match if it's exactdiff --git a/lucene/src/java/org/apache/lucene/search/FuzzyTermEnum.java b/lucene/src/java/org/apache/lucene/search/FuzzyTermEnum.javadeleted file mode 100644index c65256c6fa5..00000000000--- a/lucene/src/java/org/apache/lucene/search/FuzzyTermEnum.java+++ /dev/null@@ -1,288 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;--/** Subclass of FilteredTermEnum for enumerating all terms that are similar- * to the specified filter term.- *- * <p>Term enumerations are always ordered by Term.compareTo(). Each term in- * the enumeration is greater than all that precede it.- *- * @deprecated Please use {@link FuzzyTermsEnum} instead.- */-@Deprecated-public final class FuzzyTermEnum extends FilteredTermEnum {-- /* Allows us save time required to create a new array- * every time similarity is called.- */- private int[] p;- private int[] d;-- private float similarity;- private boolean endEnum = false;-- private Term searchTerm = null;- private final String field;- private final String text;- private final String prefix;-- private final float minimumSimilarity;- private final float scale_factor;-- /**- * Creates a FuzzyTermEnum with an empty prefix and a minSimilarity of 0.5f.- * <p>- * After calling the constructor the enumeration is already pointing to the first- * valid term if such a term exists.- *- * @param reader- * @param term- * @throws IOException- * @see #FuzzyTermEnum(IndexReader, Term, float, int)- */- public FuzzyTermEnum(IndexReader reader, Term term) throws IOException {- this(reader, term, FuzzyQuery.defaultMinSimilarity, FuzzyQuery.defaultPrefixLength);- }-- /**- * Creates a FuzzyTermEnum with an empty prefix.- * <p>- * After calling the constructor the enumeration is already pointing to the first- * valid term if such a term exists.- *- * @param reader- * @param term- * @param minSimilarity- * @throws IOException- * @see #FuzzyTermEnum(IndexReader, Term, float, int)- */- public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity) throws IOException {- this(reader, term, minSimilarity, FuzzyQuery.defaultPrefixLength);- }-- /**- * Constructor for enumeration of all terms from specified <code>reader</code> which share a prefix of- * length <code>prefixLength</code> with <code>term</code> and which have a fuzzy similarity >- * <code>minSimilarity</code>.- * <p>- * After calling the constructor the enumeration is already pointing to the first- * valid term if such a term exists.- *- * @param reader Delivers terms.- * @param term Pattern term.- * @param minSimilarity Minimum required similarity for terms from the reader. Default value is 0.5f.- * @param prefixLength Length of required common prefix. Default value is 0.- * @throws IOException- */- public FuzzyTermEnum(IndexReader reader, Term term, final float minSimilarity, final int prefixLength) throws IOException {- super();-- if (minSimilarity >= 1.0f)- throw new IllegalArgumentException("minimumSimilarity cannot be greater than or equal to 1");- else if (minSimilarity < 0.0f)- throw new IllegalArgumentException("minimumSimilarity cannot be less than 0");- if(prefixLength < 0)- throw new IllegalArgumentException("prefixLength cannot be less than 0");-- this.minimumSimilarity = minSimilarity;- this.scale_factor = 1.0f / (1.0f - minimumSimilarity);- this.searchTerm = term;- this.field = searchTerm.field();-- //The prefix could be longer than the word.- //It's kind of silly though. It means we must match the entire word.- final int fullSearchTermLength = searchTerm.text().length();- final int realPrefixLength = prefixLength > fullSearchTermLength ? fullSearchTermLength : prefixLength;-- this.text = searchTerm.text().substring(realPrefixLength);- this.prefix = searchTerm.text().substring(0, realPrefixLength);-- this.p = new int[this.text.length()+1];- this.d = new int[this.text.length()+1];-- setEnum(reader.terms(new Term(searchTerm.field(), prefix)));- }-- /**- * The termCompare method in FuzzyTermEnum uses Levenshtein distance to- * calculate the distance between the given term and the comparing term.- */- @Override- protected final boolean termCompare(Term term) {- if (field == term.field() && term.text().startsWith(prefix)) {- final String target = term.text().substring(prefix.length());- this.similarity = similarity(target);- return (similarity > minimumSimilarity);- }- endEnum = true;- return false;- }-- /** @deprecated Use {@link MultiTermQuery.BoostAttribute} together with {@link FuzzyTermsEnum} */- @Deprecated- @Override- public final float difference() {- return (similarity - minimumSimilarity) * scale_factor;- }-- /** {@inheritDoc} */- @Override- public final boolean endEnum() {- return endEnum;- }-- /******************************- * Compute Levenshtein distance- ******************************/-- /**- * <p>Similarity returns a number that is 1.0f or less (including negative numbers)- * based on how similar the Term is compared to a target term. It returns- * exactly 0.0f when- * <pre>- * editDistance > maximumEditDistance</pre>- * Otherwise it returns:- * <pre>- * 1 - (editDistance / length)</pre>- * where length is the length of the shortest term (text or target) including a- * prefix that are identical and editDistance is the Levenshtein distance for- * the two words.</p>- *- * <p>Embedded within this algorithm is a fail-fast Levenshtein distance- * algorithm. The fail-fast algorithm differs from the standard Levenshtein- * distance algorithm in that it is aborted if it is discovered that the- * minimum distance between the words is greater than some threshold.- *- * <p>To calculate the maximum distance threshold we use the following formula:- * <pre>- * (1 - minimumSimilarity) * length</pre>- * where length is the shortest term including any prefix that is not part of the- * similarity comparison. This formula was derived by solving for what maximum value- * of distance returns false for the following statements:- * <pre>- * similarity = 1 - ((float)distance / (float) (prefixLength + Math.min(textlen, targetlen)));- * return (similarity > minimumSimilarity);</pre>- * where distance is the Levenshtein distance for the two words.- * </p>- * <p>Levenshtein distance (also known as edit distance) is a measure of similarity- * between two strings where the distance is measured as the number of character- * deletions, insertions or substitutions required to transform one string to- * the other string.- * @param target the target word or phrase- * @return the similarity, 0.0 or less indicates that it matches less than the required- * threshold and 1.0 indicates that the text and target are identical- */- private float similarity(final String target) {- final int m = target.length();- final int n = text.length();- if (n == 0) {- //we don't have anything to compare. That means if we just add- //the letters for m we get the new word- return prefix.length() == 0 ? 0.0f : 1.0f - ((float) m / prefix.length());- }- if (m == 0) {- return prefix.length() == 0 ? 0.0f : 1.0f - ((float) n / prefix.length());- }-- final int maxDistance = calculateMaxDistance(m);-- if (maxDistance < Math.abs(m-n)) {- //just adding the characters of m to n or vice-versa results in- //too many edits- //for example "pre" length is 3 and "prefixes" length is 8. We can see that- //given this optimal circumstance, the edit distance cannot be less than 5.- //which is 8-3 or more precisely Math.abs(3-8).- //if our maximum edit distance is 4, then we can discard this word- //without looking at it.- return 0.0f;- }-- // init matrix d- for (int i = 0; i<=n; ++i) {- p[i] = i;- }-- // start computing edit distance- for (int j = 1; j<=m; ++j) { // iterates through target- int bestPossibleEditDistance = m;- final char t_j = target.charAt(j-1); // jth character of t- d[0] = j;-- for (int i=1; i<=n; ++i) { // iterates through text- // minimum of cell to the left+1, to the top+1, diagonally left and up +(0|1)- if (t_j != text.charAt(i-1)) {- d[i] = Math.min(Math.min(d[i-1], p[i]), p[i-1]) + 1;- } else {- d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]);- }- bestPossibleEditDistance = Math.min(bestPossibleEditDistance, d[i]);- }-- //After calculating row i, the best possible edit distance- //can be found by found by finding the smallest value in a given column.- //If the bestPossibleEditDistance is greater than the max distance, abort.-- if (j > maxDistance && bestPossibleEditDistance > maxDistance) { //equal is okay, but not greater- //the closest the target can be to the text is just too far away.- //this target is leaving the party early.- return 0.0f;- }-- // copy current distance counts to 'previous row' distance counts: swap p and d- int _d[] = p;- p = d;- d = _d;- }-- // our last action in the above loop was to switch d and p, so p now- // actually has the most recent cost counts-- // this will return less than 0.0 when the edit distance is- // greater than the number of characters in the shorter word.- // but this was the formula that was previously used in FuzzyTermEnum,- // so it has not been changed (even though minimumSimilarity must be- // greater than 0.0)- return 1.0f - ((float)p[n] / (float) (prefix.length() + Math.min(n, m)));- }-- /**- * The max Distance is the maximum Levenshtein distance for the text- * compared to some other value that results in score that is- * better than the minimum similarity.- * @param m the length of the "other value"- * @return the maximum levenshtein distance that we care about- */- private int calculateMaxDistance(int m) {- return (int) ((1-minimumSimilarity) * (Math.min(text.length(), m) + prefix.length()));- }-- /** {@inheritDoc} */- @Override- public void close() throws IOException {- p = d = null;- searchTerm = null;- super.close(); //call super.close() and let the garbage collector do its work.- }--}diff --git a/lucene/src/java/org/apache/lucene/search/MultiTermQuery.java b/lucene/src/java/org/apache/lucene/search/MultiTermQuery.javaindex 67a80da2489..47c73fdff4f 100644--- a/lucene/src/java/org/apache/lucene/search/MultiTermQuery.java+++ b/lucene/src/java/org/apache/lucene/search/MultiTermQuery.java@@ -32,7 +32,6 @@ import org.apache.lucene.index.Terms;import org.apache.lucene.queryParser.QueryParser; // for javadocimport org.apache.lucene.util.Attribute;import org.apache.lucene.util.AttributeImpl;-import org.apache.lucene.util.VirtualMethod;/*** An abstract {@link Query} that matches documents@@ -72,17 +71,6 @@ public abstract class MultiTermQuery extends Query {protected RewriteMethod rewriteMethod = CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;transient int numberOfTerms = 0;- /** @deprecated remove when getEnum is removed */- private static final VirtualMethod<MultiTermQuery> getEnumMethod =- new VirtualMethod<MultiTermQuery>(MultiTermQuery.class, "getEnum", IndexReader.class);- /** @deprecated remove when getEnum is removed */- private static final VirtualMethod<MultiTermQuery> getTermsEnumMethod =- new VirtualMethod<MultiTermQuery>(MultiTermQuery.class, "getTermsEnum", IndexReader.class);- /** @deprecated remove when getEnum is removed */- final boolean hasNewAPI =- VirtualMethod.compareImplementationDistance(getClass(),- getTermsEnumMethod, getEnumMethod) >= 0; // its ok for both to be overridden-/** Add this {@link Attribute} to a {@link TermsEnum} returned by {@link #getTermsEnum}* and update the boost on each returned term. This enables to control the boost factor* for each matching term in {@link #SCORING_BOOLEAN_QUERY_REWRITE} or@@ -190,64 +178,42 @@ public abstract class MultiTermQuery extends Query {protected final int collectTerms(IndexReader reader, MultiTermQuery query, TermCollector collector) throws IOException {- if (query.hasNewAPI) {-- if (query.field == null) {- throw new NullPointerException("If you implement getTermsEnum(), you must specify a non-null field in the constructor of MultiTermQuery.");- }+ if (query.field == null) {+ throw new NullPointerException("If you implement getTermsEnum(), you must specify a non-null field in the constructor of MultiTermQuery.");+ }- final Fields fields = MultiFields.getFields(reader);- if (fields == null) {- // reader has no fields- return 0;- }+ final Fields fields = MultiFields.getFields(reader);+ if (fields == null) {+ // reader has no fields+ return 0;+ }- final Terms terms = fields.terms(query.field);- if (terms == null) {- // field does not exist- return 0;- }+ final Terms terms = fields.terms(query.field);+ if (terms == null) {+ // field does not exist+ return 0;+ }- final TermsEnum termsEnum = query.getTermsEnum(reader);- assert termsEnum != null;-- if (termsEnum == TermsEnum.EMPTY)- return 0;- final BoostAttribute boostAtt =- termsEnum.attributes().addAttribute(BoostAttribute.class);- collector.boostAtt = boostAtt;- int count = 0;- BytesRef term;- final Term placeholderTerm = new Term(query.field);- while ((term = termsEnum.next()) != null) {- if (collector.collect(placeholderTerm.createTerm(term.utf8ToString()), boostAtt.getBoost())) {- count++;- } else {- break;- }- }- collector.boostAtt = null;- return count;- } else {- // deprecated case- final FilteredTermEnum enumerator = query.getEnum(reader);- int count = 0;- try {- do {- Term t = enumerator.term();- if (t != null) {- if (collector.collect(t, enumerator.difference())) {- count++;- } else {- break;- }- }- } while (enumerator.next());- } finally {- enumerator.close();+ final TermsEnum termsEnum = query.getTermsEnum(reader);+ assert termsEnum != null;++ if (termsEnum == TermsEnum.EMPTY)+ return 0;+ final BoostAttribute boostAtt =+ termsEnum.attributes().addAttribute(BoostAttribute.class);+ collector.boostAtt = boostAtt;+ int count = 0;+ BytesRef term;+ final Term placeholderTerm = new Term(query.field);+ while ((term = termsEnum.next()) != null) {+ if (collector.collect(placeholderTerm.createTerm(term.utf8ToString()), boostAtt.getBoost())) {+ count++;+ } else {+ break;}- return count;}+ collector.boostAtt = null;+ return count;}protected static abstract class TermCollector {@@ -698,14 +664,6 @@ public abstract class MultiTermQuery extends Query {/** Returns the field name for this query */public final String getField() { return field; }- /** Construct the enumeration to be used, expanding the- * pattern term.- * @deprecated Please override {@link #getTermsEnum} instead */- @Deprecated- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- throw new UnsupportedOperationException();- }-/** Construct the enumeration to be used, expanding the* pattern term. This method should only be called if* the field exists (ie, implementations can assume the@@ -713,10 +671,7 @@ public abstract class MultiTermQuery extends Query {* (should instead return {@link TermsEnum#EMPTY} if no* terms match). The TermsEnum must already be* positioned to the first matching term. */- // TODO 4.0: make this method abstract- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- throw new UnsupportedOperationException();- }+ protected abstract TermsEnum getTermsEnum(IndexReader reader) throws IOException;/*** Expert: Return the number of unique terms visited during execution of the query.diff --git a/lucene/src/java/org/apache/lucene/search/MultiTermQueryWrapperFilter.java b/lucene/src/java/org/apache/lucene/search/MultiTermQueryWrapperFilter.javaindex e24f097d8f8..a6b5c87d59f 100644--- a/lucene/src/java/org/apache/lucene/search/MultiTermQueryWrapperFilter.java+++ b/lucene/src/java/org/apache/lucene/search/MultiTermQueryWrapperFilter.java@@ -20,11 +20,8 @@ package org.apache.lucene.search;import java.io.IOException;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;import org.apache.lucene.index.Fields;import org.apache.lucene.index.Terms;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;import org.apache.lucene.index.TermsEnum;import org.apache.lucene.index.DocsEnum;import org.apache.lucene.index.MultiFields;@@ -109,97 +106,54 @@ public class MultiTermQueryWrapperFilter<Q extends MultiTermQuery> extends Filte*/@Overridepublic DocIdSet getDocIdSet(IndexReader reader) throws IOException {- if (query.hasNewAPI) {- if (query.field == null) {- throw new NullPointerException("If you implement getTermsEnum(), you must specify a non-null field in the constructor of MultiTermQuery.");- }+ if (query.field == null) {+ throw new NullPointerException("If you implement getTermsEnum(), you must specify a non-null field in the constructor of MultiTermQuery.");+ }- final Fields fields = MultiFields.getFields(reader);- if (fields == null) {- // reader has no fields- return DocIdSet.EMPTY_DOCIDSET;- }+ final Fields fields = MultiFields.getFields(reader);+ if (fields == null) {+ // reader has no fields+ return DocIdSet.EMPTY_DOCIDSET;+ }- final Terms terms = fields.terms(query.field);- if (terms == null) {- // field does not exist- return DocIdSet.EMPTY_DOCIDSET;- }+ final Terms terms = fields.terms(query.field);+ if (terms == null) {+ // field does not exist+ return DocIdSet.EMPTY_DOCIDSET;+ }- final TermsEnum termsEnum = query.getTermsEnum(reader);- assert termsEnum != null;- if (termsEnum.next() != null) {- // fill into a OpenBitSet- final OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());- int termCount = 0;- final Bits delDocs = MultiFields.getDeletedDocs(reader);- DocsEnum docsEnum = null;- do {- termCount++;- // System.out.println(" iter termCount=" + termCount + " term=" +- // enumerator.term().toBytesString());- docsEnum = termsEnum.docs(delDocs, docsEnum);- final DocsEnum.BulkReadResult result = docsEnum.getBulkResult();- while (true) {- final int count = docsEnum.read();- if (count != 0) {- final int[] docs = result.docs.ints;- for (int i = 0; i < count; i++) {- bitSet.set(docs[i]);- }- } else {- break;+ final TermsEnum termsEnum = query.getTermsEnum(reader);+ assert termsEnum != null;+ if (termsEnum.next() != null) {+ // fill into a OpenBitSet+ final OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());+ int termCount = 0;+ final Bits delDocs = MultiFields.getDeletedDocs(reader);+ DocsEnum docsEnum = null;+ do {+ termCount++;+ // System.out.println(" iter termCount=" + termCount + " term=" ++ // enumerator.term().toBytesString());+ docsEnum = termsEnum.docs(delDocs, docsEnum);+ final DocsEnum.BulkReadResult result = docsEnum.getBulkResult();+ while (true) {+ final int count = docsEnum.read();+ if (count != 0) {+ final int[] docs = result.docs.ints;+ for (int i = 0; i < count; i++) {+ bitSet.set(docs[i]);}+ } else {+ break;}- } while (termsEnum.next() != null);- // System.out.println(" done termCount=" + termCount);+ }+ } while (termsEnum.next() != null);+ // System.out.println(" done termCount=" + termCount);- query.incTotalNumberOfTerms(termCount);- return bitSet;- } else {- return DocIdSet.EMPTY_DOCIDSET;- }+ query.incTotalNumberOfTerms(termCount);+ return bitSet;} else {- final TermEnum enumerator = query.getEnum(reader);- try {- // if current term in enum is null, the enum is empty -> shortcut- if (enumerator.term() == null)- return DocIdSet.EMPTY_DOCIDSET;- // else fill into a OpenBitSet- final OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());- final int[] docs = new int[32];- final int[] freqs = new int[32];- TermDocs termDocs = reader.termDocs();- try {- int termCount = 0;- do {- Term term = enumerator.term();- if (term == null)- break;- termCount++;- termDocs.seek(term);- while (true) {- final int count = termDocs.read(docs, freqs);- if (count != 0) {- for (int i = 0; i < count; i++) {- bitSet.set(docs[i]);- }- } else {- break;- }- }- } while (enumerator.next());-- query.incTotalNumberOfTerms(termCount);-- } finally {- termDocs.close();- }- return bitSet;- } finally {- enumerator.close();- }+ return DocIdSet.EMPTY_DOCIDSET;}}-}diff --git a/lucene/src/java/org/apache/lucene/search/PrefixQuery.java b/lucene/src/java/org/apache/lucene/search/PrefixQuery.javaindex 9ef09138662..5215a12155e 100644--- a/lucene/src/java/org/apache/lucene/search/PrefixQuery.java+++ b/lucene/src/java/org/apache/lucene/search/PrefixQuery.java@@ -44,11 +44,6 @@ public class PrefixQuery extends MultiTermQuery {/** Returns the prefix of this query. */public Term getPrefix() { return prefix; }- @Override @Deprecated- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new PrefixTermEnum(reader, prefix);- }-@Overrideprotected TermsEnum getTermsEnum(IndexReader reader) throws IOException {if (prefix.text().length() == 0) {diff --git a/lucene/src/java/org/apache/lucene/search/PrefixTermEnum.java b/lucene/src/java/org/apache/lucene/search/PrefixTermEnum.javadeleted file mode 100644index 4aa28003935..00000000000--- a/lucene/src/java/org/apache/lucene/search/PrefixTermEnum.java+++ /dev/null@@ -1,68 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;--/**- * Subclass of FilteredTermEnum for enumerating all terms that match the- * specified prefix filter term.- * <p>- * Term enumerations are always ordered by Term.compareTo(). Each term in- * the enumeration is greater than all that precede it.- *- * @deprecated Use {@link PrefixTermsEnum} instead.- */-@Deprecated-public class PrefixTermEnum extends FilteredTermEnum {-- private final Term prefix;- private boolean endEnum = false;-- public PrefixTermEnum(IndexReader reader, Term prefix) throws IOException {- this.prefix = prefix;-- setEnum(reader.terms(new Term(prefix.field(), prefix.text())));- }-- @Override- public float difference() {- return 1.0f;- }-- @Override- protected boolean endEnum() {- return endEnum;- }-- protected Term getPrefixTerm() {- return prefix;- }-- @Override- protected boolean termCompare(Term term) {- if (term.field() == prefix.field() && term.text().startsWith(prefix.text())) {- return true;- }- endEnum = true;- return false;- }-}diff --git a/lucene/src/java/org/apache/lucene/search/SingleTermEnum.java b/lucene/src/java/org/apache/lucene/search/SingleTermEnum.javadeleted file mode 100644index 332381531bd..00000000000--- a/lucene/src/java/org/apache/lucene/search/SingleTermEnum.java+++ /dev/null@@ -1,68 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;--/**- * Subclass of FilteredTermEnum for enumerating a single term.- * <p>- * This can be used by {@link MultiTermQuery}s that need only visit one term,- * but want to preserve MultiTermQuery semantics such as- * {@link MultiTermQuery#rewriteMethod}.- */-@Deprecated-public class SingleTermEnum extends FilteredTermEnum {- private Term singleTerm;- private boolean endEnum = false;-- /**- * Creates a new <code>SingleTermEnum</code>.- * <p>- * After calling the constructor the enumeration is already pointing to the term,- * if it exists.- */- public SingleTermEnum(IndexReader reader, Term singleTerm) throws IOException {- super();- this.singleTerm = singleTerm;- setEnum(reader.terms(singleTerm));- }-- @Override- public float difference() {- return 1.0F;- }-- @Override- protected boolean endEnum() {- return endEnum;- }-- @Override- protected boolean termCompare(Term term) {- if (term.equals(singleTerm)) {- return true;- } else {- endEnum = true;- return false;- }- }-}diff --git a/lucene/src/java/org/apache/lucene/search/TermRangeQuery.java b/lucene/src/java/org/apache/lucene/search/TermRangeQuery.javaindex 045e6891cb7..bcec3e371a0 100644--- a/lucene/src/java/org/apache/lucene/search/TermRangeQuery.java+++ b/lucene/src/java/org/apache/lucene/search/TermRangeQuery.java@@ -129,12 +129,6 @@ public class TermRangeQuery extends MultiTermQuery {/** Returns the collator used to determine range inclusion, if any. */public Collator getCollator() { return collator; }- @Override @Deprecated- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new TermRangeTermEnum(reader, field, lowerTerm,- upperTerm, includeLower, includeUpper, collator);- }-@Overrideprotected TermsEnum getTermsEnum(IndexReader reader) throws IOException {if (collator == null && lowerTerm != null && upperTerm != null && lowerTerm.compareTo(upperTerm) > 0) {diff --git a/lucene/src/java/org/apache/lucene/search/TermRangeTermEnum.java b/lucene/src/java/org/apache/lucene/search/TermRangeTermEnum.javadeleted file mode 100644index ac28464de1d..00000000000--- a/lucene/src/java/org/apache/lucene/search/TermRangeTermEnum.java+++ /dev/null@@ -1,156 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.text.Collator;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.util.StringHelper;--/**- * Subclass of FilteredTermEnum for enumerating all terms that match the- * specified range parameters.- * <p>- * Term enumerations are always ordered by Term.compareTo(). Each term in- * the enumeration is greater than all that precede it.- * @since 2.9- * @deprecated Please switch to {@link TermRangeTermsEnum}- */-@Deprecated-public class TermRangeTermEnum extends FilteredTermEnum {-- private Collator collator = null;- private boolean endEnum = false;- private String field;- private String upperTermText;- private String lowerTermText;- private boolean includeLower;- private boolean includeUpper;-- /**- * Enumerates all terms greater/equal than <code>lowerTerm</code>- * but less/equal than <code>upperTerm</code>.- *- * If an endpoint is null, it is said to be "open". Either or both- * endpoints may be open. Open endpoints may not be exclusive- * (you can't select all but the first or last term without- * explicitly specifying the term to exclude.)- *- * @param reader- * @param field- * An interned field that holds both lower and upper terms.- * @param lowerTermText- * The term text at the lower end of the range- * @param upperTermText- * The term text at the upper end of the range- * @param includeLower- * If true, the <code>lowerTerm</code> is included in the range.- * @param includeUpper- * If true, the <code>upperTerm</code> is included in the range.- * @param collator- * The collator to use to collate index Terms, to determine their- * membership in the range bounded by <code>lowerTerm</code> and- * <code>upperTerm</code>.- *- * @throws IOException- */- public TermRangeTermEnum(IndexReader reader, String field, String lowerTermText, String upperTermText,- boolean includeLower, boolean includeUpper, Collator collator) throws IOException {- this.collator = collator;- this.upperTermText = upperTermText;- this.lowerTermText = lowerTermText;- this.includeLower = includeLower;- this.includeUpper = includeUpper;- this.field = StringHelper.intern(field);-- // do a little bit of normalization...- // open ended range queries should always be inclusive.- if (this.lowerTermText == null) {- this.lowerTermText = "";- this.includeLower = true;- }-- if (this.upperTermText == null) {- this.includeUpper = true;- }-- String startTermText = collator == null ? this.lowerTermText : "";- setEnum(reader.terms(new Term(this.field, startTermText)));- }-- @Override- public float difference() {- return 1.0f;- }-- @Override- protected boolean endEnum() {- return endEnum;- }-- @Override- protected boolean termCompare(Term term) {- if (collator == null) {- // Use Unicode code point ordering- boolean checkLower = false;- if (!includeLower) // make adjustments to set to exclusive- checkLower = true;- if (term != null && term.field() == field) { // interned comparison- if (!checkLower || null==lowerTermText || term.text().compareTo(lowerTermText) > 0) {- checkLower = false;- if (upperTermText != null) {- int compare = upperTermText.compareTo(term.text());- /*- * if beyond the upper term, or is exclusive and this is equal to- * the upper term, break out- */- if ((compare < 0) ||- (!includeUpper && compare==0)) {- endEnum = true;- return false;- }- }- return true;- }- } else {- // break- endEnum = true;- return false;- }- return false;- } else {- if (term != null && term.field() == field) { // interned comparison- if ((lowerTermText == null- || (includeLower- ? collator.compare(term.text(), lowerTermText) >= 0- : collator.compare(term.text(), lowerTermText) > 0))- && (upperTermText == null- || (includeUpper- ? collator.compare(term.text(), upperTermText) <= 0- : collator.compare(term.text(), upperTermText) < 0))) {- return true;- }- return false;- }- endEnum = true;- return false;- }- }-}diff --git a/lucene/src/java/org/apache/lucene/search/WildcardQuery.java b/lucene/src/java/org/apache/lucene/search/WildcardQuery.javaindex b347bba0fd3..81ac8f0ba7f 100644--- a/lucene/src/java/org/apache/lucene/search/WildcardQuery.java+++ b/lucene/src/java/org/apache/lucene/search/WildcardQuery.java@@ -17,15 +17,12 @@ package org.apache.lucene.search;* limitations under the License.*/-import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermsEnum;import org.apache.lucene.util.ToStringUtils;import org.apache.lucene.util.automaton.Automaton;import org.apache.lucene.util.automaton.BasicAutomata;import org.apache.lucene.util.automaton.BasicOperations;-import java.io.IOException;import java.util.ArrayList;import java.util.List;@@ -81,17 +78,6 @@ public class WildcardQuery extends AutomatonQuery {return BasicOperations.concatenate(automata);}- @Override @Deprecated- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new WildcardTermEnum(reader, term);- }-- // we override this method, else backwards layer in MTQ will prefer getEnum!- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return super.getTermsEnum(reader);- }-/*** Returns the pattern term.*/diff --git a/lucene/src/java/org/apache/lucene/search/WildcardTermEnum.java b/lucene/src/java/org/apache/lucene/search/WildcardTermEnum.javadeleted file mode 100644index 7e58c3b31df..00000000000--- a/lucene/src/java/org/apache/lucene/search/WildcardTermEnum.java+++ /dev/null@@ -1,192 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;--/**- * Subclass of FilteredTermEnum for enumerating all terms that match the- * specified wildcard filter term.- * <p>- * Term enumerations are always ordered by Term.compareTo(). Each term in- * the enumeration is greater than all that precede it.- * @deprecated Please use {@link AutomatonTermsEnum} instead.- */-@Deprecated-public class WildcardTermEnum extends FilteredTermEnum {- final Term searchTerm;- final String field;- final String text;- final String pre;- final int preLen;- boolean endEnum = false;-- /**- * Creates a new <code>WildcardTermEnum</code>.- * <p>- * After calling the constructor the enumeration is already pointing to the first- * valid term if such a term exists.- */- public WildcardTermEnum(IndexReader reader, Term term) throws IOException {- super();- searchTerm = term;- field = searchTerm.field();- final String searchTermText = searchTerm.text();-- final int sidx = searchTermText.indexOf(WILDCARD_STRING);- final int cidx = searchTermText.indexOf(WILDCARD_CHAR);- int idx = sidx;- if (idx == -1) {- idx = cidx;- }- else if (cidx >= 0) {- idx = Math.min(idx, cidx);- }- pre = idx != -1?searchTerm.text().substring(0,idx): "";-- preLen = pre.length();- text = searchTermText.substring(preLen);- setEnum(reader.terms(new Term(searchTerm.field(), pre)));- }-- @Override- protected final boolean termCompare(Term term) {- if (field == term.field()) {- String searchText = term.text();- if (searchText.startsWith(pre)) {- return wildcardEquals(text, 0, searchText, preLen);- }- }- endEnum = true;- return false;- }-- @Override- public float difference() {- return 1.0f;- }-- @Override- public final boolean endEnum() {- return endEnum;- }-- /********************************************- * String equality with support for wildcards- ********************************************/-- public static final char WILDCARD_STRING = WildcardQuery.WILDCARD_STRING;- public static final char WILDCARD_CHAR = WildcardQuery.WILDCARD_CHAR;-- /**- * Determines if a word matches a wildcard pattern.- * <small>Work released by Granta Design Ltd after originally being done on- * company time.</small>- */- public static final boolean wildcardEquals(String pattern, int patternIdx,- String string, int stringIdx)- {- int p = patternIdx;-- for (int s = stringIdx; ; ++p, ++s)- {- // End of string yet?- boolean sEnd = (s >= string.length());- // End of pattern yet?- boolean pEnd = (p >= pattern.length());-- // If we're looking at the end of the string...- if (sEnd)- {- // Assume the only thing left on the pattern is/are wildcards- boolean justWildcardsLeft = true;-- // Current wildcard position- int wildcardSearchPos = p;- // While we haven't found the end of the pattern,- // and haven't encountered any non-wildcard characters- while (wildcardSearchPos < pattern.length() && justWildcardsLeft)- {- // Check the character at the current position- char wildchar = pattern.charAt(wildcardSearchPos);-- // If it's not a wildcard character, then there is more- // pattern information after this/these wildcards.- if (wildchar != WILDCARD_CHAR && wildchar != WILDCARD_STRING)- {- justWildcardsLeft = false;- }- else- {- // to prevent "cat" matches "ca??"- if (wildchar == WILDCARD_CHAR) {- return false;- }-- // Look at the next character- wildcardSearchPos++;- }- }-- // This was a prefix wildcard search, and we've matched, so- // return true.- if (justWildcardsLeft)- {- return true;- }- }-- // If we've gone past the end of the string, or the pattern,- // return false.- if (sEnd || pEnd)- {- break;- }-- // Match a single character, so continue.- if (pattern.charAt(p) == WILDCARD_CHAR)- {- continue;- }-- //- if (pattern.charAt(p) == WILDCARD_STRING)- {- // Look at the character beyond the '*'.- ++p;- // Examine the string, starting at the last character.- for (int i = string.length(); i >= s; --i)- {- if (wildcardEquals(pattern, p, string, i))- {- return true;- }- }- break;- }- if (pattern.charAt(p) != string.charAt(s))- {- break;- }- }- return false;- }-}diff --git a/lucene/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java b/lucene/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.javaindex 4ea85d7a71b..61cab72a55d 100644--- a/lucene/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java+++ b/lucene/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java@@ -27,11 +27,12 @@ import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.TermVector;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.IndexWriterConfig;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermPositions;+import org.apache.lucene.index.DocsAndPositionsEnum;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.util.BytesRef;public class TestCachingTokenFilter extends BaseTokenStreamTestCase {private String[] tokens = new String[] {"term1", "term2", "term3", "term2"};@@ -75,19 +76,28 @@ public class TestCachingTokenFilter extends BaseTokenStreamTestCase {writer.close();IndexReader reader = IndexReader.open(dir, true);- TermPositions termPositions = reader.termPositions(new Term("preanalyzed", "term1"));- assertTrue(termPositions.next());+ DocsAndPositionsEnum termPositions = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "preanalyzed",+ new BytesRef("term1"));+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(1, termPositions.freq());assertEquals(0, termPositions.nextPosition());- termPositions.seek(new Term("preanalyzed", "term2"));- assertTrue(termPositions.next());+ termPositions = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "preanalyzed",+ new BytesRef("term2"));+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(2, termPositions.freq());assertEquals(1, termPositions.nextPosition());assertEquals(3, termPositions.nextPosition());- termPositions.seek(new Term("preanalyzed", "term3"));- assertTrue(termPositions.next());+ termPositions = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "preanalyzed",+ new BytesRef("term3"));+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(1, termPositions.freq());assertEquals(2, termPositions.nextPosition());reader.close();diff --git a/lucene/src/test/org/apache/lucene/index/FlexTestUtil.java b/lucene/src/test/org/apache/lucene/index/FlexTestUtil.javadeleted file mode 100644index 13b253c043e..00000000000--- a/lucene/src/test/org/apache/lucene/index/FlexTestUtil.java+++ /dev/null@@ -1,535 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.store.*;-import org.apache.lucene.util.*;-import org.apache.lucene.document.*;-import org.apache.lucene.analysis.*;-import static org.junit.Assert.*;--import java.io.*;-import java.util.*;--public class FlexTestUtil {-- // index variations- // need del docs- // need payloads- // lots of randomness- // surrogate pairs- //-- // need more diverse index- // with omitTFAP- // with payloads- // bigger index-- // test advanceTo, mixed with getting or not getting positions- // test that custom/null skipDocs work- // test: direct flex compared to flex on non flex on flex- // test with flex on one index and non-flex on the other- // (two dirs above)- // temporarily force pre-flex emulation on flex emulation- // on pre-flex segment (in back compat test)- // a sub-reader that has nonzero doc count but 100% are deleted- // foreign bitdocs- // advancing in DocsEnum, then next'ing, nextPosition'ing- // mutlti-reader w/ empty sub-reader- // - eg from merge that had all del docs- // - eg from empty flush- // make sure we test empty field (no terms)- // created from empty field in doc, but also, from- // removing all docs that had the field- // test 1 vs many segment index- // test multireader vs dir reader- // test bulk read api- // wrap reader as "external" reader -- double emulation test- public static void verifyFlexVsPreFlex(Random rand, Directory d) throws Exception {- IndexReader r = IndexReader.open(d);- verifyFlexVsPreFlex(rand, r);- r.close();- }-- public static void verifyFlexVsPreFlex(Random rand, IndexWriter w) throws Exception {- IndexReader r = w.getReader();- verifyFlexVsPreFlex(rand, r);- r.close();- }-- public static void verifyFlexVsPreFlex(Random rand, IndexReader r) throws Exception {- // First test on DirReader-- verifyFlexVsPreFlexSingle(rand, r);-- // Then on each individual sub reader- IndexReader[] subReaders = r.getSequentialSubReaders();- for(int i=0;i<subReaders.length;i++) {- verifyFlexVsPreFlexSingle(rand, subReaders[i]);- }-- // Then on a new MultiReader- IndexReader m = new MultiReader(subReaders, false);- verifyFlexVsPreFlexSingle(rand, m);- m.close();- }-- private static void verifyFlexVsPreFlexSingle(Random rand, IndexReader r) throws Exception {-- //List<Term> allTerms = new ArrayList<Term>();- //System.out.println("TEST: now verify!!");- testStraightEnum(r);- testRandomSkips(rand, r);- testRandomSeeks(rand, r);- testBogusFieldTerms(rand, r);- }-- private static void testBogusFieldTerms(Random rand, IndexReader r) throws Exception {- final Fields fields = MultiFields.getFields(r);- if (fields == null) {- return;- }- for(int i=0;i<10;i++) {- final String f = "bogus" + rand.nextInt() + "reallybogus";- Terms terms = fields.terms(f);- assertTrue(terms == null || terms.iterator().next() == null);- }- }-- private static void testStraightEnum(IndexReader r) throws Exception {-- // straight enum of fields/terms/docs/positions- TermEnum termEnum = r.terms();- final Fields fields = MultiFields.getFields(r);- if (fields == null) {- return;- }- FieldsEnum fieldsEnum = fields.iterator();- while(true) {- final String field = fieldsEnum.next();- if (field == null) {- boolean result = termEnum.next();- if (result) {- System.out.println("got unexpected term=" + termEnum.term() + " termEnum=" + termEnum);- }- assertFalse(result);- break;- }- TermsEnum terms = fieldsEnum.terms();- DocsAndPositionsEnum postings = null;- DocsEnum docsEnum = null;- final TermPositions termPos = r.termPositions();- while(true) {- final BytesRef termRef = terms.next();- if (termRef == null) {- break;- } else {- assertTrue(termEnum.next());- Term t = termEnum.term();- assertEquals(t.field(), field);- assertEquals(t.text(), termRef.utf8ToString());- assertEquals(termEnum.docFreq(), terms.docFreq());- //allTerms.add(t);-- postings = terms.docsAndPositions(MultiFields.getDeletedDocs(r), postings);- docsEnum = terms.docs(MultiFields.getDeletedDocs(r), docsEnum);-- final DocsEnum docs;- if (postings != null) {- docs = postings;- } else {- docs = docsEnum;- }-- termPos.seek(t);- while(true) {- final int doc = docs.nextDoc();- if (doc == DocsEnum.NO_MORE_DOCS) {- assertFalse(termPos.next());- break;- } else {- assertTrue(termPos.next());- assertEquals(termPos.doc(), doc);- assertEquals(termPos.freq(), docs.freq());- final int freq = docs.freq();- if (postings == null) {- assertEquals(1, freq);- // Old API did not always do this,- // specifically in the MultiTermPositions- // case when some segs omit positions and- // some don't- //assertEquals(0, termPos.nextPosition());- assertEquals(false, termPos.isPayloadAvailable());- } else {- for(int i=0;i<freq;i++) {- final int position = postings.nextPosition();- assertEquals(position, termPos.nextPosition());- assertEquals(postings.hasPayload(), termPos.isPayloadAvailable());- if (postings.hasPayload()) {- BytesRef payload = postings.getPayload();- assertEquals(payload.length, termPos.getPayloadLength());- byte[] b2 = termPos.getPayload(null, 0);- assertNotNull(payload);- assertNotNull(b2);- assertTrue(equals(payload, b2));- }- }- }- }- }- }- }- }- }-- private static void testRandomSkips(Random rand, IndexReader r) throws Exception {-- TermEnum termEnum = r.terms();- Fields fields = MultiFields.getFields(r);- if (fields == null) {- return;- }- FieldsEnum fieldsEnum = fields.iterator();- boolean skipNext = false;- int[] docs2 = new int[16];- int[] freqs2 = new int[16];- while(true) {- final String field = fieldsEnum.next();- if (field == null) {- boolean result = termEnum.next();- if (result) {- System.out.println("got unexpected term=" + termEnum.term() + " termEnum=" + termEnum);- }- assertFalse(result);- break;- }- if (rand.nextInt(3) <= 1) {- // Enum the terms- //System.out.println("TEST: get terms");- TermsEnum terms = fieldsEnum.terms();- final TermPositions termPos = r.termPositions();- final TermDocs termDocs = r.termDocs();- DocsEnum docs = null;- DocsAndPositionsEnum postings = null;- while(true) {- final BytesRef termRef = terms.next();- if (termRef == null) {- break;- } else {- if (skipNext) {- skipNext = false;- } else {- assertTrue(termEnum.next());- }- Term t = termEnum.term();- assertEquals(t.field(), field);- assertEquals(t.text(), termRef.utf8ToString());- assertEquals(termEnum.docFreq(), terms.docFreq());- //allTerms.add(t);-- if (rand.nextInt(3) <= 1) {- docs = terms.docs(MultiFields.getDeletedDocs(r), docs);- assert !(docs instanceof DocsAndPositionsEnum): "docs=" + docs;- postings = terms.docsAndPositions(MultiFields.getDeletedDocs(r), postings);- final DocsEnum docsEnum;- if (postings == null) {- docsEnum = docs;- } else {- docsEnum = postings;- }- if (rand.nextBoolean()) {- // use bulk read API- termDocs.seek(t);- DocsEnum.BulkReadResult result1 = docs.getBulkResult();- int result1Count = 0;- int count2 = 0;- while(true) {- if (result1Count == 0) {- result1Count = docs.read();- }- if (count2 == 0) {- count2 = termDocs.read(docs2, freqs2);- }-- if (result1Count == 0 || count2 == 0) {- assertEquals(0, count2);- assertEquals(0, result1Count);- break;- }- final int limit = Math.min(result1Count, count2);- for(int i=0;i<limit;i++) {- assertEquals(result1.docs.ints[i], docs2[i]);- assertEquals(result1.freqs.ints[i], freqs2[i]);- }- if (result1Count > limit) {- // copy down- // TODO: in general I should not muck w/- // the int[]'s returned to me like- // this... this could mess up codecs- // that have persistent RAM storage of- // these int[]'s- System.arraycopy(result1.docs.ints, limit, result1.docs.ints, 0, result1Count-limit);- System.arraycopy(result1.freqs.ints, limit, result1.freqs.ints, 0, result1Count-limit);- }- result1Count -= limit;-- if (count2 > limit) {- // copy down- System.arraycopy(docs2, limit, docs2, 0, count2-limit);- System.arraycopy(freqs2, limit, freqs2, 0, count2-limit);- }- count2 -= limit;- }- } else {- // Enum the docs one by one- //System.out.println("TEST: get docs");- termPos.seek(t);- while(true) {- final int doc = docsEnum.nextDoc();- if (doc == DocsEnum.NO_MORE_DOCS) {- assertFalse(termPos.next());- break;- } else {- assertTrue(termPos.next());- assertEquals(termPos.doc(), doc);- assertEquals(termPos.freq(), docsEnum.freq());- //System.out.println("TEST: doc=" + doc + " freq=" + docs.freq());- if (rand.nextInt(3) <= 1) {- // enum the positions- final int freq = docsEnum.freq();- if (postings == null) {- assertEquals(1, termPos.freq());- // Old API did not always do this,- // specifically in the MultiTermPositions- // case when some segs omit positions and- // some don't- //assertEquals(0, termPos.nextPosition());- assertFalse(termPos.isPayloadAvailable());- } else {- // we have positions- for(int i=0;i<freq;i++) {- final int position = postings.nextPosition();- //System.out.println("TEST: pos=" + position);- assertEquals(position, termPos.nextPosition());- assertEquals(postings.hasPayload(), termPos.isPayloadAvailable());- if (postings.hasPayload()) {- if (rand.nextInt(3) <= 1) {- BytesRef payload = postings.getPayload();- assertEquals(payload.length, termPos.getPayloadLength());- byte[] b2 = termPos.getPayload(null, 0);- assertNotNull(payload);- assertNotNull(b2);- assertTrue(equals(payload, b2));- }- }- }- }- }- }- }- }- } else {- //System.out.println("TEST: skip docs");- }- }- }- } else {- // Skip terms for this field- termEnum = r.terms(new Term(field, "\uFFFF"));- skipNext = true;- //System.out.println("TEST: skip terms; now=" + termEnum.term());- }- }-- // seek to before first term in a field- // seek to after last term in a field- // seek to random terms- // enum docs, sometimes skipping- // enum positions, sometimes skipping payloads- }-- private static boolean equals(BytesRef b1, byte[] b2) {- if (b1.length == b2.length) {- final int end = b1.offset + b1.length;- for(int i=b1.offset;i<end;i++) {- if (b1.bytes[i] != b2[i-b1.offset]) {- return false;- }- }- return true;- } else {- return false;- }- }-- public static int nextInt(Random rand, int min, int max) {- return min + rand.nextInt(max-min);- }-- public static int nextInt(Random rand, int max) {- return rand.nextInt(max);- }-- public static String getRandomText(Random rand, int minLen, int maxLen, boolean doUnpairedSurr) {- final int len = nextInt(rand, minLen, maxLen);- char[] buffer = new char[len];-- for(int i=0;i<len;i++) {- int t = rand.nextInt(doUnpairedSurr ? 6 : 5);- if (0 == t && i < len-1) {- // Make a surrogate pair- // High surrogate- buffer[i++] = (char) nextInt(rand, 0xd800, 0xdc00);- // Low surrogate- buffer[i] = (char) nextInt(rand, 0xdc00, 0xe000);- } else if (t <= 1) {- buffer[i] = (char) nextInt(rand, 0x80);- } else if (2 == t) {- buffer[i] = (char) nextInt(rand, 0x80, 0x800);- } else if (3 == t) {- buffer[i] = (char) nextInt(rand, 0x800, 0xd800);- } else if (4 == t) {- buffer[i] = (char) nextInt(rand, 0xe000, 0xffff);- } else if (5 == t) {- // Illegal unpaired surrogate- if (rand.nextBoolean()) {- buffer[i] = (char) nextInt(rand, 0xd800, 0xdc00);- } else {- buffer[i] = (char) nextInt(rand, 0xdc00, 0xe000);- }- }- }-- return new String(buffer);- }-- private static void testRandomSeeks(Random rand, IndexReader r) throws Exception {- final int ITER = 100 * _TestUtil.getRandomMultiplier();- List<String> allFields = new ArrayList<String>();- Fields fields = MultiFields.getFields(r);- if (fields == null) {- return;- }- FieldsEnum fieldsEnum = fields.iterator();- while(true) {- String f = fieldsEnum.next();- if (f == null) {- break;- }- allFields.add(f);- }- final int fieldCount = allFields.size();- if (fieldCount == 0) {- return;- }-- final TermPositions termPositions = r.termPositions();- DocsEnum docs = null;- DocsAndPositionsEnum postings = null;-- for(int i=0;i<ITER;i++) {- // Random field:- String f = allFields.get(rand.nextInt(fieldCount));-- String text = getRandomText(rand, 1, 3, false);- final TermsEnum termsEnum = MultiFields.getFields(r).terms(f).iterator();-- final TermsEnum.SeekStatus seekStatus = termsEnum.seek(new BytesRef(text));- Term t = new Term(f, text);- //System.out.println("seek to " + t);-- final TermEnum termEnum = r.terms(t);-- if (seekStatus == TermsEnum.SeekStatus.END) {- //System.out.println("found end");- assertTrue(termEnum.term() == null || termEnum.term().field() != f);- continue;- } else if (seekStatus == TermsEnum.SeekStatus.FOUND) {- //System.out.println("found exact");- assertEquals(t, termEnum.term());- } else {- //System.out.println("found other");- assertEquals(termsEnum.term().utf8ToString(), termEnum.term().text());- }-- assertEquals(termsEnum.docFreq(), termEnum.docFreq());-- docs = termsEnum.docs(MultiFields.getDeletedDocs(r), docs);- postings = termsEnum.docsAndPositions(MultiFields.getDeletedDocs(r), postings);-- termPositions.seek(termEnum.term());-- int doc = 0;-- final DocsEnum docsEnum;- if (postings != null) {- docsEnum = postings;- } else {- docsEnum = docs;- }- for(int j=0;j<20;j++) {- final int inc = nextInt(rand, 1, Math.max(10, r.maxDoc()/15));- int newDoc1 = docsEnum.advance(doc+inc);- boolean found = termPositions.skipTo(doc+inc);- int newDoc2;-- if (newDoc1 == DocsEnum.NO_MORE_DOCS) {- assertFalse(found);- break;- } else {- assertTrue(found);- newDoc2 = termPositions.doc();- }-- assertEquals(newDoc1, newDoc2);- assertEquals(docsEnum.freq(), termPositions.freq());-- doc = newDoc1;-- if (postings == null) {- assertEquals(1, termPositions.freq());- // Old API did not always do this,- // specifically in the MultiTermPositions- // case when some segs omit positions and- // some don't- //assertEquals(0, termPositions.nextPosition());- assertFalse(termPositions.isPayloadAvailable());- } else {- for(int k=0;k<docsEnum.freq();k++) {- int pos1 = postings.nextPosition();- int pos2 = termPositions.nextPosition();- assertEquals(pos1, pos2);- assertEquals(postings.hasPayload(), termPositions.isPayloadAvailable());- if (postings.hasPayload()) {- BytesRef b1 = postings.getPayload();- assertEquals(b1.length, termPositions.getPayloadLength());- byte[] b2 = termPositions.getPayload(null, 0);- assertNotNull(b1);- assertNotNull(b2);- assertTrue(equals(b1, b2));- }- }- }- }- }- }-- public static void main(String[] args) throws Exception {- //Directory dir = FSDirectory.open(new File("/x/lucene/wiki.5M/index"));- Directory dir = FSDirectory.open(new File("/x/lucene/flex.wiki.1M/index"));- verifyFlexVsPreFlex(new Random(), dir);- dir.close();- }-}\ No newline at end of filediff --git a/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java b/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.javaindex 01085443256..a544a984f64 100644--- a/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java+++ b/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java@@ -24,7 +24,6 @@ import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Arrays;-import java.util.Random;import java.util.Enumeration;import java.util.List;import java.util.zip.ZipEntry;@@ -129,20 +128,15 @@ public class TestBackwardsCompatibility extends LuceneTestCase {};public void testOptimizeOldIndex() throws Exception {- Random rand = newRandom();-for(int i=0;i<oldNames.length;i++) {unzip(getDataFile("index." + oldNames[i] + ".zip"), oldNames[i]);String fullPath = fullDir(oldNames[i]);Directory dir = FSDirectory.open(new File(fullPath));- FlexTestUtil.verifyFlexVsPreFlex(rand, dir);-IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));w.optimize();- FlexTestUtil.verifyFlexVsPreFlex(rand, w);w.close();_TestUtil.checkIndex(dir);diff --git a/lucene/src/test/org/apache/lucene/index/TestDirectoryReader.java b/lucene/src/test/org/apache/lucene/index/TestDirectoryReader.javaindex 836b3dbfcf1..d347bcd67ea 100644--- a/lucene/src/test/org/apache/lucene/index/TestDirectoryReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestDirectoryReader.java@@ -25,6 +25,7 @@ import org.apache.lucene.document.Field;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.util.BytesRef;import java.io.IOException;@@ -158,35 +159,29 @@ public class TestDirectoryReader extends LuceneTestCase {MultiReader mr3 = new MultiReader(readers2);// test mixing up TermDocs and TermEnums from different readers.- TermDocs td2 = mr2.termDocs();- TermEnum te3 = mr3.terms(new Term("body","wow"));- td2.seek(te3);+ TermsEnum te2 = MultiFields.getTerms(mr2, "body").iterator();+ te2.seek(new BytesRef("wow"));+ DocsEnum td = MultiFields.getTermDocsEnum(mr2,+ MultiFields.getDeletedDocs(mr2),+ "body",+ te2.term());++ TermsEnum te3 = MultiFields.getTerms(mr3, "body").iterator();+ te3.seek(new BytesRef("wow"));+ td = te3.docs(MultiFields.getDeletedDocs(mr3),+ td);+int ret = 0;// This should blow up if we forget to check that the TermEnum is from the same// reader as the TermDocs.- while (td2.next()) ret += td2.doc();- td2.close();- te3.close();+ while (td.nextDoc() != td.NO_MORE_DOCS) ret += td.docID();// really a dummy assert to ensure that we got some docs and to ensure that// nothing is optimized out.assertTrue(ret > 0);}- public void testAllTermDocs() throws IOException {- IndexReader reader = openReader();- int NUM_DOCS = 2;- TermDocs td = reader.termDocs(null);- for(int i=0;i<NUM_DOCS;i++) {- assertTrue(td.next());- assertEquals(i, td.doc());- assertEquals(1, td.freq());- }- td.close();- reader.close();- }-private void addDoc(RAMDirectory ramDir1, String s, boolean create) throws IOException {IndexWriter iw = new IndexWriter(ramDir1, new IndexWriterConfig(TEST_VERSION_CURRENT,diff --git a/lucene/src/test/org/apache/lucene/index/TestDoc.java b/lucene/src/test/org/apache/lucene/index/TestDoc.javaindex 84437dc32ab..779d74b21ba 100644--- a/lucene/src/test/org/apache/lucene/index/TestDoc.java+++ b/lucene/src/test/org/apache/lucene/index/TestDoc.java@@ -213,15 +213,19 @@ public class TestDoc extends LuceneTestCase {for (int i = 0; i < reader.numDocs(); i++)out.println(reader.document(i));- TermEnum tis = reader.terms();- while (tis.next()) {- out.print(tis.term());- out.println(" DF=" + tis.docFreq());+ FieldsEnum fis = reader.fields().iterator();+ String field = fis.next();+ while(field != null) {+ TermsEnum tis = fis.terms();+ while(tis.next() != null) {- TermPositions positions = reader.termPositions(tis.term());- try {- while (positions.next()) {- out.print(" doc=" + positions.doc());+ out.print(" term=" + field + ":" + tis.term());+ out.println(" DF=" + tis.docFreq());++ DocsAndPositionsEnum positions = tis.docsAndPositions(reader.getDeletedDocs(), null);++ while (positions.nextDoc() != positions.NO_MORE_DOCS) {+ out.print(" doc=" + positions.docID());out.print(" TF=" + positions.freq());out.print(" pos=");out.print(positions.nextPosition());@@ -229,11 +233,9 @@ public class TestDoc extends LuceneTestCase {out.print("," + positions.nextPosition());out.println("");}- } finally {- positions.close();}+ field = fis.next();}- tis.close();reader.close();}}diff --git a/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.java b/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.javaindex ad292b2ffdb..da18c63605b 100644--- a/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.java+++ b/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.java@@ -38,6 +38,7 @@ import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util._TestUtil;+import org.apache.lucene.util.BytesRef;public class TestDocumentWriter extends LuceneTestCase {private RAMDirectory dir;@@ -128,8 +129,9 @@ public class TestDocumentWriter extends LuceneTestCase {writer.close();SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);- TermPositions termPositions = reader.termPositions(new Term("repeated", "repeated"));- assertTrue(termPositions.next());+ DocsAndPositionsEnum termPositions = MultiFields.getTermPositionsEnum(reader, MultiFields.getDeletedDocs(reader),+ "repeated", new BytesRef("repeated"));+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);int freq = termPositions.freq();assertEquals(2, freq);assertEquals(0, termPositions.nextPosition());@@ -190,16 +192,16 @@ public class TestDocumentWriter extends LuceneTestCase {writer.close();SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);- TermPositions termPositions = reader.termPositions(new Term("f1", "a"));- assertTrue(termPositions.next());+ DocsAndPositionsEnum termPositions = reader.fields().terms("f1").docsAndPositions(reader.getDeletedDocs(), new BytesRef("a"), null);+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);int freq = termPositions.freq();assertEquals(3, freq);assertEquals(0, termPositions.nextPosition());- assertEquals(true, termPositions.isPayloadAvailable());+ assertEquals(true, termPositions.hasPayload());assertEquals(6, termPositions.nextPosition());- assertEquals(false, termPositions.isPayloadAvailable());+ assertEquals(false, termPositions.hasPayload());assertEquals(7, termPositions.nextPosition());- assertEquals(false, termPositions.isPayloadAvailable());+ assertEquals(false, termPositions.hasPayload());}@@ -233,19 +235,19 @@ public class TestDocumentWriter extends LuceneTestCase {writer.close();SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);- TermPositions termPositions = reader.termPositions(new Term("preanalyzed", "term1"));- assertTrue(termPositions.next());+ DocsAndPositionsEnum termPositions = reader.fields().terms("preanalyzed").docsAndPositions(reader.getDeletedDocs(), new BytesRef("term1"), null);+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(1, termPositions.freq());assertEquals(0, termPositions.nextPosition());- termPositions.seek(new Term("preanalyzed", "term2"));- assertTrue(termPositions.next());+ termPositions = reader.fields().terms("preanalyzed").docsAndPositions(reader.getDeletedDocs(), new BytesRef("term2"), null);+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(2, termPositions.freq());assertEquals(1, termPositions.nextPosition());assertEquals(3, termPositions.nextPosition());- termPositions.seek(new Term("preanalyzed", "term3"));- assertTrue(termPositions.next());+ termPositions = reader.fields().terms("preanalyzed").docsAndPositions(reader.getDeletedDocs(), new BytesRef("term3"), null);+ assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(1, termPositions.freq());assertEquals(2, termPositions.nextPosition());diff --git a/lucene/src/test/org/apache/lucene/index/TestFilterIndexReader.java b/lucene/src/test/org/apache/lucene/index/TestFilterIndexReader.javaindex 0246b333dab..a722c5a22b8 100644--- a/lucene/src/test/org/apache/lucene/index/TestFilterIndexReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestFilterIndexReader.java@@ -159,26 +159,19 @@ public class TestFilterIndexReader extends LuceneTestCase {assertTrue(reader.isOptimized());- TermEnum terms = reader.terms();- while (terms.next()) {- assertTrue(terms.term().text().indexOf('e') != -1);+ TermsEnum terms = MultiFields.getTerms(reader, "default").iterator();+ while (terms.next() != null) {+ assertTrue(terms.term().utf8ToString().indexOf('e') != -1);}- terms.close();- TermPositions positions = reader.termPositions(new Term("default", "one"));- while (positions.next()) {- assertTrue((positions.doc() % 2) == 1);+ assertEquals(TermsEnum.SeekStatus.FOUND, terms.seek(new BytesRef("one")));++ DocsAndPositionsEnum positions = terms.docsAndPositions(MultiFields.getDeletedDocs(reader),+ null);+ while (positions.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ assertTrue((positions.docID() % 2) == 1);}- int NUM_DOCS = 3;-- TermDocs td = reader.termDocs(null);- for(int i=0;i<NUM_DOCS;i++) {- assertTrue(td.next());- assertEquals(i, td.doc());- assertEquals(1, td.freq());- }- td.close();reader.close();directory.close();}diff --git a/lucene/src/test/org/apache/lucene/index/TestFlex.java b/lucene/src/test/org/apache/lucene/index/TestFlex.javaindex 65a31ce2875..cd114a0aa99 100644--- a/lucene/src/test/org/apache/lucene/index/TestFlex.java+++ b/lucene/src/test/org/apache/lucene/index/TestFlex.java@@ -52,13 +52,9 @@ public class TestFlex extends LuceneTestCase {}IndexReader r = w.getReader();- TermEnum terms = r.terms(new Term("field3", "bbb"));- // pre-flex API should seek to the next field- assertNotNull(terms.term());- assertEquals("field4", terms.term().field());- terms = r.terms(new Term("field5", "abc"));- assertNull(terms.term());+ TermsEnum terms = MultiFields.getTerms(r, "field3").iterator();+ assertEquals(TermsEnum.SeekStatus.END, terms.seek(new BytesRef("abc")));r.close();}diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexReader.java b/lucene/src/test/org/apache/lucene/index/TestIndexReader.javaindex dc0cdb02758..29641b0910a 100644--- a/lucene/src/test/org/apache/lucene/index/TestIndexReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReader.java@@ -55,6 +55,8 @@ import org.apache.lucene.store.NoSuchDirectoryException;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util._TestUtil;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.Bits;public class TestIndexReader extends LuceneTestCase{@@ -287,22 +289,17 @@ public class TestIndexReader extends LuceneTestCaseint expected)throws IOException{- TermDocs tdocs = null;-- try {- tdocs = reader.termDocs(term);- assertNotNull(msg + ", null TermDocs", tdocs);- int count = 0;- while(tdocs.next()) {- count++;- }- assertEquals(msg + ", count mismatch", expected, count);-- } finally {- if (tdocs != null)- tdocs.close();+ DocsEnum tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ term.field(),+ new BytesRef(term.text()));+ int count = 0;+ if (tdocs != null) {+ while(tdocs.nextDoc()!= tdocs.NO_MORE_DOCS) {+ count++;+ }}-+ assertEquals(msg + ", count mismatch", expected, count);}public void testBasicDelete() throws IOException {@@ -1348,21 +1345,26 @@ public class TestIndexReader extends LuceneTestCase}// check dictionary and posting lists- TermEnum enum1 = index1.terms();- TermEnum enum2 = index2.terms();- TermPositions tp1 = index1.termPositions();- TermPositions tp2 = index2.termPositions();- while(enum1.next()) {- assertTrue(enum2.next());- assertEquals("Different term in dictionary.", enum1.term(), enum2.term());- tp1.seek(enum1.term());- tp2.seek(enum1.term());- while(tp1.next()) {- assertTrue(tp2.next());- assertEquals("Different doc id in postinglist of term " + enum1.term() + ".", tp1.doc(), tp2.doc());- assertEquals("Different term frequence in postinglist of term " + enum1.term() + ".", tp1.freq(), tp2.freq());- for (int i = 0; i < tp1.freq(); i++) {- assertEquals("Different positions in postinglist of term " + enum1.term() + ".", tp1.nextPosition(), tp2.nextPosition());+ FieldsEnum fenum1 = MultiFields.getFields(index1).iterator();+ FieldsEnum fenum2 = MultiFields.getFields(index1).iterator();+ String field1 = null;+ Bits delDocs = MultiFields.getDeletedDocs(index1);+ while((field1=fenum1.next()) != null) {+ assertEquals("Different fields", field1, fenum2.next());+ TermsEnum enum1 = fenum1.terms();+ TermsEnum enum2 = fenum2.terms();+ while(enum1.next() != null) {+ assertEquals("Different terms", enum1.term(), enum2.next());+ DocsAndPositionsEnum tp1 = enum1.docsAndPositions(delDocs, null);+ DocsAndPositionsEnum tp2 = enum2.docsAndPositions(delDocs, null);++ while(tp1.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ assertTrue(tp2.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals("Different doc id in postinglist of term " + enum1.term() + ".", tp1.docID(), tp2.docID());+ assertEquals("Different term frequence in postinglist of term " + enum1.term() + ".", tp1.freq(), tp2.freq());+ for (int i = 0; i < tp1.freq(); i++) {+ assertEquals("Different positions in postinglist of term " + enum1.term() + ".", tp1.nextPosition(), tp2.nextPosition());+ }}}}diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java b/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.javaindex 3635230f481..b3771943dab 100644--- a/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java@@ -863,8 +863,6 @@ public class TestIndexReaderReopen extends LuceneTestCase {assertReaderClosed(reader, true, true);assertReaderClosed(firstReader, true, true);- FlexTestUtil.verifyFlexVsPreFlex(rnd, dir);-dir.close();}diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.javaindex f25268b7093..0cc3ec314b2 100644--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java@@ -1379,8 +1379,11 @@ public class TestIndexWriter extends LuceneTestCase {assertEquals(1, reader.numDocs());Term t = new Term("field", "a");assertEquals(1, reader.docFreq(t));- TermDocs td = reader.termDocs(t);- td.next();+ DocsEnum td = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "field",+ new BytesRef("a"));+ td.nextDoc();assertEquals(128*1024, td.freq());reader.close();dir.close();@@ -1701,9 +1704,13 @@ public class TestIndexWriter extends LuceneTestCase {// Make sure the doc that hit the exception was marked// as deleted:- TermDocs tdocs = reader.termDocs(t);+ DocsEnum tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ t.field(),+ new BytesRef(t.text()));+int count = 0;- while(tdocs.next()) {+ while(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {count++;}assertEquals(2, count);@@ -2244,9 +2251,12 @@ public class TestIndexWriter extends LuceneTestCase {// Quick test to make sure index is not corrupt:IndexReader reader = IndexReader.open(dir, true);- TermDocs tdocs = reader.termDocs(new Term("field", "aaa"));+ DocsEnum tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "field",+ new BytesRef("aaa"));int count = 0;- while(tdocs.next()) {+ while(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {count++;}assertTrue(count > 0);@@ -3454,8 +3464,13 @@ public class TestIndexWriter extends LuceneTestCase {Query q = new SpanTermQuery(new Term("field", "a"));hits = s.search(q, null, 1000).scoreDocs;assertEquals(1, hits.length);- TermPositions tps = s.getIndexReader().termPositions(new Term("field", "a"));- assertTrue(tps.next());++ DocsAndPositionsEnum tps = MultiFields.getTermPositionsEnum(s.getIndexReader(),+ MultiFields.getDeletedDocs(s.getIndexReader()),+ "field",+ new BytesRef("a"));++ assertTrue(tps.nextDoc() != DocsEnum.NO_MORE_DOCS);assertEquals(1, tps.freq());assertEquals(0, tps.nextPosition());w.close();@@ -4465,12 +4480,12 @@ public class TestIndexWriter extends LuceneTestCase {// test that the terms were indexed.- assertTrue(ir.termDocs(new Term("binary","doc1field1")).next());- assertTrue(ir.termDocs(new Term("binary","doc2field1")).next());- assertTrue(ir.termDocs(new Term("binary","doc3field1")).next());- assertTrue(ir.termDocs(new Term("string","doc1field2")).next());- assertTrue(ir.termDocs(new Term("string","doc2field2")).next());- assertTrue(ir.termDocs(new Term("string","doc3field2")).next());+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "binary", new BytesRef("doc1field1")).nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "binary", new BytesRef("doc2field1")).nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "binary", new BytesRef("doc3field1")).nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "string", new BytesRef("doc1field2")).nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "string", new BytesRef("doc2field2")).nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(MultiFields.getTermDocsEnum(ir, null, "string", new BytesRef("doc3field2")).nextDoc() != DocsEnum.NO_MORE_DOCS);ir.close();dir.close();diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexWriterReader.java b/lucene/src/test/org/apache/lucene/index/TestIndexWriterReader.javaindex 2b84bc72522..e49d5c0f05d 100644--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterReader.java@@ -38,6 +38,7 @@ import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.store.AlreadyClosedException;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util._TestUtil;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.ThreadInterruptedException;public class TestIndexWriterReader extends LuceneTestCase {@@ -63,12 +64,16 @@ public class TestIndexWriterReader extends LuceneTestCase {public static int count(Term t, IndexReader r) throws IOException {int count = 0;- TermDocs td = r.termDocs(t);- while (td.next()) {- td.doc();- count++;+ DocsEnum td = MultiFields.getTermDocsEnum(r,+ MultiFields.getDeletedDocs(r),+ t.field(), new BytesRef(t.text()));++ if (td != null) {+ while (td.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ td.docID();+ count++;+ }}- td.close();return count;}diff --git a/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java b/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.javaindex 68b6423e8e2..4c15e0834ad 100755--- a/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java+++ b/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java@@ -30,6 +30,7 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;/*** Tests lazy skipping on the proximity file.@@ -127,17 +128,26 @@ public class TestLazyProxSkipping extends LuceneTestCase {writer.close();IndexReader reader = IndexReader.open(directory, true);- TermPositions tp = reader.termPositions();- tp.seek(new Term(this.field, "b"));++ DocsAndPositionsEnum tp = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ this.field,+ new BytesRef("b"));+for (int i = 0; i < 10; i++) {- tp.next();- assertEquals(tp.doc(), i);+ tp.nextDoc();+ assertEquals(tp.docID(), i);assertEquals(tp.nextPosition(), 1);}- tp.seek(new Term(this.field, "a"));++ tp = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ this.field,+ new BytesRef("a"));+for (int i = 0; i < 10; i++) {- tp.next();- assertEquals(tp.doc(), i);+ tp.nextDoc();+ assertEquals(tp.docID(), i);assertEquals(tp.nextPosition(), 0);}diff --git a/lucene/src/test/org/apache/lucene/index/TestMultiLevelSkipList.java b/lucene/src/test/org/apache/lucene/index/TestMultiLevelSkipList.javaindex 74d011406ba..08585991239 100644--- a/lucene/src/test/org/apache/lucene/index/TestMultiLevelSkipList.java+++ b/lucene/src/test/org/apache/lucene/index/TestMultiLevelSkipList.java@@ -21,7 +21,6 @@ import java.io.IOException;import java.io.Reader;import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.analysis.MockTokenizer;import org.apache.lucene.analysis.TokenFilter;import org.apache.lucene.analysis.TokenStream;@@ -34,6 +33,7 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;/*** This testcase tests whether multi-level skipping is being used@@ -68,11 +68,12 @@ public class TestMultiLevelSkipList extends LuceneTestCase {writer.close();IndexReader reader = SegmentReader.getOnlySegmentReader(dir);- TermPositions tp = reader.termPositions();for (int i = 0; i < 2; i++) {counter = 0;- tp.seek(term);+ DocsAndPositionsEnum tp = reader.termPositionsEnum(reader.getDeletedDocs(),+ term.field(),+ new BytesRef(term.text()));checkSkipTo(tp, 14, 185); // no skipscheckSkipTo(tp, 17, 190); // one skip on level 0@@ -84,18 +85,18 @@ public class TestMultiLevelSkipList extends LuceneTestCase {}}- public void checkSkipTo(TermPositions tp, int target, int maxCounter) throws IOException {- tp.skipTo(target);+ public void checkSkipTo(DocsAndPositionsEnum tp, int target, int maxCounter) throws IOException {+ tp.advance(target);if (maxCounter < counter) {fail("Too many bytes read: " + counter);}- assertEquals("Wrong document " + tp.doc() + " after skipTo target " + target, target, tp.doc());+ assertEquals("Wrong document " + tp.docID() + " after skipTo target " + target, target, tp.docID());assertEquals("Frequency is not 1: " + tp.freq(), 1,tp.freq());tp.nextPosition();- byte[] b = new byte[1];- tp.getPayload(b, 0);- assertEquals("Wrong payload for the target " + target + ": " + b[0], (byte) target, b[0]);+ BytesRef b = tp.getPayload();+ assertEquals(1, b.length);+ assertEquals("Wrong payload for the target " + target + ": " + b.bytes[b.offset], (byte) target, b.bytes[b.offset]);}private static class PayloadAnalyzer extends Analyzer {diff --git a/lucene/src/test/org/apache/lucene/index/TestOmitTf.java b/lucene/src/test/org/apache/lucene/index/TestOmitTf.javaindex 06fb2d6397b..cc6d321beaa 100644--- a/lucene/src/test/org/apache/lucene/index/TestOmitTf.java+++ b/lucene/src/test/org/apache/lucene/index/TestOmitTf.java@@ -19,7 +19,6 @@ package org.apache.lucene.index;import java.io.IOException;import java.util.Collection;-import java.util.Random;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util._TestUtil;@@ -87,10 +86,7 @@ public class TestOmitTf extends LuceneTestCase {f2.setOmitTermFreqAndPositions(false);d.add(f2);- Random rnd = newRandom();-writer.addDocument(d);- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);// force mergewriter.optimize();@@ -98,8 +94,6 @@ public class TestOmitTf extends LuceneTestCase {writer.close();_TestUtil.checkIndex(ram);- FlexTestUtil.verifyFlexVsPreFlex(rnd, ram);-SegmentReader reader = SegmentReader.getOnlySegmentReader(ram);FieldInfos fi = reader.fieldInfos();assertTrue("OmitTermFreqAndPositions field bit should be set.", fi.fieldInfo("f1").omitTermFreqAndPositions);@@ -145,12 +139,8 @@ public class TestOmitTf extends LuceneTestCase {for(int i=0;i<30;i++)writer.addDocument(d);- Random rnd = newRandom();- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);-// force mergewriter.optimize();- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);// flushwriter.close();diff --git a/lucene/src/test/org/apache/lucene/index/TestParallelReader.java b/lucene/src/test/org/apache/lucene/index/TestParallelReader.javaindex 7570c1f1255..ab96103418f 100644--- a/lucene/src/test/org/apache/lucene/index/TestParallelReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestParallelReader.java@@ -195,26 +195,6 @@ public class TestParallelReader extends LuceneTestCase {}- public void testAllTermDocs() throws IOException {- Directory dir1 = getDir1();- Directory dir2 = getDir2();- ParallelReader pr = new ParallelReader();- pr.add(IndexReader.open(dir1, false));- pr.add(IndexReader.open(dir2, false));- int NUM_DOCS = 2;- TermDocs td = pr.termDocs(null);- for(int i=0;i<NUM_DOCS;i++) {- assertTrue(td.next());- assertEquals(i, td.doc());- assertEquals(1, td.freq());- }- td.close();- pr.close();- dir1.close();- dir2.close();- }--private void queryTest(Query query) throws IOException {ScoreDoc[] parallelHits = parallel.search(query, null, 1000).scoreDocs;ScoreDoc[] singleHits = single.search(query, null, 1000).scoreDocs;diff --git a/lucene/src/test/org/apache/lucene/index/TestParallelTermEnum.java b/lucene/src/test/org/apache/lucene/index/TestParallelTermEnum.javaindex ad0f402a145..c81a0a65c8a 100755--- a/lucene/src/test/org/apache/lucene/index/TestParallelTermEnum.java+++ b/lucene/src/test/org/apache/lucene/index/TestParallelTermEnum.java@@ -26,6 +26,7 @@ import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.Index;import org.apache.lucene.document.Field.Store;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.util.Bits;public class TestParallelTermEnum extends LuceneTestCase {private IndexReader ir1;@@ -77,105 +78,123 @@ public class TestParallelTermEnum extends LuceneTestCase {pr.add(ir1);pr.add(ir2);- TermDocs td = pr.termDocs();-- TermEnum te = pr.terms();- assertTrue(te.next());- assertEquals("field1:brown", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field1:fox", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field1:jumps", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field1:quick", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field1:the", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field2:brown", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field2:fox", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field2:jumps", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field2:quick", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field2:the", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:dog", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:fox", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:jumps", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:lazy", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:over", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertTrue(te.next());- assertEquals("field3:the", te.term().toString());- td.seek(te.term());- assertTrue(td.next());- assertEquals(0, td.doc());- assertFalse(td.next());- assertFalse(te.next());+ Bits delDocs = pr.getDeletedDocs();++ FieldsEnum fe = pr.fields().iterator();++ String f = fe.next();+ assertEquals("field0", f);+ f = fe.next();+ assertEquals("field1", f);++ TermsEnum te = fe.terms();++ assertEquals("brown", te.next().utf8ToString());+ DocsEnum td = te.docs(delDocs, null);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("fox", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("jumps", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("quick", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("the", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertNull(te.next());+ f = fe.next();+ assertEquals("field2", f);+ te = fe.terms();++ assertEquals("brown", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("fox", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("jumps", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("quick", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("the", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertNull(te.next());+ f = fe.next();+ assertEquals("field3", f);+ te = fe.terms();++ assertEquals("dog", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("fox", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("jumps", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("lazy", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("over", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertEquals("the", te.next().utf8ToString());+ td = te.docs(delDocs, td);+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, td.docID());+ assertEquals(td.nextDoc(), DocsEnum.NO_MORE_DOCS);++ assertNull(te.next());}}diff --git a/lucene/src/test/org/apache/lucene/index/TestPayloads.java b/lucene/src/test/org/apache/lucene/index/TestPayloads.javaindex 3f972347c01..d0ce816d63f 100644--- a/lucene/src/test/org/apache/lucene/index/TestPayloads.java+++ b/lucene/src/test/org/apache/lucene/index/TestPayloads.java@@ -41,6 +41,7 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.Bits;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.UnicodeUtil;import org.apache.lucene.util._TestUtil;@@ -141,8 +142,6 @@ public class TestPayloads extends LuceneTestCase {analyzer.setPayloadData("f3", "somedata".getBytes(), 0, 3);writer.addDocument(d);- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);-// force mergewriter.optimize();// flush@@ -154,7 +153,6 @@ public class TestPayloads extends LuceneTestCase {assertTrue("Payload field bit should be set.", fi.fieldInfo("f2").storePayloads);assertTrue("Payload field bit should be set.", fi.fieldInfo("f3").storePayloads);reader.close();- FlexTestUtil.verifyFlexVsPreFlex(rnd, ram);}// Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory@@ -220,9 +218,7 @@ public class TestPayloads extends LuceneTestCase {writer.addDocument(d);}- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);writer.optimize();- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);// flushwriter.close();@@ -232,83 +228,87 @@ public class TestPayloads extends LuceneTestCase {* first we test if all payloads are stored correctly*/IndexReader reader = IndexReader.open(dir, true);-+byte[] verifyPayloadData = new byte[payloadDataLength];offset = 0;- TermPositions[] tps = new TermPositions[numTerms];+ DocsAndPositionsEnum[] tps = new DocsAndPositionsEnum[numTerms];for (int i = 0; i < numTerms; i++) {- tps[i] = reader.termPositions(terms[i]);+ tps[i] = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ terms[i].field(),+ new BytesRef(terms[i].text()));}- while (tps[0].next()) {+ while (tps[0].nextDoc() != DocsEnum.NO_MORE_DOCS) {for (int i = 1; i < numTerms; i++) {- tps[i].next();+ tps[i].nextDoc();}int freq = tps[0].freq();for (int i = 0; i < freq; i++) {for (int j = 0; j < numTerms; j++) {tps[j].nextPosition();- tps[j].getPayload(verifyPayloadData, offset);- offset += tps[j].getPayloadLength();+ BytesRef br = tps[j].getPayload();+ System.arraycopy(br.bytes, br.offset, verifyPayloadData, offset, br.length);+ offset += br.length;}}}- for (int i = 0; i < numTerms; i++) {- tps[i].close();- }-assertByteArrayEquals(payloadData, verifyPayloadData);/** test lazy skipping*/- TermPositions tp = reader.termPositions(terms[0]);- tp.next();+ DocsAndPositionsEnum tp = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ terms[0].field(),+ new BytesRef(terms[0].text()));+ tp.nextDoc();tp.nextPosition();// NOTE: prior rev of this test was failing to first// call next here:- tp.next();+ tp.nextDoc();// now we don't read this payloadtp.nextPosition();- assertEquals("Wrong payload length.", 1, tp.getPayloadLength());- byte[] payload = tp.getPayload(null, 0);- assertEquals(payload[0], payloadData[numTerms]);- // NOTE: prior rev of this test was failing to first- // call next here:- tp.next();+ BytesRef payload = tp.getPayload();+ assertEquals("Wrong payload length.", 1, payload.length);+ assertEquals(payload.bytes[payload.offset], payloadData[numTerms]);+ tp.nextDoc();tp.nextPosition();// we don't read this payload and skip to a different document- tp.skipTo(5);+ tp.advance(5);tp.nextPosition();- assertEquals("Wrong payload length.", 1, tp.getPayloadLength());- payload = tp.getPayload(null, 0);- assertEquals(payload[0], payloadData[5 * numTerms]);+ payload = tp.getPayload();+ assertEquals("Wrong payload length.", 1, payload.length);+ assertEquals(payload.bytes[payload.offset], payloadData[5 * numTerms]);/** Test different lengths at skip points*/- tp.seek(terms[1]);- tp.next();+ tp = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ terms[1].field(),+ new BytesRef(terms[1].text()));+ tp.nextDoc();tp.nextPosition();- assertEquals("Wrong payload length.", 1, tp.getPayloadLength());- tp.skipTo(skipInterval - 1);+ assertEquals("Wrong payload length.", 1, tp.getPayload().length);+ tp.advance(skipInterval - 1);tp.nextPosition();- assertEquals("Wrong payload length.", 1, tp.getPayloadLength());- tp.skipTo(2 * skipInterval - 1);+ assertEquals("Wrong payload length.", 1, tp.getPayload().length);+ tp.advance(2 * skipInterval - 1);tp.nextPosition();- assertEquals("Wrong payload length.", 1, tp.getPayloadLength());- tp.skipTo(3 * skipInterval - 1);+ assertEquals("Wrong payload length.", 1, tp.getPayload().length);+ tp.advance(3 * skipInterval - 1);tp.nextPosition();- assertEquals("Wrong payload length.", 3 * skipInterval - 2 * numDocs - 1, tp.getPayloadLength());+ assertEquals("Wrong payload length.", 3 * skipInterval - 2 * numDocs - 1, tp.getPayload().length);/** Test multiple call of getPayload()*/- tp.getPayload(null, 0);+ assertFalse(tp.hasPayload());reader.close();@@ -326,23 +326,24 @@ public class TestPayloads extends LuceneTestCase {writer.addDocument(d);- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);writer.optimize();- FlexTestUtil.verifyFlexVsPreFlex(rnd, writer);// flushwriter.close();reader = IndexReader.open(dir, true);- tp = reader.termPositions(new Term(fieldName, singleTerm));- tp.next();+ tp = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ fieldName,+ new BytesRef(singleTerm));+ tp.nextDoc();tp.nextPosition();-- verifyPayloadData = new byte[tp.getPayloadLength()];- tp.getPayload(verifyPayloadData, 0);++ BytesRef br = tp.getPayload();+ verifyPayloadData = new byte[br.length];byte[] portion = new byte[1500];System.arraycopy(payloadData, 100, portion, 0, 1500);- assertByteArrayEquals(portion, verifyPayloadData);+ assertByteArrayEquals(portion, br.bytes, br.offset, br.length);reader.close();}@@ -389,6 +390,18 @@ public class TestPayloads extends LuceneTestCase {}}+ void assertByteArrayEquals(byte[] b1, byte[] b2, int b2offset, int b2length) {+ if (b1.length != b2length) {+ fail("Byte arrays have different lengths: " + b1.length + ", " + b2length);+ }++ for (int i = 0; i < b1.length; i++) {+ if (b1[i] != b2[b2offset+i]) {+ fail("Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[b2offset+i]);+ }+ }+ }+/*** This Analyzer uses an WhitespaceTokenizer and PayloadFilter.@@ -506,19 +519,20 @@ public class TestPayloads extends LuceneTestCase {}writer.close();IndexReader reader = IndexReader.open(dir, true);- TermEnum terms = reader.terms();- while (terms.next()) {- TermPositions tp = reader.termPositions(terms.term());- while(tp.next()) {- int freq = tp.freq();- for (int i = 0; i < freq; i++) {- tp.nextPosition();- assertEquals(pool.bytesToString(tp.getPayload(new byte[5], 0)), terms.term().text);- }+ TermsEnum terms = MultiFields.getFields(reader).terms(field).iterator();+ Bits delDocs = MultiFields.getDeletedDocs(reader);+ DocsAndPositionsEnum tp = null;+ while (terms.next() != null) {+ String termText = terms.term().utf8ToString();+ tp = terms.docsAndPositions(delDocs, tp);+ while(tp.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ int freq = tp.freq();+ for (int i = 0; i < freq; i++) {+ tp.nextPosition();+ assertEquals(tp.getPayload().utf8ToString(), termText);}- tp.close();+ }}- terms.close();reader.close();assertEquals(pool.size(), numThreads);diff --git a/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java b/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.javaindex d7f8744a653..4a53073d3fc 100644--- a/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java@@ -23,6 +23,7 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.document.Document;import org.apache.lucene.index.codecs.CodecProvider;+import org.apache.lucene.util.BytesRef;import java.io.IOException;import java.util.Collection;@@ -85,9 +86,12 @@ public class TestSegmentMerger extends LuceneTestCase {assertTrue(newDoc2 != null);assertTrue(DocHelper.numFields(newDoc2) == DocHelper.numFields(doc2) - DocHelper.unstored.size());- TermDocs termDocs = mergedReader.termDocs(new Term(DocHelper.TEXT_FIELD_2_KEY, "field"));+ DocsEnum termDocs = MultiFields.getTermDocsEnum(mergedReader,+ MultiFields.getDeletedDocs(mergedReader),+ DocHelper.TEXT_FIELD_2_KEY,+ new BytesRef("field"));assertTrue(termDocs != null);- assertTrue(termDocs.next() == true);+ assertTrue(termDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);Collection<String> stored = mergedReader.getFieldNames(IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR);assertTrue(stored != null);diff --git a/lucene/src/test/org/apache/lucene/index/TestSegmentReader.java b/lucene/src/test/org/apache/lucene/index/TestSegmentReader.javaindex 3a855f16541..05398171945 100644--- a/lucene/src/test/org/apache/lucene/index/TestSegmentReader.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentReader.java@@ -23,6 +23,7 @@ import java.util.Iterator;import java.util.List;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.document.Document;import org.apache.lucene.document.Fieldable;@@ -113,33 +114,40 @@ public class TestSegmentReader extends LuceneTestCase {}public void testTerms() throws IOException {- TermEnum terms = reader.terms();- assertTrue(terms != null);- while (terms.next() == true)- {- Term term = terms.term();- assertTrue(term != null);- //System.out.println("Term: " + term);- String fieldValue = (String)DocHelper.nameValues.get(term.field());- assertTrue(fieldValue.indexOf(term.text()) != -1);+ FieldsEnum fields = MultiFields.getFields(reader).iterator();+ String field;+ while((field = fields.next()) != null) {+ TermsEnum terms = fields.terms();+ while(terms.next() != null) {+ BytesRef term = terms.term();+ assertTrue(term != null);+ String fieldValue = (String) DocHelper.nameValues.get(field);+ assertTrue(fieldValue.indexOf(term.utf8ToString()) != -1);+ }}- TermDocs termDocs = reader.termDocs();- assertTrue(termDocs != null);- termDocs.seek(new Term(DocHelper.TEXT_FIELD_1_KEY, "field"));- assertTrue(termDocs.next() == true);+ DocsEnum termDocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ DocHelper.TEXT_FIELD_1_KEY,+ new BytesRef("field"));+ assertTrue(termDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);++ termDocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ DocHelper.NO_NORMS_KEY,+ new BytesRef(DocHelper.NO_NORMS_TEXT));- termDocs.seek(new Term(DocHelper.NO_NORMS_KEY, DocHelper.NO_NORMS_TEXT));- assertTrue(termDocs.next() == true);+ assertTrue(termDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);- TermPositions positions = reader.termPositions();- assertTrue(positions != null);- positions.seek(new Term(DocHelper.TEXT_FIELD_1_KEY, "field"));+ DocsAndPositionsEnum positions = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ DocHelper.TEXT_FIELD_1_KEY,+ new BytesRef("field"));// NOTE: prior rev of this test was failing to first// call next here:- assertTrue(positions.next());- assertTrue(positions.doc() == 0);+ assertTrue(positions.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertTrue(positions.docID() == 0);assertTrue(positions.nextPosition() >= 0);}diff --git a/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.java b/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.javaindex 90102f0aeba..3440e0660d9 100644--- a/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.java@@ -24,6 +24,7 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.lucene.util.BytesRef;import java.io.IOException;@@ -56,11 +57,12 @@ public class TestSegmentTermDocs extends LuceneTestCase {SegmentReader reader = SegmentReader.get(true, info, indexDivisor);assertTrue(reader != null);assertEquals(indexDivisor, reader.getTermInfosIndexDivisor());- TermDocs termDocs = reader.termDocs();- assertTrue(termDocs != null);- termDocs.seek(new Term(DocHelper.TEXT_FIELD_2_KEY, "field"));- if (termDocs.next() == true) {- int docId = termDocs.doc();++ TermsEnum terms = reader.fields().terms(DocHelper.TEXT_FIELD_2_KEY).iterator();+ terms.seek(new BytesRef("field"));+ DocsEnum termDocs = terms.docs(reader.getDeletedDocs(), null);+ if (termDocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ int docId = termDocs.docID();assertTrue(docId == 0);int freq = termDocs.freq();assertTrue(freq == 3);@@ -77,20 +79,21 @@ public class TestSegmentTermDocs extends LuceneTestCase {//After adding the document, we should be able to read it back inSegmentReader reader = SegmentReader.get(true, info, indexDivisor);assertTrue(reader != null);- TermDocs termDocs = reader.termDocs();- assertTrue(termDocs != null);- termDocs.seek(new Term("textField2", "bad"));- assertTrue(termDocs.next() == false);+ DocsEnum termDocs = reader.termDocsEnum(reader.getDeletedDocs(),+ "textField2",+ new BytesRef("bad"));++ assertNull(termDocs);reader.close();}{//After adding the document, we should be able to read it back inSegmentReader reader = SegmentReader.get(true, info, indexDivisor);assertTrue(reader != null);- TermDocs termDocs = reader.termDocs();- assertTrue(termDocs != null);- termDocs.seek(new Term("junk", "bad"));- assertTrue(termDocs.next() == false);+ DocsEnum termDocs = reader.termDocsEnum(reader.getDeletedDocs(),+ "junk",+ new BytesRef("bad"));+ assertNull(termDocs);reader.close();}}@@ -121,105 +124,125 @@ public class TestSegmentTermDocs extends LuceneTestCase {IndexReader reader = IndexReader.open(dir, null, true, indexDivisor);- TermDocs tdocs = reader.termDocs();+ DocsEnum tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ ta.field(),+ new BytesRef(ta.text()));// without optimization (assumption skipInterval == 16)// with next- tdocs.seek(ta);- assertTrue(tdocs.next());- assertEquals(0, tdocs.doc());+ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.next());- assertEquals(1, tdocs.doc());+ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(1, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.skipTo(0));- assertEquals(2, tdocs.doc());- assertTrue(tdocs.skipTo(4));- assertEquals(4, tdocs.doc());- assertTrue(tdocs.skipTo(9));- assertEquals(9, tdocs.doc());- assertFalse(tdocs.skipTo(10));+ assertTrue(tdocs.advance(0) != DocsEnum.NO_MORE_DOCS);+ assertEquals(2, tdocs.docID());+ assertTrue(tdocs.advance(4) != DocsEnum.NO_MORE_DOCS);+ assertEquals(4, tdocs.docID());+ assertTrue(tdocs.advance(9) != DocsEnum.NO_MORE_DOCS);+ assertEquals(9, tdocs.docID());+ assertFalse(tdocs.advance(10) != DocsEnum.NO_MORE_DOCS);// without next- tdocs.seek(ta);- assertTrue(tdocs.skipTo(0));- assertEquals(0, tdocs.doc());- assertTrue(tdocs.skipTo(4));- assertEquals(4, tdocs.doc());- assertTrue(tdocs.skipTo(9));- assertEquals(9, tdocs.doc());- assertFalse(tdocs.skipTo(10));+ tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ ta.field(),+ new BytesRef(ta.text()));++ assertTrue(tdocs.advance(0) != DocsEnum.NO_MORE_DOCS);+ assertEquals(0, tdocs.docID());+ assertTrue(tdocs.advance(4) != DocsEnum.NO_MORE_DOCS);+ assertEquals(4, tdocs.docID());+ assertTrue(tdocs.advance(9) != DocsEnum.NO_MORE_DOCS);+ assertEquals(9, tdocs.docID());+ assertFalse(tdocs.advance(10) != DocsEnum.NO_MORE_DOCS);// exactly skipInterval documents and therefore with optimization// with next- tdocs.seek(tb);- assertTrue(tdocs.next());- assertEquals(10, tdocs.doc());+ tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ tb.field(),+ new BytesRef(tb.text()));++ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(10, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.next());- assertEquals(11, tdocs.doc());+ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(11, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.skipTo(5));- assertEquals(12, tdocs.doc());- assertTrue(tdocs.skipTo(15));- assertEquals(15, tdocs.doc());- assertTrue(tdocs.skipTo(24));- assertEquals(24, tdocs.doc());- assertTrue(tdocs.skipTo(25));- assertEquals(25, tdocs.doc());- assertFalse(tdocs.skipTo(26));+ assertTrue(tdocs.advance(5) != DocsEnum.NO_MORE_DOCS);+ assertEquals(12, tdocs.docID());+ assertTrue(tdocs.advance(15) != DocsEnum.NO_MORE_DOCS);+ assertEquals(15, tdocs.docID());+ assertTrue(tdocs.advance(24) != DocsEnum.NO_MORE_DOCS);+ assertEquals(24, tdocs.docID());+ assertTrue(tdocs.advance(25) != DocsEnum.NO_MORE_DOCS);+ assertEquals(25, tdocs.docID());+ assertFalse(tdocs.advance(26) != DocsEnum.NO_MORE_DOCS);// without next- tdocs.seek(tb);- assertTrue(tdocs.skipTo(5));- assertEquals(10, tdocs.doc());- assertTrue(tdocs.skipTo(15));- assertEquals(15, tdocs.doc());- assertTrue(tdocs.skipTo(24));- assertEquals(24, tdocs.doc());- assertTrue(tdocs.skipTo(25));- assertEquals(25, tdocs.doc());- assertFalse(tdocs.skipTo(26));+ tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ tb.field(),+ new BytesRef(tb.text()));++ assertTrue(tdocs.advance(5) != DocsEnum.NO_MORE_DOCS);+ assertEquals(10, tdocs.docID());+ assertTrue(tdocs.advance(15) != DocsEnum.NO_MORE_DOCS);+ assertEquals(15, tdocs.docID());+ assertTrue(tdocs.advance(24) != DocsEnum.NO_MORE_DOCS);+ assertEquals(24, tdocs.docID());+ assertTrue(tdocs.advance(25) != DocsEnum.NO_MORE_DOCS);+ assertEquals(25, tdocs.docID());+ assertFalse(tdocs.advance(26) != DocsEnum.NO_MORE_DOCS);// much more than skipInterval documents and therefore with optimization// with next- tdocs.seek(tc);- assertTrue(tdocs.next());- assertEquals(26, tdocs.doc());+ tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ tc.field(),+ new BytesRef(tc.text()));++ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(26, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.next());- assertEquals(27, tdocs.doc());+ assertTrue(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS);+ assertEquals(27, tdocs.docID());assertEquals(4, tdocs.freq());- assertTrue(tdocs.skipTo(5));- assertEquals(28, tdocs.doc());- assertTrue(tdocs.skipTo(40));- assertEquals(40, tdocs.doc());- assertTrue(tdocs.skipTo(57));- assertEquals(57, tdocs.doc());- assertTrue(tdocs.skipTo(74));- assertEquals(74, tdocs.doc());- assertTrue(tdocs.skipTo(75));- assertEquals(75, tdocs.doc());- assertFalse(tdocs.skipTo(76));+ assertTrue(tdocs.advance(5) != DocsEnum.NO_MORE_DOCS);+ assertEquals(28, tdocs.docID());+ assertTrue(tdocs.advance(40) != DocsEnum.NO_MORE_DOCS);+ assertEquals(40, tdocs.docID());+ assertTrue(tdocs.advance(57) != DocsEnum.NO_MORE_DOCS);+ assertEquals(57, tdocs.docID());+ assertTrue(tdocs.advance(74) != DocsEnum.NO_MORE_DOCS);+ assertEquals(74, tdocs.docID());+ assertTrue(tdocs.advance(75) != DocsEnum.NO_MORE_DOCS);+ assertEquals(75, tdocs.docID());+ assertFalse(tdocs.advance(76) != DocsEnum.NO_MORE_DOCS);//without next- tdocs.seek(tc);- assertTrue(tdocs.skipTo(5));- assertEquals(26, tdocs.doc());- assertTrue(tdocs.skipTo(40));- assertEquals(40, tdocs.doc());- assertTrue(tdocs.skipTo(57));- assertEquals(57, tdocs.doc());- assertTrue(tdocs.skipTo(74));- assertEquals(74, tdocs.doc());- assertTrue(tdocs.skipTo(75));- assertEquals(75, tdocs.doc());- assertFalse(tdocs.skipTo(76));+ tdocs = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ tc.field(),+ new BytesRef(tc.text()));+ assertTrue(tdocs.advance(5) != DocsEnum.NO_MORE_DOCS);+ assertEquals(26, tdocs.docID());+ assertTrue(tdocs.advance(40) != DocsEnum.NO_MORE_DOCS);+ assertEquals(40, tdocs.docID());+ assertTrue(tdocs.advance(57) != DocsEnum.NO_MORE_DOCS);+ assertEquals(57, tdocs.docID());+ assertTrue(tdocs.advance(74) != DocsEnum.NO_MORE_DOCS);+ assertEquals(74, tdocs.docID());+ assertTrue(tdocs.advance(75) != DocsEnum.NO_MORE_DOCS);+ assertEquals(75, tdocs.docID());+ assertFalse(tdocs.advance(76) != DocsEnum.NO_MORE_DOCS);- tdocs.close();reader.close();dir.close();}diff --git a/lucene/src/test/org/apache/lucene/index/TestSegmentTermEnum.java b/lucene/src/test/org/apache/lucene/index/TestSegmentTermEnum.javaindex 4b18f1ed751..48a5efdd3d8 100644--- a/lucene/src/test/org/apache/lucene/index/TestSegmentTermEnum.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentTermEnum.java@@ -20,6 +20,7 @@ package org.apache.lucene.index;import java.io.IOException;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;@@ -83,36 +84,32 @@ public class TestSegmentTermEnum extends LuceneTestCase {throws IOException{IndexReader reader = IndexReader.open(dir, true);- TermEnum termEnum = null;+ TermsEnum termEnum = MultiFields.getTerms(reader, "content").iterator();// create enumeration of all terms- termEnum = reader.terms();// go to the first term (aaa)termEnum.next();// assert that term is 'aaa'- assertEquals("aaa", termEnum.term().text());+ assertEquals("aaa", termEnum.term().utf8ToString());assertEquals(200, termEnum.docFreq());// go to the second term (bbb)termEnum.next();// assert that term is 'bbb'- assertEquals("bbb", termEnum.term().text());+ assertEquals("bbb", termEnum.term().utf8ToString());assertEquals(100, termEnum.docFreq());- termEnum.close();-- // create enumeration of terms after term 'aaa', including 'aaa'- termEnum = reader.terms(new Term("content", "aaa"));+ // create enumeration of terms after term 'aaa',+ // including 'aaa'+ termEnum.seek(new BytesRef("aaa"));// assert that term is 'aaa'- assertEquals("aaa", termEnum.term().text());+ assertEquals("aaa", termEnum.term().utf8ToString());assertEquals(200, termEnum.docFreq());// go to term 'bbb'termEnum.next();// assert that term is 'bbb'- assertEquals("bbb", termEnum.term().text());+ assertEquals("bbb", termEnum.term().utf8ToString());assertEquals(100, termEnum.docFreq());-- termEnum.close();}private void addDoc(IndexWriter writer, String value) throws IOExceptiondiff --git a/lucene/src/test/org/apache/lucene/index/TestStressIndexing.java b/lucene/src/test/org/apache/lucene/index/TestStressIndexing.javaindex e030322b4e6..0c506f2e798 100644--- a/lucene/src/test/org/apache/lucene/index/TestStressIndexing.java+++ b/lucene/src/test/org/apache/lucene/index/TestStressIndexing.java@@ -153,8 +153,6 @@ public class TestStressIndexing extends MultiCodecTestCase {modifier.close();- FlexTestUtil.verifyFlexVsPreFlex(RANDOM, directory);-for(int i=0;i<numThread;i++)assertTrue(! threads[i].failed);diff --git a/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java b/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.javaindex 6d6b8ffaca3..217abe53df3 100644--- a/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java+++ b/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java@@ -71,8 +71,6 @@ public class TestStressIndexing2 extends MultiCodecTestCase {IndexReader r = dw.writer.getReader();dw.writer.commit();verifyEquals(r, dir, "id");- FlexTestUtil.verifyFlexVsPreFlex(this.r, r);- FlexTestUtil.verifyFlexVsPreFlex(this.r, dir);r.close();dw.writer.close();dir.close();@@ -94,8 +92,6 @@ public class TestStressIndexing2 extends MultiCodecTestCase {// verifyEquals(dir2, dir2, "id");verifyEquals(dir1, dir2, "id");- FlexTestUtil.verifyFlexVsPreFlex(r, dir1);- FlexTestUtil.verifyFlexVsPreFlex(r, dir2);}public void testMultiConfig() throws Throwable {@@ -121,9 +117,6 @@ public class TestStressIndexing2 extends MultiCodecTestCase {indexSerial(docs, dir2);//System.out.println("TEST: verify");verifyEquals(dir1, dir2, "id");-- FlexTestUtil.verifyFlexVsPreFlex(r, dir1);- FlexTestUtil.verifyFlexVsPreFlex(r, dir2);}}diff --git a/lucene/src/test/org/apache/lucene/index/TestTermEnumSurrogate.java b/lucene/src/test/org/apache/lucene/index/TestTermEnumSurrogate.javadeleted file mode 100644index 1177e047aa5..00000000000--- a/lucene/src/test/org/apache/lucene/index/TestTermEnumSurrogate.java+++ /dev/null@@ -1,53 +0,0 @@-package org.apache.lucene.index;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.util.LuceneTestCase;--/**- * Back-compat test that you can seek to a lead surrogate in the term- * dictionary. With the old lucene API, this worked, due to the fact that the- * Term itself did not need to be converted into proper UTF-8 bytes.- *- * With the new API the provided Term text must be encodeable into UTF-8.- *- * @deprecated Remove this when the old API is no longer supported.- */-@Deprecated-public class TestTermEnumSurrogate extends LuceneTestCase {- public void testSeekSurrogate() throws Exception {- RAMDirectory dir = new RAMDirectory();- IndexWriter writer = new IndexWriter(dir, new MockAnalyzer(),- IndexWriter.MaxFieldLength.UNLIMITED);- Document d = new Document();- Field f = new Field("field", "", Field.Store.NO, Field.Index.ANALYZED);- d.add(f);- f.setValue("abacadaba");- writer.addDocument(d);- f.setValue("𩬅");- writer.addDocument(d);- writer.close();- IndexReader reader = IndexReader.open(dir, true);- TermEnum te = reader.terms(new Term("field", "𩬅".substring(0, 1)));- assertEquals(new Term("field", "𩬅"), te.term());- }-}diff --git a/lucene/src/test/org/apache/lucene/index/TestTermdocPerf.java b/lucene/src/test/org/apache/lucene/index/TestTermdocPerf.javaindex bfdcbb62279..155cf3826b9 100644--- a/lucene/src/test/org/apache/lucene/index/TestTermdocPerf.java+++ b/lucene/src/test/org/apache/lucene/index/TestTermdocPerf.java@@ -30,6 +30,7 @@ import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;class RepeatingTokenStream extends TokenStream {public int num;@@ -94,16 +95,18 @@ public class TestTermdocPerf extends LuceneTestCase {if (VERBOSE) System.out.println("milliseconds for creation of " + ndocs + " docs = " + (end-start));IndexReader reader = IndexReader.open(dir, true);- TermEnum tenum = reader.terms(new Term("foo","val"));- TermDocs tdocs = reader.termDocs();++ TermsEnum tenum = MultiFields.getTerms(reader, "foo").iterator();start = System.currentTimeMillis();int ret=0;+ DocsEnum tdocs = null;for (int i=0; i<iter; i++) {- tdocs.seek(tenum);- while (tdocs.next()) {- ret += tdocs.doc();+ tenum.seek(new BytesRef("val"));+ tdocs = tenum.docs(MultiFields.getDeletedDocs(reader), tdocs);+ while (tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ ret += tdocs.docID();}}diff --git a/lucene/src/test/org/apache/lucene/search/JustCompileSearch.java b/lucene/src/test/org/apache/lucene/search/JustCompileSearch.javaindex 291970399ac..e0cf8e75513 100644--- a/lucene/src/test/org/apache/lucene/search/JustCompileSearch.java+++ b/lucene/src/test/org/apache/lucene/search/JustCompileSearch.java@@ -298,25 +298,6 @@ final class JustCompileSearch {}- static final class JustCompileFilteredTermEnum extends FilteredTermEnum {-- @Override- public float difference() {- throw new UnsupportedOperationException(UNSUPPORTED_MSG);- }-- @Override- protected boolean endEnum() {- throw new UnsupportedOperationException(UNSUPPORTED_MSG);- }-- @Override- protected boolean termCompare(Term term) {- throw new UnsupportedOperationException(UNSUPPORTED_MSG);- }-- }-static final class JustCompilePhraseScorer extends PhraseScorer {JustCompilePhraseScorer(Weight weight, DocsAndPositionsEnum[] docs, int[] offsets,diff --git a/lucene/src/test/org/apache/lucene/search/TestAutomatonQuery.java b/lucene/src/test/org/apache/lucene/search/TestAutomatonQuery.javaindex 9bcf75ce486..e77cc755e6d 100644--- a/lucene/src/test/org/apache/lucene/search/TestAutomatonQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestAutomatonQuery.java@@ -196,10 +196,4 @@ public class TestAutomatonQuery extends LuceneTestCase {assertSame(TermsEnum.EMPTY, aq.getTermsEnum(searcher.getIndexReader()));assertEquals(0, automatonQueryNrHits(aq));}-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new AutomatonQuery(newTerm("bogus"), BasicAutomata- .makeString("piece")).hasNewAPI);- }}diff --git a/lucene/src/test/org/apache/lucene/search/TestFuzzyQuery.java b/lucene/src/test/org/apache/lucene/search/TestFuzzyQuery.javaindex 2065fadd969..3f41bc8f1ff 100644--- a/lucene/src/test/org/apache/lucene/search/TestFuzzyQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestFuzzyQuery.java@@ -377,10 +377,4 @@ public class TestFuzzyQuery extends LuceneTestCase {doc.add(new Field("field", text, Field.Store.YES, Field.Index.ANALYZED));writer.addDocument(doc);}-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new FuzzyQuery(new Term("dummy", "dummy")).hasNewAPI);- }-}diff --git a/lucene/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java b/lucene/src/test/org/apache/lucene/search/TestMultiPhraseQuery.javaindex ed9c2bfe7b2..33b4a0690e8 100644--- a/lucene/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java@@ -19,21 +19,20 @@ package org.apache.lucene.search;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.util.LuceneTestCase;-import org.apache.lucene.util.Version;import java.io.IOException;-import java.util.HashSet;import java.util.LinkedList;-import java.util.Collections;/*** This class tests the MultiPhraseQuery class.@@ -73,13 +72,16 @@ public class TestMultiPhraseQuery extends LuceneTestCase// this TermEnum gives "piccadilly", "pie" and "pizza".String prefix = "pi";- TermEnum te = ir.terms(new Term("body", prefix));+ TermsEnum te = MultiFields.getFields(ir).terms("body").iterator();+ te.seek(new BytesRef(prefix));do {- if (te.term().text().startsWith(prefix))- {- termsWithPrefix.add(te.term());+ String s = te.term().utf8ToString();+ if (s.startsWith(prefix)) {+ termsWithPrefix.add(new Term("body", s));+ } else {+ break;}- } while (te.next());+ } while (te.next() != null);query1.add(termsWithPrefix.toArray(new Term[0]));assertEquals("body:\"blueberry (piccadilly pie pizza)\"", query1.toString());@@ -96,13 +98,14 @@ public class TestMultiPhraseQuery extends LuceneTestCaseMultiPhraseQuery query3 = new MultiPhraseQuery();termsWithPrefix.clear();prefix = "blue";- te = ir.terms(new Term("body", prefix));+ te.seek(new BytesRef(prefix));+do {- if (te.term().text().startsWith(prefix))+ if (te.term().utf8ToString().startsWith(prefix)){- termsWithPrefix.add(te.term());+ termsWithPrefix.add(new Term("body", te.term().utf8ToString()));}- } while (te.next());+ } while (te.next() != null);ir.close();query3.add(termsWithPrefix.toArray(new Term[0]));query3.add(new Term("body", "pizza"));diff --git a/lucene/src/test/org/apache/lucene/search/TestMultiTermQueryBWComp.java b/lucene/src/test/org/apache/lucene/search/TestMultiTermQueryBWComp.javadeleted file mode 100644index f2d7ad97598..00000000000--- a/lucene/src/test/org/apache/lucene/search/TestMultiTermQueryBWComp.java+++ /dev/null@@ -1,239 +0,0 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermsEnum;-import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.util.LuceneTestCaseJ4;-import org.junit.AfterClass;-import org.junit.BeforeClass;-import org.junit.Test;-import static org.junit.Assert.*;--/**- * Test MultiTermQuery api backwards compat- * @deprecated Remove test when old API is no longer supported- */-@Deprecated-public class TestMultiTermQueryBWComp extends LuceneTestCaseJ4 {- private static RAMDirectory dir;- private static Searcher searcher;- private static final String FIELD = "test";-- /**- * Test that the correct method (getTermsEnum/getEnum) is called.- */- @Test- public void testEnumMethod() throws IOException {- assertAPI("old", new OldAPI(FIELD));- assertAPI("new", new NewAPI(FIELD));- assertAPI("new", new BothAPI(FIELD));-- assertAPI("old2", new OldExtendsOldAPI(FIELD));- assertAPI("old2", new OldExtendsNewAPI(FIELD));- assertAPI("old2", new OldExtendsBothAPI(FIELD));-- assertAPI("new2", new NewExtendsOldAPI(FIELD));- assertAPI("new2", new NewExtendsNewAPI(FIELD));- assertAPI("new2", new NewExtendsBothAPI(FIELD));-- assertAPI("new2", new BothExtendsOldAPI(FIELD));- assertAPI("new2", new BothExtendsNewAPI(FIELD));- assertAPI("new2", new BothExtendsBothAPI(FIELD));- }-- private static void assertAPI(String expected, Query query) throws IOException {- TopDocs td = searcher.search(query, 25);- assertEquals(1, td.totalHits);- Document doc = searcher.doc(td.scoreDocs[0].doc);- assertEquals(expected, doc.get(FIELD));- }-- private class OldAPI extends MultiTermQuery {- OldAPI(String field) { super(field); }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old"));- }-- @Override- public String toString(String field) { return null; }- }-- private class NewAPI extends MultiTermQuery {- NewAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new"));- }-- @Override- public String toString(String field) { return null; }- }-- private class BothAPI extends MultiTermQuery {- BothAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new"));- }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old"));- }-- @Override- public String toString(String field) { return null; }- }-- private class OldExtendsOldAPI extends OldAPI {- OldExtendsOldAPI(String field) { super(field); }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- private class OldExtendsNewAPI extends NewAPI {- OldExtendsNewAPI(String field) { super(field); }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- private class OldExtendsBothAPI extends BothAPI {- OldExtendsBothAPI(String field) { super(field); }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- private class NewExtendsOldAPI extends OldAPI {- NewExtendsOldAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }- }-- private class NewExtendsNewAPI extends NewAPI {- NewExtendsNewAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }- }-- private class NewExtendsBothAPI extends BothAPI {- NewExtendsBothAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }- }-- private class BothExtendsOldAPI extends OldAPI {- BothExtendsOldAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- private class BothExtendsNewAPI extends NewAPI {- BothExtendsNewAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- private class BothExtendsBothAPI extends BothAPI {- BothExtendsBothAPI(String field) { super(field); }-- @Override- protected TermsEnum getTermsEnum(IndexReader reader) throws IOException {- return new SingleTermsEnum(reader, new Term(FIELD, "new2"));- }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new SingleTermEnum(reader, new Term(FIELD, "old2"));- }- }-- @BeforeClass- public static void beforeClass() throws Exception {- dir = new RAMDirectory();- IndexWriter writer = new IndexWriter(dir,- new MockAnalyzer(), true,- IndexWriter.MaxFieldLength.LIMITED);-- String values[] = { "old", "old2", "new", "new2" };- for (String value : values) {- Document doc = new Document();- doc.add(new Field(FIELD, value,- Field.Store.YES, Field.Index.ANALYZED));- writer.addDocument(doc);- }-- writer.optimize();- writer.close();- searcher = new IndexSearcher(dir, true);- }-- @AfterClass- public static void afterClass() throws Exception {- searcher.close();- searcher = null;- dir.close();- dir = null;- }-}diff --git a/lucene/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java b/lucene/src/test/org/apache/lucene/search/TestNumericRangeQuery64.javaindex eda0d8d50a7..da431d0aec7 100644--- a/lucene/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java+++ b/lucene/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java@@ -590,10 +590,4 @@ public class TestNumericRangeQuery64 extends LuceneTestCaseJ4 {);// difference to int range is tested in TestNumericRangeQuery32}-- @Test @Deprecated- public void testBackwardsLayer() {- assertTrue(NumericRangeQuery.newLongRange("dummy", null, null, true, true).hasNewAPI);- }-}diff --git a/lucene/src/test/org/apache/lucene/search/TestPhrasePrefixQuery.java b/lucene/src/test/org/apache/lucene/search/TestPhrasePrefixQuery.javaindex 8ccdb58f542..1464c5e7f3d 100644--- a/lucene/src/test/org/apache/lucene/search/TestPhrasePrefixQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestPhrasePrefixQuery.java@@ -21,11 +21,13 @@ import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.lucene.index.TermsEnum;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.store.RAMDirectory;import java.io.IOException;@@ -79,13 +81,16 @@ public class TestPhrasePrefixQuery extends LuceneTestCase {// this TermEnum gives "piccadilly", "pie" and "pizza".String prefix = "pi";- TermEnum te = ir.terms(new Term("body", prefix + "*"));+ TermsEnum te = MultiFields.getFields(ir).terms("body").iterator();+ te.seek(new BytesRef(prefix));do {- if (te.term().text().startsWith(prefix))- {- termsWithPrefix.add(te.term());+ String s = te.term().utf8ToString();+ if (s.startsWith(prefix)) {+ termsWithPrefix.add(new Term("body", s));+ } else {+ break;}- } while (te.next());+ } while (te.next() != null);query1.add(termsWithPrefix.toArray(new Term[0]));query2.add(termsWithPrefix.toArray(new Term[0]));diff --git a/lucene/src/test/org/apache/lucene/search/TestPositionIncrement.java b/lucene/src/test/org/apache/lucene/search/TestPositionIncrement.javaindex c3724875191..8cec7a2b056 100644--- a/lucene/src/test/org/apache/lucene/search/TestPositionIncrement.java+++ b/lucene/src/test/org/apache/lucene/search/TestPositionIncrement.java@@ -32,11 +32,12 @@ import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.index.DocsAndPositionsEnum;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermPositions;import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.store.Directory;@@ -50,6 +51,7 @@ import org.apache.lucene.search.spans.Spans;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.automaton.CharacterRunAutomaton;import org.apache.lucene.util.automaton.RegExp;+import org.apache.lucene.util.BytesRef;/*** Term position unit test.@@ -99,13 +101,19 @@ public class TestPositionIncrement extends LuceneTestCase {IndexSearcher searcher = new IndexSearcher(store, true);- TermPositions pos = searcher.getIndexReader().termPositions(new Term("field", "1"));- pos.next();+ DocsAndPositionsEnum pos = MultiFields.getTermPositionsEnum(searcher.getIndexReader(),+ MultiFields.getDeletedDocs(searcher.getIndexReader()),+ "field",+ new BytesRef("1"));+ pos.nextDoc();// first token should be at position 0assertEquals(0, pos.nextPosition());- pos = searcher.getIndexReader().termPositions(new Term("field", "2"));- pos.next();+ pos = MultiFields.getTermPositionsEnum(searcher.getIndexReader(),+ MultiFields.getDeletedDocs(searcher.getIndexReader()),+ "field",+ new BytesRef("2"));+ pos.nextDoc();// second token should be at position 2assertEquals(2, pos.nextPosition());@@ -238,9 +246,13 @@ public class TestPositionIncrement extends LuceneTestCase {IndexReader r = writer.getReader();- TermPositions tp = r.termPositions(new Term("content", "a"));+ DocsAndPositionsEnum tp = MultiFields.getTermPositionsEnum(r,+ MultiFields.getDeletedDocs(r),+ "content",+ new BytesRef("a"));+int count = 0;- assertTrue(tp.next());+ assertTrue(tp.nextDoc() != tp.NO_MORE_DOCS);// "a" occurs 4 timesassertEquals(4, tp.freq());int expected = 0;@@ -250,7 +262,7 @@ public class TestPositionIncrement extends LuceneTestCase {assertEquals(6, tp.nextPosition());// only one doc has "a"- assertFalse(tp.next());+ assertEquals(tp.NO_MORE_DOCS, tp.nextDoc());IndexSearcher is = new IndexSearcher(r);diff --git a/lucene/src/test/org/apache/lucene/search/TestPrefixQuery.java b/lucene/src/test/org/apache/lucene/search/TestPrefixQuery.javaindex 4efe1ea71f4..5508dacc08d 100644--- a/lucene/src/test/org/apache/lucene/search/TestPrefixQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestPrefixQuery.java@@ -59,9 +59,4 @@ public class TestPrefixQuery extends LuceneTestCase {hits = searcher.search(query, null, 1000).scoreDocs;assertEquals("everything", 3, hits.length);}-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new PrefixQuery(new Term("dummy", "dummy")).hasNewAPI);- }}diff --git a/lucene/src/test/org/apache/lucene/search/TestRegexpQuery.java b/lucene/src/test/org/apache/lucene/search/TestRegexpQuery.javaindex 065f2f9caa5..a0c1742a3b8 100644--- a/lucene/src/test/org/apache/lucene/search/TestRegexpQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestRegexpQuery.java@@ -25,7 +25,6 @@ import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.Term;-import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.automaton.Automaton;@@ -120,9 +119,4 @@ public class TestRegexpQuery extends LuceneTestCase {public void testBacktracking() throws IOException {assertEquals(1, regexQueryNrHits("4934[314]"));}-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new RegexpQuery(newTerm(".*")).hasNewAPI);- }}diff --git a/lucene/src/test/org/apache/lucene/search/TestTermRangeQuery.java b/lucene/src/test/org/apache/lucene/search/TestTermRangeQuery.javaindex f588018c0c5..f32390a32fd 100644--- a/lucene/src/test/org/apache/lucene/search/TestTermRangeQuery.java+++ b/lucene/src/test/org/apache/lucene/search/TestTermRangeQuery.java@@ -420,9 +420,4 @@ public class TestTermRangeQuery extends LuceneTestCase {//assertEquals("C added => A,B,<empty string>,C in range", 3, hits.length());searcher.close();}-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new TermRangeQuery("dummy", null, null, true, true).hasNewAPI);- }}diff --git a/lucene/src/test/org/apache/lucene/search/TestTermVectors.java b/lucene/src/test/org/apache/lucene/search/TestTermVectors.javaindex 39fd3de7e76..65db25dfe9d 100644--- a/lucene/src/test/org/apache/lucene/search/TestTermVectors.java+++ b/lucene/src/test/org/apache/lucene/search/TestTermVectors.java@@ -244,40 +244,38 @@ public class TestTermVectors extends LuceneTestCase {writer.addDocument(testDoc4);writer.close();IndexSearcher knownSearcher = new IndexSearcher(dir, true);- TermEnum termEnum = knownSearcher.reader.terms();- TermDocs termDocs = knownSearcher.reader.termDocs();- //System.out.println("Terms: " + termEnum.size() + " Orig Len: " + termArray.length);-- //Similarity sim = knownSearcher.getSimilarity();- while (termEnum.next() == true)- {- Term term = termEnum.term();- //System.out.println("Term: " + term);- termDocs.seek(term);- while (termDocs.next())- {- int docId = termDocs.doc();- int freq = termDocs.freq();- //System.out.println("Doc Id: " + docId + " freq " + freq);- TermFreqVector vector = knownSearcher.reader.getTermFreqVector(docId, "field");- //float tf = sim.tf(freq);- //float idf = sim.idf(knownSearcher.docFreq(term), knownSearcher.maxDoc());- //float qNorm = sim.queryNorm()- //This is fine since we don't have stop words- //float lNorm = sim.lengthNorm("field", vector.getTerms().length);- //float coord = sim.coord()- //System.out.println("TF: " + tf + " IDF: " + idf + " LenNorm: " + lNorm);- assertTrue(vector != null);- String[] vTerms = vector.getTerms();- int [] freqs = vector.getTermFrequencies();- for (int i = 0; i < vTerms.length; i++)- {- if (term.text().equals(vTerms[i]))- {- assertTrue(freqs[i] == freq);- }+ FieldsEnum fields = MultiFields.getFields(knownSearcher.reader).iterator();++ DocsEnum docs = null;+ while(fields.next() != null) {+ TermsEnum terms = fields.terms();+ while(terms.next() != null) {+ String text = terms.term().utf8ToString();+ docs = terms.docs(MultiFields.getDeletedDocs(knownSearcher.reader), docs);++ while (docs.nextDoc() != DocsEnum.NO_MORE_DOCS) {+ int docId = docs.docID();+ int freq = docs.freq();+ //System.out.println("Doc Id: " + docId + " freq " + freq);+ TermFreqVector vector = knownSearcher.reader.getTermFreqVector(docId, "field");+ //float tf = sim.tf(freq);+ //float idf = sim.idf(knownSearcher.docFreq(term), knownSearcher.maxDoc());+ //float qNorm = sim.queryNorm()+ //This is fine since we don't have stop words+ //float lNorm = sim.lengthNorm("field", vector.getTerms().length);+ //float coord = sim.coord()+ //System.out.println("TF: " + tf + " IDF: " + idf + " LenNorm: " + lNorm);+ assertTrue(vector != null);+ String[] vTerms = vector.getTerms();+ int [] freqs = vector.getTermFrequencies();+ for (int i = 0; i < vTerms.length; i++)+ {+ if (text.equals(vTerms[i]))+ {+ assertTrue(freqs[i] == freq);+ }+ }}-}//System.out.println("--------");}diff --git a/lucene/src/test/org/apache/lucene/search/TestWildcard.java b/lucene/src/test/org/apache/lucene/search/TestWildcard.javaindex 6889b3f3c3d..a45cf94d630 100644--- a/lucene/src/test/org/apache/lucene/search/TestWildcard.java+++ b/lucene/src/test/org/apache/lucene/search/TestWildcard.java@@ -19,12 +19,10 @@ package org.apache.lucene.search;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.Store;import org.apache.lucene.document.Field.Index;-import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;@@ -309,62 +307,4 @@ public class TestWildcardsearcher.close();}- @Deprecated- private static final class OldWildcardQuery extends MultiTermQuery {- final Term term;-- OldWildcardQuery(Term term) {- this.term = term;- }-- @Override- protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {- return new WildcardTermEnum(reader, term);- }-- @Override- public String toString(String field) {- return "OldWildcard(" + term.toString()+ ")";- }- }-- @Deprecated- public void testDeprecatedTermEnum() throws Exception {- RAMDirectory indexStore = getIndexStore("body", new String[]- {"metal", "metals"});- IndexSearcher searcher = new IndexSearcher(indexStore, true);- Query query1 = new TermQuery(new Term("body", "metal"));- Query query2 = new OldWildcardQuery(new Term("body", "metal*"));- Query query3 = new OldWildcardQuery(new Term("body", "m*tal"));- Query query4 = new OldWildcardQuery(new Term("body", "m*tal*"));- Query query5 = new OldWildcardQuery(new Term("body", "m*tals"));-- BooleanQuery query6 = new BooleanQuery();- query6.add(query5, BooleanClause.Occur.SHOULD);-- BooleanQuery query7 = new BooleanQuery();- query7.add(query3, BooleanClause.Occur.SHOULD);- query7.add(query5, BooleanClause.Occur.SHOULD);-- // Queries do not automatically lower-case search terms:- Query query8 = new OldWildcardQuery(new Term("body", "M*tal*"));-- assertMatches(searcher, query1, 1);- assertMatches(searcher, query2, 2);- assertMatches(searcher, query3, 1);- assertMatches(searcher, query4, 2);- assertMatches(searcher, query5, 1);- assertMatches(searcher, query6, 1);- assertMatches(searcher, query7, 2);- assertMatches(searcher, query8, 0);- assertMatches(searcher, new OldWildcardQuery(new Term("body", "*tall")), 0);- assertMatches(searcher, new OldWildcardQuery(new Term("body", "*tal")), 1);- assertMatches(searcher, new OldWildcardQuery(new Term("body", "*tal*")), 2);- }-- @Deprecated- public void testBackwardsLayer() {- assertTrue(new WildcardQuery(new Term("body", "metal*")).hasNewAPI);- assertFalse(new OldWildcardQuery(new Term("body", "metal*")).hasNewAPI);- }}diff --git a/modules/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java b/modules/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.javaindex 41720e6333e..bc4e62794d2 100644--- a/modules/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java+++ b/modules/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java@@ -18,12 +18,14 @@ package org.apache.lucene.analysis.query;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.core.StopFilter;-import org.apache.lucene.util.StringHelper;import org.apache.lucene.util.Version;+import org.apache.lucene.util.BytesRef;import java.io.IOException;import java.io.Reader;@@ -141,20 +143,15 @@ public final class QueryAutoStopWordAnalyzer extends Analyzer {*/public int addStopWords(IndexReader reader, String fieldName, int maxDocFreq) throws IOException {HashSet<String> stopWords = new HashSet<String>();- String internedFieldName = StringHelper.intern(fieldName);- TermEnum te = reader.terms(new Term(fieldName));- Term term = te.term();- while (term != null) {- if (term.field() != internedFieldName) {- break;+ Terms terms = MultiFields.getTerms(reader, fieldName);+ if (terms != null) {+ TermsEnum te = terms.iterator();+ BytesRef text;+ while ((text = te.next()) != null) {+ if (te.docFreq() > maxDocFreq) {+ stopWords.add(text.utf8ToString());+ }}- if (te.docFreq() > maxDocFreq) {- stopWords.add(term.text());- }- if (!te.next()) {- break;- }- term = te.term();}stopWordsPerField.put(fieldName, stopWords);diff --git a/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestKeywordAnalyzer.java b/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestKeywordAnalyzer.javaindex 3baa63157d2..a8fbc731d93 100644--- a/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestKeywordAnalyzer.java+++ b/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestKeywordAnalyzer.java@@ -21,17 +21,17 @@ import java.io.StringReader;import org.apache.lucene.analysis.BaseTokenStreamTestCase;import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.analysis.core.KeywordAnalyzer;import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.util.BytesRef;public class TestKeywordAnalyzer extends BaseTokenStreamTestCase {@@ -82,10 +82,16 @@ public class TestKeywordAnalyzer extends BaseTokenStreamTestCase {writer.close();IndexReader reader = IndexReader.open(dir, true);- TermDocs td = reader.termDocs(new Term("partnum", "Q36"));- assertTrue(td.next());- td = reader.termDocs(new Term("partnum", "Q37"));- assertTrue(td.next());+ DocsEnum td = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "partnum",+ new BytesRef("Q36"));+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);+ td = MultiFields.getTermDocsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "partnum",+ new BytesRef("Q37"));+ assertTrue(td.nextDoc() != DocsEnum.NO_MORE_DOCS);}// LUCENE-1441diff --git a/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java b/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.javaindex 803606f0877..a30e4461b02 100644--- a/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java+++ b/modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java@@ -12,10 +12,13 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermPositions;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.Version;+import org.apache.lucene.util.BytesRef;/**@@ -279,8 +282,11 @@ public class TestStandardAnalyzer extends BaseTokenStreamTestCase {// Make sure position is still incremented when// massive term is skipped:- TermPositions tps = reader.termPositions(new Term("content", "another"));- assertTrue(tps.next());+ DocsAndPositionsEnum tps = MultiFields.getTermPositionsEnum(reader,+ MultiFields.getDeletedDocs(reader),+ "content",+ new BytesRef("another"));+ assertTrue(tps.nextDoc() != DocsEnum.NO_MORE_DOCS);assertEquals(1, tps.freq());assertEquals(3, tps.nextPosition());diff --git a/solr/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java b/solr/src/java/org/apache/solr/handler/admin/LukeRequestHandler.javaindex 10619456a9e..cf7169b4c27 100644--- a/solr/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java+++ b/solr/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java@@ -37,13 +37,17 @@ import org.apache.lucene.document.Document;import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.Fields;+import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.TermFreqVector;import org.apache.lucene.search.Query;import org.apache.lucene.search.TermRangeQuery;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.util.PriorityQueue;+import org.apache.lucene.util.BytesRef;import org.apache.solr.analysis.CharFilterFactory;import org.apache.solr.analysis.TokenFilterFactory;import org.apache.solr.analysis.TokenizerChain;@@ -468,18 +472,18 @@ public class LukeRequestHandler extends RequestHandlerBaseindexInfo.add("maxDoc", reader.maxDoc());if( countTerms ) {- TermEnum te = null;- try{- te = reader.terms();- int numTerms = 0;- while (te.next()) {- numTerms++;+ Fields fields = MultiFields.getFields(reader);+ int numTerms = 0;+ if (fields != null) {+ FieldsEnum fieldsEnum = fields.iterator();+ while(fieldsEnum.next() != null) {+ TermsEnum termsEnum = fieldsEnum.terms();+ while(termsEnum.next() != null) {+ numTerms++;+ }}- indexInfo.add("numTerms", numTerms );- }- finally{- if( te != null ) te.close();}+ indexInfo.add("numTerms", numTerms );}indexInfo.add("version", reader.getVersion()); // TODO? Is this different then: IndexReader.getCurrentVersion( dir )?@@ -528,7 +532,6 @@ public class LukeRequestHandler extends RequestHandlerBaseint maxBucket = -1;public Map<Integer,Integer> hist = new HashMap<Integer, Integer>();- private static final double LOG2 = Math.log( 2 );public static int getPowerOfTwoBucket( int num ){return Math.max(1, Integer.highestOneBit(num-1) << 1);@@ -621,45 +624,48 @@ public class LukeRequestHandler extends RequestHandlerBaseprivate static Map<String,TopTermQueue> getTopTerms( IndexReader reader, Set<String> fields, int numTerms, Set<String> junkWords ) throws Exception{Map<String,TopTermQueue> info = new HashMap<String, TopTermQueue>();-- TermEnum terms = null;- try{- terms = reader.terms();- while (terms.next()) {- String field = terms.term().field();- String t = terms.term().text();++ Fields fieldsC = MultiFields.getFields(reader);+ if (fieldsC != null) {+ FieldsEnum fieldsEnum = fieldsC.iterator();+ String field;+ while((field = fieldsEnum.next()) != null) {++ TermsEnum termsEnum = fieldsEnum.terms();+ BytesRef text;+ while((text = termsEnum.next()) != null) {+ String t = text.utf8ToString();- // Compute distinct terms for every field- TopTermQueue tiq = info.get( field );- if( tiq == null ) {- tiq = new TopTermQueue( numTerms+1 );- info.put( field, tiq );- }- tiq.distinctTerms++;- tiq.histogram.add( terms.docFreq() ); // add the term to the histogram+ // Compute distinct terms for every field+ TopTermQueue tiq = info.get( field );+ if( tiq == null ) {+ tiq = new TopTermQueue( numTerms+1 );+ info.put( field, tiq );+ }++ tiq.distinctTerms++;+ tiq.histogram.add( termsEnum.docFreq() ); // add the term to the histogram- // Only save the distinct terms for fields we worry about- if (fields != null && fields.size() > 0) {- if( !fields.contains( field ) ) {+ // Only save the distinct terms for fields we worry about+ if (fields != null && fields.size() > 0) {+ if( !fields.contains( field ) ) {+ continue;+ }+ }+ if( junkWords != null && junkWords.contains( t ) ) {continue;}- }- if( junkWords != null && junkWords.contains( t ) ) {- continue;- }- if( terms.docFreq() > tiq.minFreq ) {- tiq.add(new TopTermQueue.TermInfo(terms.term(), terms.docFreq()));+ if( termsEnum.docFreq() > tiq.minFreq ) {+ tiq.add(new TopTermQueue.TermInfo(new Term(field, t), termsEnum.docFreq()));if (tiq.size() > numTerms) { // if tiq full- tiq.pop(); // remove lowest in tiq- tiq.minFreq = ((TopTermQueue.TermInfo)tiq.top()).docFreq; // reset minFreq+ tiq.pop(); // remove lowest in tiq+ tiq.minFreq = ((TopTermQueue.TermInfo)tiq.top()).docFreq; // reset minFreq+ }}}}}- finally {- if( terms != null ) terms.close();- }return info;}}diff --git a/solr/src/java/org/apache/solr/handler/component/TermVectorComponent.java b/solr/src/java/org/apache/solr/handler/component/TermVectorComponent.javaindex 03b865c26d3..8ddbffb544e 100644--- a/solr/src/java/org/apache/solr/handler/component/TermVectorComponent.java+++ b/solr/src/java/org/apache/solr/handler/component/TermVectorComponent.java@@ -4,9 +4,12 @@ import org.apache.lucene.document.Document;import org.apache.lucene.document.SetBasedFieldSelector;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.TermVectorMapper;import org.apache.lucene.index.TermVectorOffsetInfo;+import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.ModifiableSolrParams;@@ -31,7 +34,7 @@ import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;-import java.util.logging.Logger;+/*** Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements. See the NOTICE file distributed with@@ -252,9 +255,12 @@ public class TermVectorComponent extends SearchComponent implements SolrCoreAwarint result = 1;currentTerm = currentTerm.createTerm(term);try {- TermEnum termEnum = reader.terms(currentTerm);- if (termEnum != null && termEnum.term().equals(currentTerm)) {- result = termEnum.docFreq();+ Terms terms = MultiFields.getTerms(reader, currentTerm.field());+ if (terms != null) {+ TermsEnum termsEnum = terms.iterator();+ if (termsEnum.seek(new BytesRef(term)) == TermsEnum.SeekStatus.FOUND) {+ result = termsEnum.docFreq();+ }}} catch (IOException e) {throw new RuntimeException(e);diff --git a/solr/src/java/org/apache/solr/request/UnInvertedField.java b/solr/src/java/org/apache/solr/request/UnInvertedField.javaindex 017a1b18e40..43bdf012c80 100755--- a/solr/src/java/org/apache/solr/request/UnInvertedField.java+++ b/solr/src/java/org/apache/solr/request/UnInvertedField.java@@ -20,10 +20,14 @@ package org.apache.solr.request;import org.apache.lucene.search.FieldCache;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TermRangeQuery;+import org.apache.noggit.CharArr;import org.apache.solr.common.params.FacetParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.SolrException;@@ -36,6 +40,8 @@ import org.apache.solr.util.BoundedTreeSet;import org.apache.solr.handler.component.StatsValues;import org.apache.solr.handler.component.FieldFacetStats;import org.apache.lucene.util.OpenBitSet;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.Bits;import java.io.IOException;import java.util.ArrayList;@@ -43,6 +49,7 @@ import java.util.Arrays;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;+import java.util.Comparator;import java.util.concurrent.atomic.AtomicLong;@@ -80,12 +87,12 @@ public class UnInvertedField {private static int TNUM_OFFSET=2;static class TopTerm {- Term term;+ BytesRef term;int termNum;long memSize() {return 8 + // obj header- 8 + 8 +(term.text().length()<<1) + //term+ 8 + 8 +term.length + //term4; // int}}@@ -191,7 +198,7 @@ public class UnInvertedField {final byte[][] bytes = new byte[maxDoc][]; // list of term numbers for the doc (delta encoded vInts)maxTermCounts = new int[1024];- NumberedTermEnum te = ti.getEnumerator(reader);+ NumberedTermsEnum te = ti.getEnumerator(reader);// threshold, over which we use set intersections instead of counting// to (1) save memory, and (2) speed up faceting.@@ -199,8 +206,6 @@ public class UnInvertedField {// the threshold even when the index is very small.int threshold = maxDoc / 20 + 2;// threshold = 2000000000; //////////////////////////////// USE FOR TESTING- int[] docs = new int[1000];- int[] freqs = new int[1000];// we need a minimum of 9 bytes, but round up to 12 since the space would// be wasted with most allocators anyway.@@ -223,7 +228,7 @@ public class UnInvertedField {// frequent terms ahead of time.for (;;) {- Term t = te.term();+ BytesRef t = te.term();if (t==null) break;int termNum = te.getTermNumber();@@ -239,11 +244,11 @@ public class UnInvertedField {int df = te.docFreq();if (df >= threshold) {TopTerm topTerm = new TopTerm();- topTerm.term = t;+ topTerm.term = new BytesRef(t);topTerm.termNum = termNum;bigTerms.put(topTerm.termNum, topTerm);- DocSet set = searcher.getDocSet(new TermQuery(topTerm.term));+ DocSet set = searcher.getDocSet(new TermQuery(new Term(ti.field, topTerm.term.utf8ToString())));maxTermCounts[termNum] = set.size();te.next();@@ -252,17 +257,19 @@ public class UnInvertedField {termsInverted++;- TermDocs td = te.getTermDocs();- td.seek(te);+ DocsEnum td = te.getDocsEnum();++ DocsEnum.BulkReadResult bulkResult = td.getBulkResult();+for(;;) {- int n = td.read(docs,freqs);+ int n = td.read();if (n <= 0) break;maxTermCounts[termNum] += n;for (int i=0; i<n; i++) {termInstances++;- int doc = docs[i];+ int doc = bulkResult.docs.ints[i];// add 2 to the term number to make room for special reserved values:// 0 (end term) and 1 (index into byte array follows)int delta = termNum - lastTerm[doc] + TNUM_OFFSET;@@ -460,11 +467,11 @@ public class UnInvertedField {int startTerm = 0;int endTerm = numTermsInField; // one past the end- NumberedTermEnum te = ti.getEnumerator(searcher.getReader());+ NumberedTermsEnum te = ti.getEnumerator(searcher.getReader());if (prefix != null && prefix.length() > 0) {- te.skipTo(prefix);+ te.skipTo(new BytesRef(prefix));startTerm = te.getTermNumber();- te.skipTo(prefix + "\uffff\uffff\uffff\uffff");+ te.skipTo(new BytesRef(prefix + "\uffff\uffff\uffff\uffff"));endTerm = te.getTermNumber();}@@ -497,7 +504,7 @@ public class UnInvertedField {for (TopTerm tt : bigTerms.values()) {// TODO: counts could be deferred if sorted==falseif (tt.termNum >= startTerm && tt.termNum < endTerm) {- counts[tt.termNum] = searcher.numDocs(new TermQuery(tt.term), docs);+ counts[tt.termNum] = searcher.numDocs(new TermQuery(new Term(ti.field, tt.term.utf8ToString())), docs);}}@@ -549,6 +556,8 @@ public class UnInvertedField {}}+ CharArr spare = new CharArr();+int off=offset;int lim=limit>=0 ? limit : Integer.MAX_VALUE;@@ -584,7 +593,7 @@ public class UnInvertedField {int c = -(int)(p.longValue() >>> 32);//int tnum = 0x7fffffff - (int)p.longValue(); // use if priority queueint tnum = (int)p.longValue();- String label = ft.indexedToReadable(getTermText(te, tnum));+ String label = getReadableValue(getTermValue(te, tnum), ft, spare);res.add(label, c);}} else {@@ -602,7 +611,7 @@ public class UnInvertedField {if (c<mincount || --off>=0) continue;if (--lim<0) break;- String label = ft.indexedToReadable(getTermText(te, i));+ String label = getReadableValue(getTermValue(te, i), ft, spare);res.add(label, c);}}@@ -669,7 +678,7 @@ public class UnInvertedField {final int[] index = this.index;final int[] counts = new int[numTermsInField];//keep track of the number of times we see each word in the field for all the documents in the docset- NumberedTermEnum te = ti.getEnumerator(searcher.getReader());+ NumberedTermsEnum te = ti.getEnumerator(searcher.getReader());boolean doNegative = false;@@ -693,12 +702,13 @@ public class UnInvertedField {for (TopTerm tt : bigTerms.values()) {// TODO: counts could be deferred if sorted==falseif (tt.termNum >= 0 && tt.termNum < numTermsInField) {+ final Term t = new Term(ti.field, tt.term.utf8ToString());if (finfo.length == 0) {- counts[tt.termNum] = searcher.numDocs(new TermQuery(tt.term), docs);+ counts[tt.termNum] = searcher.numDocs(new TermQuery(t), docs);} else {//COULD BE VERY SLOW//if we're collecting stats for facet fields, we need to iterate on all matching documents- DocSet bigTermDocSet = searcher.getDocSet(new TermQuery(tt.term)).intersection(docs);+ DocSet bigTermDocSet = searcher.getDocSet(new TermQuery(t)).intersection(docs);DocIterator iter = bigTermDocSet.iterator();while (iter.hasNext()) {int doc = iter.nextDoc();@@ -758,11 +768,15 @@ public class UnInvertedField {}// add results in index order+ CharArr spare = new CharArr();for (i = 0; i < numTermsInField; i++) {int c = doNegative ? maxTermCounts[i] - counts[i] : counts[i];if (c == 0) continue;- Double value = Double.parseDouble(ft.indexedToReadable(getTermText(te, i)));+ String label = getReadableValue(getTermValue(te, i), ft, spare);+ // TODO: we should avoid this re-parse+ Double value = Double.parseDouble(label);+allstats.accumulate(value, c);//as we've parsed the termnum into a value, lets also accumulate fieldfacet statisticsfor (FieldFacetStats f : finfo) {@@ -792,20 +806,27 @@ public class UnInvertedField {}+ String getReadableValue(BytesRef termval, FieldType ft, CharArr spare) {+ if (spare == null) {+ spare = new CharArr();+ } else {+ spare.reset();+ }+ ft.indexedToReadable(termval, spare);+ return spare.toString();+ }--- String getTermText(NumberedTermEnum te, int termNum) throws IOException {+ /** may return a reused BytesRef */+ BytesRef getTermValue(NumberedTermsEnum te, int termNum) throws IOException {if (bigTerms.size() > 0) {// see if the term is one of our big terms.TopTerm tt = bigTerms.get(termNum);if (tt != null) {- return tt.term.text();+ return tt.term;}}- te.skipTo(termNum);- return te.term().text();+ return te.skipTo(termNum);}public String toString() {@@ -860,95 +881,97 @@ class TermEnumListener {***/-class NumberedTermEnum extends TermEnum {+class NumberedTermsEnum extends TermsEnum {protected final IndexReader reader;protected final TermIndex tindex;- protected TermEnum tenum;+ protected TermsEnum tenum;protected int pos=-1;- protected Term t;- protected TermDocs termDocs;+ protected BytesRef termText;+ protected DocsEnum docsEnum;- NumberedTermEnum(IndexReader reader, TermIndex tindex) throws IOException {+ NumberedTermsEnum(IndexReader reader, TermIndex tindex) throws IOException {this.reader = reader;this.tindex = tindex;}- NumberedTermEnum(IndexReader reader, TermIndex tindex, String termValue, int pos) throws IOException {+ NumberedTermsEnum(IndexReader reader, TermIndex tindex, BytesRef termValue, int pos) throws IOException {this.reader = reader;this.tindex = tindex;this.pos = pos;- tenum = reader.terms(tindex.createTerm(termValue));- setTerm();+ Terms terms = MultiFields.getTerms(reader, tindex.field);+ if (terms != null) {+ tenum = terms.iterator();+ tenum.seek(termValue);+ setTerm();+ }}- public TermDocs getTermDocs() throws IOException {- if (termDocs==null) termDocs = reader.termDocs(t);- else termDocs.seek(t);- return termDocs;+ @Override+ public Comparator<BytesRef> getComparator() throws IOException {+ return tenum.getComparator();}- protected boolean setTerm() {- t = tenum.term();- if (t==null- || t.field() != tindex.fterm.field() // intern'd compare- || (tindex.prefix != null && !t.text().startsWith(tindex.prefix,0)) )- {- t = null;- return false;- }- return true;+ public DocsEnum getDocsEnum() throws IOException {+ docsEnum = tenum.docs(MultiFields.getDeletedDocs(reader), docsEnum);+ return docsEnum;}+ protected BytesRef setTerm() throws IOException {+ termText = tenum.term();+ if (tindex.prefix != null && !termText.startsWith(tindex.prefix)) {+ termText = null;+ }+ return termText;+ }- public boolean next() throws IOException {+ @Override+ public BytesRef next() throws IOException {pos++;- boolean b = tenum.next();- if (!b) {- t = null;- return false;+ if (tenum.next() == null) {+ termText = null;+ return null;}return setTerm(); // this is extra work if we know we are in bounds...}- public Term term() {- return t;+ @Override+ public BytesRef term() {+ return termText;}+ @Overridepublic int docFreq() {return tenum.docFreq();}- public void close() throws IOException {- if (tenum!=null) tenum.close();- }+ public BytesRef skipTo(BytesRef target) throws IOException {- public boolean skipTo(String target) throws IOException {- return skipTo(tindex.fterm.createTerm(target));- }-- public boolean skipTo(Term target) throws IOException {// already here- if (t != null && t.equals(target)) return true;+ if (termText != null && termText.equals(target)) return termText;++ if (tenum == null) {+ return null;+ }- int startIdx = Arrays.binarySearch(tindex.index,target.text());+ int startIdx = Arrays.binarySearch(tindex.index,target);if (startIdx >= 0) {// we hit the term exactly... lucky us!- if (tenum != null) tenum.close();- tenum = reader.terms(target);+ TermsEnum.SeekStatus seekStatus = tenum.seek(target);+ assert seekStatus == TermsEnum.SeekStatus.FOUND;pos = startIdx << tindex.intervalBits;return setTerm();}// we didn't hit the term exactlystartIdx=-startIdx-1;-+if (startIdx == 0) {// our target occurs *before* the first term- if (tenum != null) tenum.close();- tenum = reader.terms(target);+ TermsEnum.SeekStatus seekStatus = tenum.seek(target);+ assert seekStatus == TermsEnum.SeekStatus.NOT_FOUND;pos = 0;return setTerm();}@@ -956,53 +979,81 @@ class NumberedTermEnum extends TermEnum {// back up to the start of the blockstartIdx--;- if ((pos >> tindex.intervalBits) == startIdx && t != null && t.text().compareTo(target.text())<=0) {+ if ((pos >> tindex.intervalBits) == startIdx && termText != null && termText.compareTo(target)<=0) {// we are already in the right block and the current term is before the term we want,// so we don't need to seek.} else {// seek to the right block- if (tenum != null) tenum.close();- tenum = reader.terms(target.createTerm(tindex.index[startIdx]));+ TermsEnum.SeekStatus seekStatus = tenum.seek(tindex.index[startIdx]);+ assert seekStatus == TermsEnum.SeekStatus.FOUND;pos = startIdx << tindex.intervalBits;- setTerm(); // should be true since it's in the index+ setTerm(); // should be non-null since it's in the index}-- while (t != null && t.text().compareTo(target.text()) < 0) {+ while (termText != null && termText.compareTo(target) < 0) {next();}- return t != null;+ return termText;}-- public boolean skipTo(int termNumber) throws IOException {+ public BytesRef skipTo(int termNumber) throws IOException {int delta = termNumber - pos;if (delta < 0 || delta > tindex.interval || tenum==null) {int idx = termNumber >>> tindex.intervalBits;- String base = tindex.index[idx];+ BytesRef base = tindex.index[idx];pos = idx << tindex.intervalBits;delta = termNumber - pos;- if (tenum != null) tenum.close();- tenum = reader.terms(tindex.createTerm(base));+ TermsEnum.SeekStatus seekStatus = tenum.seek(base);+ assert seekStatus == TermsEnum.SeekStatus.FOUND;}while (--delta >= 0) {- boolean b = tenum.next();- if (b==false) {- t = null;- return false;+ BytesRef br = tenum.next();+ if (br == null) {+ termText = null;+ return null;}++pos;}return setTerm();}+ protected void close() throws IOException {+ // no-op, needed so the anon subclass that does indexing+ // can build its index+ }+/** The current term number, starting at 0.* Only valid if the previous call to next() or skipTo() returned true.*/public int getTermNumber() {return pos;}++ @Override+ public long ord() {+ throw new UnsupportedOperationException();+ }++ @Override+ public SeekStatus seek(long ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public DocsEnum docs(Bits skipDocs, DocsEnum reuse) {+ throw new UnsupportedOperationException();+ }++ @Override+ public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse) {+ throw new UnsupportedOperationException();+ }++ @Override+ public SeekStatus seek(BytesRef target, boolean useCache) {+ throw new UnsupportedOperationException();+ }}@@ -1018,9 +1069,9 @@ class TermIndex {final static int intervalMask = 0xffffffff >>> (32-intervalBits);final static int interval = 1 << intervalBits;- final Term fterm; // prototype to be used in term construction w/o String.intern overhead- final String prefix;- String[] index;+ final String field;+ final BytesRef prefix;+ BytesRef[] index;int nTerms;long sizeOfStrings;@@ -1029,16 +1080,12 @@ class TermIndex {}TermIndex(String field, String prefix) {- this.fterm = new Term(field, "");- this.prefix = prefix;- }-- Term createTerm(String termVal) {- return fterm.createTerm(termVal);+ this.field = field;+ this.prefix = prefix == null ? null : new BytesRef(prefix);}- NumberedTermEnum getEnumerator(IndexReader reader, int termNumber) throws IOException {- NumberedTermEnum te = new NumberedTermEnum(reader, this);+ NumberedTermsEnum getEnumerator(IndexReader reader, int termNumber) throws IOException {+ NumberedTermsEnum te = new NumberedTermsEnum(reader, this);te.skipTo(termNumber);return te;}@@ -1047,38 +1094,37 @@ class TermIndex {with next() to fully traverse all of the terms so the indexwill be built.*/- NumberedTermEnum getEnumerator(IndexReader reader) throws IOException {- if (index==null) return new NumberedTermEnum(reader,this, prefix==null?"":prefix, 0) {- ArrayList<String> lst;-- protected boolean setTerm() {- boolean b = super.setTerm();- if (b && (pos & intervalMask)==0) {- String text = term().text();- sizeOfStrings += text.length() << 1;+ NumberedTermsEnum getEnumerator(IndexReader reader) throws IOException {+ if (index==null) return new NumberedTermsEnum(reader,this, prefix==null?new BytesRef():prefix, 0) {+ ArrayList<BytesRef> lst;++ protected BytesRef setTerm() throws IOException {+ BytesRef br = super.setTerm();+ if (br != null && (pos & intervalMask)==0) {+ sizeOfStrings += br.length;if (lst==null) {- lst = new ArrayList<String>();+ lst = new ArrayList<BytesRef>();}- lst.add(text);+ lst.add(new BytesRef(br));}- return b;+ return br;}- public boolean skipTo(Term target) throws IOException {+ public BytesRef skipTo(Term target) throws IOException {throw new UnsupportedOperationException();}- public boolean skipTo(int termNumber) throws IOException {+ public BytesRef skipTo(int termNumber) throws IOException {throw new UnsupportedOperationException();}public void close() throws IOException {nTerms=pos;super.close();- index = lst!=null ? lst.toArray(new String[lst.size()]) : new String[0];+ index = lst!=null ? lst.toArray(new BytesRef[lst.size()]) : new BytesRef[0];}};- else return new NumberedTermEnum(reader,this,"",0);+ else return new NumberedTermsEnum(reader,this,new BytesRef(),0);}diff --git a/solr/src/java/org/apache/solr/search/SolrIndexReader.java b/solr/src/java/org/apache/solr/search/SolrIndexReader.javaindex 1e9910d851b..93a592f2da2 100755--- a/solr/src/java/org/apache/solr/search/SolrIndexReader.java+++ b/solr/src/java/org/apache/solr/search/SolrIndexReader.java@@ -484,11 +484,6 @@ public class SolrIndexReader extends FilterIndexReader {in.setNorm(doc, field, value);}- @Override- public TermPositions termPositions(Term term) throws IOException {- return in.termPositions(term);- }-@Overridepublic void undeleteAll() throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {in.undeleteAll();diff --git a/solr/src/java/org/apache/solr/search/function/FileFloatSource.java b/solr/src/java/org/apache/solr/search/function/FileFloatSource.javaindex 7f28e53db19..c4ffe271f2a 100755--- a/solr/src/java/org/apache/solr/search/function/FileFloatSource.java+++ b/solr/src/java/org/apache/solr/search/function/FileFloatSource.java@@ -17,10 +17,12 @@package org.apache.solr.search.function;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.index.Term;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;import org.apache.solr.core.SolrCore;import org.apache.solr.schema.SchemaField;import org.apache.solr.schema.FieldType;@@ -220,29 +222,22 @@ public class FileFloatSource extends ValueSource {int notFoundCount=0;int otherErrors=0;- TermDocs termDocs = null;- Term protoTerm = new Term(idName, "");- TermEnum termEnum = null;// Number of times to try termEnum.next() before resorting to skipint numTimesNext = 10;char delimiter='=';- String termVal;- boolean hasNext=true;- String prevKey="";- String lastVal="\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF";+ BytesRef lastVal=new BytesRef("\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF");+ BytesRef internalKey = new BytesRef();+ BytesRef prevKey=new BytesRef();+ BytesRef tmp;try {- termDocs = reader.termDocs();- termEnum = reader.terms(protoTerm);- Term t = termEnum.term();- if (t != null && t.field() == idName) { // intern'd comparison- termVal = t.text();- } else {- termVal = lastVal;- }-+ TermsEnum termsEnum = MultiFields.getTerms(reader, idName).iterator();+ DocsEnum docsEnum = null;+ BytesRef t = termsEnum.next();+ if (t==null) t=lastVal;+ final Bits delDocs = MultiFields.getDeletedDocs(reader);for (String line; (line=r.readLine())!=null;) {int delimIndex = line.indexOf(delimiter);@@ -258,7 +253,9 @@ public class FileFloatSource extends ValueSource {String key = line.substring(0, delimIndex);String val = line.substring(delimIndex+1, endIndex);- String internalKey = idType.toInternal(key);+ tmp = prevKey; prevKey=internalKey; internalKey=tmp;+ idType.readableToIndexed(key, internalKey);+float fval;try {fval=Float.parseFloat(val);@@ -274,16 +271,16 @@ public class FileFloatSource extends ValueSource {if (sorted) {// make sure this key is greater than the previous keysorted = internalKey.compareTo(prevKey) >= 0;- prevKey = internalKey;if (sorted) {int countNext = 0;for(;;) {- int cmp = internalKey.compareTo(termVal);+ int cmp = internalKey.compareTo(t);if (cmp == 0) {- termDocs.seek(termEnum);- while (termDocs.next()) {- vals[termDocs.doc()] = fval;+ docsEnum = termsEnum.docs(delDocs, docsEnum);+ int doc;+ while ((doc = docsEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {+ vals[doc] = fval;}break;} else if (cmp < 0) {@@ -301,32 +298,26 @@ public class FileFloatSource extends ValueSource {// so the best thing is to simply ask the reader for a new termEnum(target)// if we really need to skip.if (++countNext > numTimesNext) {- termEnum = reader.terms(protoTerm.createTerm(internalKey));- t = termEnum.term();+ termsEnum.seek(internalKey);+ t = termsEnum.term();} else {- hasNext = termEnum.next();- t = hasNext ? termEnum.term() : null;+ t = termsEnum.next();}- if (t != null && t.field() == idName) { // intern'd comparison- termVal = t.text();- } else {- termVal = lastVal;- }+ if (t==null) t = lastVal;}} // end for(;;)}}if (!sorted) {- termEnum = reader.terms(protoTerm.createTerm(internalKey));- t = termEnum.term();- if (t != null && t.field() == idName // intern'd comparison- && internalKey.equals(t.text()))- {- termDocs.seek (termEnum);- while (termDocs.next()) {- vals[termDocs.doc()] = fval;+ TermsEnum.SeekStatus result = termsEnum.seek(internalKey);+ t = termsEnum.term();+ if (result == TermsEnum.SeekStatus.FOUND) {+ docsEnum = termsEnum.docs(delDocs, docsEnum);+ int doc;+ while ((doc = docsEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {+ vals[doc] = fval;}} else {if (notFoundCount<10) { // collect first 10 not found for logging@@ -342,8 +333,6 @@ public class FileFloatSource extends ValueSource {} finally {// swallow exceptions on close so we don't override any// exceptions that happened in the loop- if (termDocs!=null) try{termDocs.close();}catch(Exception e){}- if (termEnum!=null) try{termEnum.close();}catch(Exception e){}try{r.close();}catch(Exception e){}}diff --git a/solr/src/java/org/apache/solr/update/DirectUpdateHandler.java b/solr/src/java/org/apache/solr/update/DirectUpdateHandler.javaindex 35af727089b..9a3f8e0d995 100644--- a/solr/src/java/org/apache/solr/update/DirectUpdateHandler.java+++ b/solr/src/java/org/apache/solr/update/DirectUpdateHandler.java@@ -22,10 +22,12 @@ package org.apache.solr.update;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.DocsEnum;import org.apache.lucene.index.Term;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.document.Document;import org.apache.lucene.search.Query;+import org.apache.lucene.util.BytesRef;import java.util.HashSet;import java.util.concurrent.Future;@@ -35,7 +37,6 @@ import java.net.URL;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.search.QueryParsing;-import org.apache.solr.update.UpdateHandler;import org.apache.solr.common.SolrException;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;@@ -113,15 +114,16 @@ public class DirectUpdateHandler extends UpdateHandler {closeWriter();openSearcher();IndexReader ir = searcher.getReader();- TermDocs tdocs = null;- boolean exists=false;- try {- tdocs = ir.termDocs(idTerm(indexedId));- if (tdocs.next()) exists=true;- } finally {- try { if (tdocs != null) tdocs.close(); } catch (Exception e) {}+ Term idTerm = idTerm(indexedId);+ DocsEnum tdocs = MultiFields.getTermDocsEnum(ir,+ MultiFields.getDeletedDocs(ir),+ idTerm.field(),+ new BytesRef(idTerm.text()));+ if (tdocs != null) {+ return tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS;+ } else {+ return false;}- return exists;}@@ -130,16 +132,11 @@ public class DirectUpdateHandler extends UpdateHandler {closeWriter(); openSearcher();IndexReader ir = searcher.getReader();- TermDocs tdocs = null;int num=0;- try {- Term term = new Term(idField.getName(), indexedId);- num = ir.deleteDocuments(term);- if (core.log.isTraceEnabled()) {- core.log.trace( core.getLogId()+"deleted " + num + " docs matching id " + idFieldType.indexedToReadable(indexedId));- }- } finally {- try { if (tdocs != null) tdocs.close(); } catch (Exception e) {}+ Term term = new Term(idField.getName(), indexedId);+ num = ir.deleteDocuments(term);+ if (core.log.isTraceEnabled()) {+ core.log.trace( core.getLogId()+"deleted " + num + " docs matching id " + idFieldType.indexedToReadable(indexedId));}return num;}@@ -265,8 +262,6 @@ public class DirectUpdateHandler extends UpdateHandler {SolrException.log(log,e);}}-- return;}/**diff --git a/solr/src/java/org/apache/solr/util/HighFrequencyDictionary.java b/solr/src/java/org/apache/solr/util/HighFrequencyDictionary.javaindex f66f4f9eab7..fe88b460151 100644--- a/solr/src/java/org/apache/solr/util/HighFrequencyDictionary.java+++ b/solr/src/java/org/apache/solr/util/HighFrequencyDictionary.java@@ -21,19 +21,18 @@ import java.io.IOException;import java.util.Iterator;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.MultiFields;import org.apache.lucene.search.spell.Dictionary;import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.BytesRef;/*** HighFrequencyDictionary: terms taken from the given field* of a Lucene index, which appear in a number of documents* above a given threshold.*- * When using IndexReader.terms(Term) the code must not call next() on TermEnum- * as the first call to TermEnum, see: http://issues.apache.org/jira/browse/LUCENE-6- ** Threshold is a value in [0..1] representing the minimum* number of documents (of the total) where a term should appear.*@@ -55,41 +54,34 @@ public class HighFrequencyDictionary implements Dictionary {}final class HighFrequencyIterator implements Iterator {- private TermEnum termEnum;- private Term actualTerm;+ private TermsEnum termsEnum;+ private BytesRef actualTerm;private boolean hasNextCalled;private int minNumDocs;HighFrequencyIterator() {try {- termEnum = reader.terms(new Term(field, ""));+ Terms terms = MultiFields.getTerms(reader, field);+ if (terms != null) {+ termsEnum = terms.iterator();+ }minNumDocs = (int)(thresh * (float)reader.numDocs());} catch (IOException e) {throw new RuntimeException(e);}}- private boolean isFrequent(Term term) {- try {- return reader.docFreq(term) >= minNumDocs;- } catch (IOException e) {- throw new RuntimeException(e);- }+ private boolean isFrequent(int freq) {+ return freq >= minNumDocs;}public Object next() {- if (!hasNextCalled) {- hasNext();+ if (!hasNextCalled && !hasNext()) {+ return null;}hasNextCalled = false;- try {- termEnum.next();- } catch (IOException e) {- throw new RuntimeException(e);- }-- return (actualTerm != null) ? actualTerm.text() : null;+ return (actualTerm != null) ? actualTerm.utf8ToString() : null;}public boolean hasNext() {@@ -98,35 +90,28 @@ public class HighFrequencyDictionary implements Dictionary {}hasNextCalled = true;- do {- actualTerm = termEnum.term();+ if (termsEnum == null) {+ return false;+ }- // if there are no words return false- if (actualTerm == null) {- return false;- }+ while(true) {- String currentField = actualTerm.field();+ try {+ actualTerm = termsEnum.next();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }- // if the next word doesn't have the same field return false- if (currentField != field) { // intern'd comparison- actualTerm = null;+ // if there are no words return false+ if (actualTerm == null) {return false;}// got a valid term, does it pass the threshold?- if (isFrequent(actualTerm)) {+ if (isFrequent(termsEnum.docFreq())) {return true;}-- // term not up to threshold- try {- termEnum.next();- } catch (IOException e) {- throw new RuntimeException(e);- }-- } while (true);+ }}public void remove() {diff --git a/solr/src/test/org/apache/solr/request/TestFaceting.java b/solr/src/test/org/apache/solr/request/TestFaceting.javaindex 6c761a75dc5..91b26d75f68 100755--- a/solr/src/test/org/apache/solr/request/TestFaceting.java+++ b/solr/src/test/org/apache/solr/request/TestFaceting.java@@ -18,6 +18,7 @@package org.apache.solr.request;import org.apache.lucene.index.Term;+import org.apache.lucene.util.BytesRef;import org.apache.solr.SolrTestCaseJ4;import org.junit.After;import org.junit.BeforeClass;@@ -68,7 +69,7 @@ public class TestFaceting extends SolrTestCaseJ4 {req = lrf.makeRequest("q","*:*");TermIndex ti = new TermIndex(proto.field());- NumberedTermEnum te = ti.getEnumerator(req.getSearcher().getReader());+ NumberedTermsEnum te = ti.getEnumerator(req.getSearcher().getReader());// iterate through firstwhile(te.term() != null) te.next();@@ -82,11 +83,11 @@ public class TestFaceting extends SolrTestCaseJ4 {for (int i=0; i<size*2+10; i++) {int rnum = r.nextInt(size+2);String s = t(rnum);- boolean b = te.skipTo(proto.createTerm(s));- assertEquals(b, rnum < size);+ BytesRef br = te.skipTo(new BytesRef(s));+ assertEquals(br != null, rnum < size);if (rnum < size) {assertEquals(rnum, te.pos);- assertEquals(s, te.term().text());+ assertEquals(s, te.term().utf8ToString());} else {assertEquals(null, te.term());assertEquals(size, te.getTermNumber());@@ -94,10 +95,10 @@ public class TestFaceting extends SolrTestCaseJ4 {}// test seeking before term- assertEquals(size>0, te.skipTo(proto.createTerm("000")));+ assertEquals(size>0, te.skipTo(new BytesRef("000")) != null);assertEquals(0, te.getTermNumber());if (size>0) {- assertEquals(t(0), te.term().text());+ assertEquals(t(0), te.term().utf8ToString());} else {assertEquals(null, te.term());}@@ -107,10 +108,10 @@ public class TestFaceting extends SolrTestCaseJ4 {for (int i=0; i<size*2+10; i++) {int rnum = r.nextInt(size);String s = t(rnum);- boolean b = te.skipTo(rnum);- assertEquals(true, b);+ BytesRef br = te.skipTo(rnum);+ assertNotNull(br);assertEquals(rnum, te.pos);- assertEquals(s, te.term().text());+ assertEquals(s, te.term().utf8ToString());}}}@@ -204,7 +205,6 @@ public class TestFaceting extends SolrTestCaseJ4 {sb.append(t(i));sb.append(' ');}- String many_ws = sb.toString();int i1=1000000;diff --git a/solr/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java b/solr/src/test/org/apache/solr/update/DirectUpdateHandlerTest.javaindex 65a3d33c996..5920553c2ae 100644--- a/solr/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java+++ b/solr/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java@@ -17,22 +17,13 @@package org.apache.solr.update;-import java.io.IOException;-import java.util.ArrayList;import java.util.HashMap;-import java.util.HashSet;-import java.util.List;import java.util.Map;-import java.util.Set;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.Index;import org.apache.lucene.document.Field.Store;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.SegmentReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.MapSolrParams;@@ -40,9 +31,7 @@ import org.apache.solr.core.SolrCore;import org.apache.solr.request.LocalSolrQueryRequest;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.search.SolrIndexReader;-import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.util.AbstractSolrTestCase;-import org.apache.solr.util.RefCounted;/***