Apache Lucene open-source search software
LUCENE-2380: cutover to shared byte[] (BytesRef) instead of String, in FieldCache
Michael McCandless46acc0cbb32c
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex bc85c23fbf0..9da70938c79 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -73,6 +73,13 @@ Changes in backwards compatibility policynot unicode code units. For example, a Wildcard "?" represents any unicodecharacter. Furthermore, the rest of the automaton package and RegexpQuery usetrue Unicode codepoint representation. (Robert Muir, Mike McCandless)++* LUCENE-2380: The String-based FieldCache methods (getStrings,+ getStringIndex) have been replaced with BytesRef-based equivalents+ (getTerms, getTermsIndex). Also, the sort values (returned in+ FieldDoc.fields) when sorting by SortField.STRING or+ SortField.STRING_VAL are now BytesRef instances. See MIGRATE.txt+ for more details. (Mike McCandless)* LUCENE-2480: Though not a change in backwards compatibility policy, pre-3.0indexes are no longer supported. You should upgrade to 3.x first, then run@@ -611,6 +618,11 @@ Optimizations* LUCENE-2360: Small speedup to recycling of reused per-doc RAM inIndexWriter (Robert Muir, Mike McCandless)+* LUCENE-2380: The terms field cache methods (getTerms,+ getTermsIndex), which replace the older String equivalents+ (getStrings, getStringIndex), consume quite a bit less RAM in most+ cases. (Mike McCandless)+Build* LUCENE-2124: Moved the JDK-based collation support from contrib/collationdiff --git a/lucene/MIGRATE.txt b/lucene/MIGRATE.txtnew file mode 100644index 00000000000..67cb13a77f5--- /dev/null+++ b/lucene/MIGRATE.txt@@ -0,0 +1,45 @@++LUCENE-2380++ * The field values returned when sorting by SortField.STRING are now+ BytesRef. You can call value.utf8ToString() to convert back to+ string, if necessary.++ * In FieldCache, getStrings (returning String[]) has been replaced+ with getTerms (returning a FieldCache.DocTerms instance).+ DocTerms provides a getTerm method, taking a docID and a BytesRef+ to fill (which must not be null), and it fills it in with the+ reference to the bytes for that term.++ If you had code like this before:++ String[] values = FieldCache.DEFAULT.getStrings(reader, field);+ ...+ String aValue = values[docID];++ you can do this instead:++ DocTerms values = FieldCache.DEFAULT.getTerms(reader, field);+ ...+ BytesRef term = new BytesRef();+ String aValue = values.get(docID, term).utf8ToString();++ Note however that it can be costly to convert to String, so it's+ better to work directly with the BytesRef.++ * StringComparatorLocale is now more CPU costly than it was before+ (it was already very CPU costly since it does not compare using+ indexed collation keys; use CollationKeyFilter for better+ performance), since it converts BytesRef -> String on the fly.+ Also, the field values returned when sorting by SortField.STRING+ are now BytesRef.++ * FieldComparator.StringOrdValComparator has been renamed to+ TermOrdValComparator, and now uses BytesRef for its values.+ Likewise for StringValComparator, renamed to TermValComparator.+ This means when sorting by SortField.STRING or+ SortField.STRING_VAL (or directly invoking these comparators) the+ values returned in the FieldDoc.fields array will be BytesRef not+ String. You can call the .utf8ToString() method on the BytesRef+ instances, if necessary.+diff --git a/lucene/contrib/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java b/lucene/contrib/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.javaindex 22d0c2fb8fa..6dc973ca73f 100755--- a/lucene/contrib/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java+++ b/lucene/contrib/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java@@ -48,9 +48,10 @@ import org.apache.lucene.index.LogMergePolicy;import org.apache.lucene.index.SerialMergeScheduler;import org.apache.lucene.index.LogDocMergePolicy;import org.apache.lucene.index.TermFreqVector;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.store.Directory;-import org.apache.lucene.search.FieldCache.StringIndex;+import org.apache.lucene.search.FieldCache.DocTermsIndex;import org.apache.lucene.search.FieldCache;/**@@ -326,11 +327,12 @@ public class TestPerfTasksLogic extends BenchmarkTestCase {Benchmark benchmark = execBenchmark(algLines);IndexReader r = IndexReader.open(benchmark.getRunData().getDirectory(), true);- StringIndex idx = FieldCache.DEFAULT.getStringIndex(r, "country");+ DocTermsIndex idx = FieldCache.DEFAULT.getTermsIndex(r, "country");final int maxDoc = r.maxDoc();assertEquals(1000, maxDoc);+ BytesRef br = new BytesRef();for(int i=0;i<1000;i++) {- assertNotNull("doc " + i + " has null country", idx.lookup[idx.order[i]]);+ assertNotNull("doc " + i + " has null country", idx.getTerm(i, br));}r.close();}diff --git a/lucene/contrib/spatial/src/java/org/apache/lucene/spatial/geohash/GeoHashDistanceFilter.java b/lucene/contrib/spatial/src/java/org/apache/lucene/spatial/geohash/GeoHashDistanceFilter.javaindex 0bbb8ac002c..6faaaad04dc 100644--- a/lucene/contrib/spatial/src/java/org/apache/lucene/spatial/geohash/GeoHashDistanceFilter.java+++ b/lucene/contrib/spatial/src/java/org/apache/lucene/spatial/geohash/GeoHashDistanceFilter.java@@ -21,9 +21,11 @@ import java.io.IOException;import org.apache.lucene.index.IndexReader;import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.FieldCache.DocTerms;import org.apache.lucene.search.Filter;import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.FilteredDocIdSet;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.spatial.tier.DistanceFilter;import org.apache.lucene.spatial.tier.DistanceUtils;@@ -62,7 +64,8 @@ public class GeoHashDistanceFilter extends DistanceFilter {@Overridepublic DocIdSet getDocIdSet(IndexReader reader) throws IOException {- final String[] geoHashValues = FieldCache.DEFAULT.getStrings(reader, geoHashField);+ final DocTerms geoHashValues = FieldCache.DEFAULT.getTerms(reader, geoHashField);+ final BytesRef br = new BytesRef();final int docBase = nextDocBase;nextDocBase += reader.maxDoc();@@ -70,8 +73,10 @@ public class GeoHashDistanceFilter extends DistanceFilter {return new FilteredDocIdSet(startingFilter.getDocIdSet(reader)) {@Overridepublic boolean match(int doc) {-- String geoHash = geoHashValues[doc];++ // TODO: cutover to BytesRef so we don't have to+ // make String here+ String geoHash = geoHashValues.getTerm(doc, br).utf8ToString();double[] coords = GeoHashUtils.decode(geoHash);double x = coords[0];double y = coords[1];diff --git a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.javaindex 978637f5993..090d66a9fe5 100644--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java@@ -820,7 +820,7 @@ final class DocumentsWriter {boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm)throws CorruptIndexException, IOException {-+// This call is synchronized but fastfinal DocumentsWriterThreadState state = getThreadState(doc, delTerm);@@ -1301,6 +1301,8 @@ final class DocumentsWriter {final static int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1;final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;+ /* if you increase this, you must fix field cache impl for+ * getTerms/getTermsIndex requires <= 32768 */final static int MAX_TERM_LENGTH_UTF8 = BYTE_BLOCK_SIZE-2;private class ByteBlockAllocator extends ByteBlockPool.Allocator {diff --git a/lucene/src/java/org/apache/lucene/index/codecs/standard/PagedBytes.java b/lucene/src/java/org/apache/lucene/index/codecs/standard/PagedBytes.javadeleted file mode 100644index b3ddc986ef5..00000000000--- a/lucene/src/java/org/apache/lucene/index/codecs/standard/PagedBytes.java+++ /dev/null@@ -1,129 +0,0 @@-package org.apache.lucene.index.codecs.standard;--/**- * 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.util.CloseableThreadLocal;-import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.ArrayUtil;-import org.apache.lucene.store.IndexInput;--import java.util.List;-import java.util.ArrayList;-import java.io.Closeable;-import java.io.IOException;--/** Represents a logical byte[] as a series of pages. You- * can write-once into the logical byte[], using copy, and- * then retrieve slices (BytesRef) into it using fill. */-class PagedBytes implements Closeable {- private final List<byte[]> blocks = new ArrayList<byte[]>();- private final int blockSize;- private final int blockBits;- private final int blockMask;- private int upto;- private byte[] currentBlock;- private final CloseableThreadLocal<byte[]> threadBuffers = new CloseableThreadLocal<byte[]>();-- private static final byte[] EMPTY_BYTES = new byte[0];-- /** 1<<blockBits must be bigger than biggest single- * BytesRef slice that will be pulled */- public PagedBytes(int blockBits) {- this.blockSize = 1 << blockBits;- this.blockBits = blockBits;- blockMask = blockSize-1;- upto = blockSize;- }-- /** Read this many bytes from in */- public void copy(IndexInput in, long byteCount) throws IOException {- while (byteCount > 0) {- int left = blockSize - upto;- if (left == 0) {- if (currentBlock != null) {- blocks.add(currentBlock);- }- currentBlock = new byte[blockSize];- upto = 0;- left = blockSize;- }- if (left < byteCount) {- in.readBytes(currentBlock, upto, left, false);- upto = blockSize;- byteCount -= left;- } else {- in.readBytes(currentBlock, upto, (int) byteCount, false);- upto += byteCount;- byteCount = 0;- }- }- }-- /** Commits final byte[], trimming it if necessary. */- public void finish() {- if (upto < blockSize) {- final byte[] newBlock = new byte[upto];- System.arraycopy(currentBlock, 0, newBlock, 0, upto);- currentBlock = newBlock;- }- if (currentBlock == null) {- currentBlock = EMPTY_BYTES;- }- blocks.add(currentBlock);- currentBlock = null;- }-- public long getPointer() {- if (currentBlock == null) {- return 0;- } else {- return (blocks.size() * ((long) blockSize)) + upto;- }- }-- /** Get a slice out of the byte array. */- public void fill(BytesRef b, long start, int length) {- assert length >= 0: "length=" + length;- final int index = (int) (start >> blockBits);- final int offset = (int) (start & blockMask);- b.length = length;- if (blockSize - offset >= length) {- // Within block- b.bytes = blocks.get(index);- b.offset = offset;- } else {- // Split- byte[] buffer = threadBuffers.get();- if (buffer == null) {- buffer = new byte[length];- threadBuffers.set(buffer);- } else if (buffer.length < length) {- buffer = ArrayUtil.grow(buffer, length);- threadBuffers.set(buffer);- }- b.bytes = buffer;- b.offset = 0;- System.arraycopy(blocks.get(index), offset, buffer, 0, blockSize-offset);- System.arraycopy(blocks.get(1+index), 0, buffer, blockSize-offset, length-(blockSize-offset));- }- }-- public void close() {- threadBuffers.close();- }-}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/standard/SimpleStandardTermsIndexReader.java b/lucene/src/java/org/apache/lucene/index/codecs/standard/SimpleStandardTermsIndexReader.javaindex 266cccf8c11..4dde4f1d166 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/standard/SimpleStandardTermsIndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/standard/SimpleStandardTermsIndexReader.java@@ -24,6 +24,7 @@ import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.SegmentInfo;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CodecUtil;+import org.apache.lucene.util.PagedBytes;import org.apache.lucene.util.packed.PackedInts;import java.util.HashMap;@@ -82,6 +83,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {// all fields share this single logical byte[]private final PagedBytes termBytes = new PagedBytes(PAGED_BYTES_BITS);+ private PagedBytes.Reader termBytesReader;final HashMap<FieldInfo,FieldIndexReader> fields = new HashMap<FieldInfo,FieldIndexReader>();@@ -135,7 +137,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {if (success) {indexLoaded = true;}- termBytes.finish();+ termBytesReader = termBytes.freeze();} else {this.in = in;}@@ -347,7 +349,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {private void fillResult(int idx, TermsIndexResult result) {final long offset = termOffsets.get(idx);final int length = (int) (termOffsets.get(1+idx) - offset);- termBytes.fill(result.term, termBytesStart + offset, length);+ termBytesReader.fill(result.term, termBytesStart + offset, length);result.position = idx * totalIndexInterval;result.offset = termsStart + termsDictOffsets.get(idx);}@@ -361,7 +363,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {final long offset = termOffsets.get(mid);final int length = (int) (termOffsets.get(1+mid) - offset);- termBytes.fill(result.term, termBytesStart + offset, length);+ termBytesReader.fill(result.term, termBytesStart + offset, length);int delta = termComp.compare(term, result.term);if (delta < 0) {@@ -382,7 +384,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {final long offset = termOffsets.get(hi);final int length = (int) (termOffsets.get(1+hi) - offset);- termBytes.fill(result.term, termBytesStart + offset, length);+ termBytesReader.fill(result.term, termBytesStart + offset, length);result.position = hi*totalIndexInterval;result.offset = termsStart + termsDictOffsets.get(hi);@@ -411,7 +413,7 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {indexLoaded = true;in.close();- termBytes.finish();+ termBytesReader = termBytes.freeze();}}@@ -438,5 +440,8 @@ public class SimpleStandardTermsIndexReader extends StandardTermsIndexReader {if (in != null && !indexLoaded) {in.close();}+ if (termBytesReader != null) {+ termBytesReader.close();+ }}}diff --git a/lucene/src/java/org/apache/lucene/search/FieldCache.java b/lucene/src/java/org/apache/lucene/search/FieldCache.javaindex 3f09fd8f206..72da0abfdf9 100644--- a/lucene/src/java/org/apache/lucene/search/FieldCache.java+++ b/lucene/src/java/org/apache/lucene/search/FieldCache.java@@ -44,50 +44,6 @@ public interface FieldCache {Object value;}- /** Indicator for StringIndex values in the cache. */- // NOTE: the value assigned to this constant must not be- // the same as any of those in SortField!!- public static final int STRING_INDEX = -1;--- /** Expert: Stores term text values and document ordering data. */- public static class StringIndex {-- public int binarySearchLookup(String key) {- // this special case is the reason that Arrays.binarySearch() isn't useful.- if (key == null)- return 0;-- int low = 1;- int high = lookup.length-1;-- while (low <= high) {- int mid = (low + high) >>> 1;- int cmp = lookup[mid].compareTo(key);-- if (cmp < 0)- low = mid + 1;- else if (cmp > 0)- high = mid - 1;- else- return mid; // key found- }- return -(low + 1); // key not found.- }-- /** All the term values, in natural order. */- public final String[] lookup;-- /** For each document, an index into the lookup array. */- public final int[] order;-- /** Creates one of these objects */- public StringIndex (int[] values, String[] lookup) {- this.order = values;- this.lookup = lookup;- }- }-/*** Marker interface as super-interface to all parsers. It* is used to specify a custom parser to {@link@@ -490,28 +446,112 @@ public interface FieldCache {public double[] getDoubles(IndexReader reader, String field, DoubleParser parser)throws IOException;+ /** Returned by {@link #getTerms} */+ public abstract static class DocTerms {+ /** The BytesRef argument must not be null; the method+ * returns the same BytesRef, or an empty (length=0)+ * BytesRef if the doc did not have this field or was+ * deleted. */+ public abstract BytesRef getTerm(int docID, BytesRef ret);++ /** Returns true if this doc has this field and is not+ * deleted. */+ public abstract boolean exists(int docID);++ /** Number of documents */+ public abstract int size();+ }+/** Checks the internal cache for an appropriate entry, and if none- * is found, reads the term values in <code>field</code> and returns an array- * of size <code>reader.maxDoc()</code> containing the value each document- * has in the given field.+ * is found, reads the term values in <code>field</code>+ * and returns a {@link DocTerms} instance, providing a+ * method to retrieve the term (as a BytesRef) per document.* @param reader Used to get field values.* @param field Which field contains the strings.* @return The values in the given field for each document.* @throws IOException If any error occurs.*/- public String[] getStrings (IndexReader reader, String field)+ public DocTerms getTerms (IndexReader reader, String field)+ throws IOException;++ /** Expert: just like {@link #getTerms(IndexReader,String)},+ * but you can specify whether more RAM should be consumed in exchange for+ * faster lookups (default is "true"). Note that the+ * first call for a given reader and field "wins",+ * subsequent calls will share the same cache entry. */+ public DocTerms getTerms (IndexReader reader, String field, boolean fasterButMoreRAM)throws IOException;+ /** Returned by {@link #getTermsIndex} */+ public abstract static class DocTermsIndex {++ public int binarySearchLookup(BytesRef key, BytesRef spare) {+ // this special case is the reason that Arrays.binarySearch() isn't useful.+ if (key == null)+ return 0;++ int low = 1;+ int high = numOrd()-1;++ while (low <= high) {+ int mid = (low + high) >>> 1;+ int cmp = lookup(mid, spare).compareTo(key);++ if (cmp < 0)+ low = mid + 1;+ else if (cmp > 0)+ high = mid - 1;+ else+ return mid; // key found+ }+ return -(low + 1); // key not found.+ }++ /** The BytesRef argument must not be null; the method+ * returns the same BytesRef, or an empty (length=0)+ * BytesRef if this ord is the null ord (0). */+ public abstract BytesRef lookup(int ord, BytesRef reuse);++ /** Convenience method, to lookup the Term for a doc.+ * If this doc is deleted or did not have this field,+ * this will return an empty (length=0) BytesRef. */+ public BytesRef getTerm(int docID, BytesRef reuse) {+ return lookup(getOrd(docID), reuse);+ }++ /** Returns sort ord for this document. Ord 0 is+ * reserved for docs that are deleted or did not have+ * this field. */+ public abstract int getOrd(int docID);++ /** Returns total unique ord count; this includes +1 for+ * the null ord (always 0). */+ public abstract int numOrd();++ /** Number of documents */+ public abstract int size();+ }+/** Checks the internal cache for an appropriate entry, and if none- * is found reads the term values in <code>field</code> and returns- * an array of them in natural order, along with an array telling- * which element in the term array each document uses.+ * is found, reads the term values in <code>field</code>+ * and returns a {@link DocTerms} instance, providing a+ * method to retrieve the term (as a BytesRef) per document.* @param reader Used to get field values.* @param field Which field contains the strings.- * @return Array of terms and index into the array for each document.+ * @return The values in the given field for each document.* @throws IOException If any error occurs.*/- public StringIndex getStringIndex (IndexReader reader, String field)+ public DocTermsIndex getTermsIndex (IndexReader reader, String field)+ throws IOException;+++ /** Expert: just like {@link+ * #getTermsIndex(IndexReader,String)}, but you can specify+ * whether more RAM should be consumed in exchange for+ * faster lookups (default is "true"). Note that the+ * first call for a given reader and field "wins",+ * subsequent calls will share the same cache entry. */+ public DocTermsIndex getTermsIndex (IndexReader reader, String field, boolean fasterButMoreRAM)throws IOException;/**diff --git a/lucene/src/java/org/apache/lucene/search/FieldCacheImpl.java b/lucene/src/java/org/apache/lucene/search/FieldCacheImpl.javaindex 0cf6becb510..aaaa3af8c9d 100644--- a/lucene/src/java/org/apache/lucene/search/FieldCacheImpl.java+++ b/lucene/src/java/org/apache/lucene/search/FieldCacheImpl.java@@ -30,7 +30,11 @@ import org.apache.lucene.index.DocsEnum;import org.apache.lucene.index.Terms;import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.util.PagedBytes;+import org.apache.lucene.util.packed.PackedInts;+import org.apache.lucene.util.packed.GrowableWriter;import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.Bits;import org.apache.lucene.util.StringHelper;import org.apache.lucene.util.FieldCacheSanityChecker;@@ -57,8 +61,8 @@ class FieldCacheImpl implements FieldCache {caches.put(Float.TYPE, new FloatCache(this));caches.put(Long.TYPE, new LongCache(this));caches.put(Double.TYPE, new DoubleCache(this));- caches.put(String.class, new StringCache(this));- caches.put(StringIndex.class, new StringIndexCache(this));+ caches.put(DocTermsIndex.class, new DocTermsIndexCache(this));+ caches.put(DocTerms.class, new DocTermsCache(this));}public synchronized void purgeAllCaches() {@@ -638,76 +642,222 @@ class FieldCacheImpl implements FieldCache {}}- // inherit javadocs- public String[] getStrings(IndexReader reader, String field)- throws IOException {- return (String[]) caches.get(String.class).get(reader, new Entry(field, (Parser)null));+ private static class DocTermsIndexImpl extends DocTermsIndex {+ private final PagedBytes.Reader bytes;+ private final PackedInts.Reader termOrdToBytesOffset;+ private final PackedInts.Reader docToTermOrd;+ private final int numOrd;++ public DocTermsIndexImpl(PagedBytes.Reader bytes, PackedInts.Reader termOrdToBytesOffset, PackedInts.Reader docToTermOrd, int numOrd) {+ this.bytes = bytes;+ this.docToTermOrd = docToTermOrd;+ this.termOrdToBytesOffset = termOrdToBytesOffset;+ this.numOrd = numOrd;+ }++ @Override+ public int numOrd() {+ return numOrd;+ }++ @Override+ public int getOrd(int docID) {+ return (int) docToTermOrd.get(docID);+ }++ @Override+ public int size() {+ return docToTermOrd.size();+ }++ @Override+ public BytesRef lookup(int ord, BytesRef ret) {+ return bytes.fillUsingLengthPrefix(ret, termOrdToBytesOffset.get(ord));+ }+ }++ private static boolean DEFAULT_FASTER_BUT_MORE_RAM = true;++ public DocTermsIndex getTermsIndex(IndexReader reader, String field) throws IOException {+ return getTermsIndex(reader, field, DEFAULT_FASTER_BUT_MORE_RAM);}- static final class StringCache extends Cache {- StringCache(FieldCache wrapper) {+ public DocTermsIndex getTermsIndex(IndexReader reader, String field, boolean fasterButMoreRAM) throws IOException {+ return (DocTermsIndex) caches.get(DocTermsIndex.class).get(reader, new Entry(field, Boolean.valueOf(fasterButMoreRAM)));+ }++ static class DocTermsIndexCache extends Cache {+ DocTermsIndexCache(FieldCache wrapper) {super(wrapper);}@Overrideprotected Object createValue(IndexReader reader, Entry entryKey)throws IOException {- String field = StringHelper.intern(entryKey.field);- final String[] retArray = new String[reader.maxDoc()];+ String field = StringHelper.intern(entryKey.field);Terms terms = MultiFields.getTerms(reader, field);++ final boolean fasterButMoreRAM = ((Boolean) entryKey.custom).booleanValue();++ final PagedBytes bytes = new PagedBytes(15);++ int startBytesBPV;+ int startTermsBPV;+ int startNumUniqueTerms;++ if (terms != null) {+ // Try for coarse estimate for number of bits; this+ // should be an underestimate most of the time, which+ // is fine -- GrowableWriter will reallocate as needed+ long numUniqueTerms = 0;+ try {+ numUniqueTerms = terms.getUniqueTermCount();+ } catch (UnsupportedOperationException uoe) {+ numUniqueTerms = -1;+ }+ if (numUniqueTerms != -1) {+ startBytesBPV = PackedInts.bitsRequired(numUniqueTerms*4);+ startTermsBPV = PackedInts.bitsRequired(numUniqueTerms);+ if (numUniqueTerms > Integer.MAX_VALUE-1) {+ throw new IllegalStateException("this field has too many (" + numUniqueTerms + ") unique terms");+ }+ startNumUniqueTerms = (int) numUniqueTerms;+ } else {+ startBytesBPV = 1;+ startTermsBPV = 1;+ startNumUniqueTerms = 1;+ }+ } else {+ startBytesBPV = 1;+ startTermsBPV = 1;+ startNumUniqueTerms = 1;+ }++ GrowableWriter termOrdToBytesOffset = new GrowableWriter(startBytesBPV, 1+startNumUniqueTerms, fasterButMoreRAM);+ final GrowableWriter docToTermOrd = new GrowableWriter(startTermsBPV, reader.maxDoc(), false);++ // 0 is reserved for "unset"+ bytes.copyUsingLengthPrefix(new BytesRef());+ int termOrd = 1;+if (terms != null) {final TermsEnum termsEnum = terms.iterator();final Bits delDocs = MultiFields.getDeletedDocs(reader);DocsEnum docs = null;+while(true) {final BytesRef term = termsEnum.next();if (term == null) {break;}+ if (termOrd == termOrdToBytesOffset.size()) {+ // NOTE: this code only runs if the incoming+ // reader impl doesn't implement+ // getUniqueTermCount (which should be uncommon)+ termOrdToBytesOffset = termOrdToBytesOffset.resize(ArrayUtil.oversize(1+termOrd, 1));+ }+ termOrdToBytesOffset.set(termOrd, bytes.copyUsingLengthPrefix(term));+ bytes.copyUsingLengthPrefix(term);docs = termsEnum.docs(delDocs, docs);- final String termval = term.utf8ToString();while (true) {final int docID = docs.nextDoc();if (docID == DocsEnum.NO_MORE_DOCS) {break;}- retArray[docID] = termval;+ docToTermOrd.set(docID, termOrd);}+ termOrd++;+ }++ if (termOrdToBytesOffset.size() > termOrd) {+ termOrdToBytesOffset = termOrdToBytesOffset.resize(termOrd);}}- return retArray;++ // maybe an int-only impl?+ return new DocTermsIndexImpl(bytes.freeze(), termOrdToBytesOffset.getMutable(), docToTermOrd.getMutable(), termOrd);}}- // inherit javadocs- public StringIndex getStringIndex(IndexReader reader, String field)- throws IOException {- return (StringIndex) caches.get(StringIndex.class).get(reader, new Entry(field, (Parser)null));+ private static class DocTermsImpl extends DocTerms {+ private final PagedBytes.Reader bytes;+ private final PackedInts.Reader docToOffset;++ public DocTermsImpl(PagedBytes.Reader bytes, PackedInts.Reader docToOffset) {+ this.bytes = bytes;+ this.docToOffset = docToOffset;+ }++ @Override+ public int size() {+ return docToOffset.size();+ }++ @Override+ public boolean exists(int docID) {+ return docToOffset.get(docID) == 0;+ }++ @Override+ public BytesRef getTerm(int docID, BytesRef ret) {+ final int pointer = (int) docToOffset.get(docID);+ return bytes.fillUsingLengthPrefix(ret, pointer);+ }+ }++ // TODO: this if DocTermsIndex was already created, we+ // should share it...+ public DocTerms getTerms(IndexReader reader, String field) throws IOException {+ return getTerms(reader, field, DEFAULT_FASTER_BUT_MORE_RAM);}- static final class StringIndexCache extends Cache {- StringIndexCache(FieldCache wrapper) {+ public DocTerms getTerms(IndexReader reader, String field, boolean fasterButMoreRAM) throws IOException {+ return (DocTerms) caches.get(DocTerms.class).get(reader, new Entry(field, Boolean.valueOf(fasterButMoreRAM)));+ }++ static final class DocTermsCache extends Cache {+ DocTermsCache(FieldCache wrapper) {super(wrapper);}@Overrideprotected Object createValue(IndexReader reader, Entry entryKey)throws IOException {- String field = StringHelper.intern(entryKey.field);- final int[] retArray = new int[reader.maxDoc()];- String[] mterms = new String[reader.maxDoc()+1];- //System.out.println("FC: getStringIndex field=" + field);+ String field = StringHelper.intern(entryKey.field);Terms terms = MultiFields.getTerms(reader, field);- int t = 0; // current term number+ final boolean fasterButMoreRAM = ((Boolean) entryKey.custom).booleanValue();++ // Holds the actual term data, expanded.+ final PagedBytes bytes = new PagedBytes(15);- // an entry for documents that have no terms in this field- // should a document with no terms be at top or bottom?- // this puts them at the top - if it is changed, FieldDocSortedHitQueue- // needs to change as well.- mterms[t++] = null;+ int startBPV;++ if (terms != null) {+ // Try for coarse estimate for number of bits; this+ // should be an underestimate most of the time, which+ // is fine -- GrowableWriter will reallocate as needed+ long numUniqueTerms = 0;+ try {+ numUniqueTerms = terms.getUniqueTermCount();+ } catch (UnsupportedOperationException uoe) {+ numUniqueTerms = -1;+ }+ if (numUniqueTerms != -1) {+ startBPV = PackedInts.bitsRequired(numUniqueTerms*4);+ } else {+ startBPV = 1;+ }+ } else {+ startBPV = 1;+ }++ final GrowableWriter docToOffset = new GrowableWriter(startBPV, reader.maxDoc(), fasterButMoreRAM);++ // pointer==0 means not set+ bytes.copyUsingLengthPrefix(new BytesRef());if (terms != null) {final TermsEnum termsEnum = terms.iterator();@@ -718,42 +868,22 @@ class FieldCacheImpl implements FieldCache {if (term == null) {break;}-- // store term text- mterms[t] = term.utf8ToString();- //System.out.println("FC: ord=" + t + " term=" + term.toBytesString());-+ final long pointer = bytes.copyUsingLengthPrefix(term);docs = termsEnum.docs(delDocs, docs);while (true) {final int docID = docs.nextDoc();if (docID == DocsEnum.NO_MORE_DOCS) {break;}- //System.out.println("FC: docID=" + docID);- retArray[docID] = t;+ docToOffset.set(docID, pointer);}- t++;}}- if (t == 0) {- // if there are no terms, make the term array- // have a single null entry- mterms = new String[1];- } else if (t < mterms.length) {- // if there are less terms than documents,- // trim off the dead array space- String[] newTerms = new String[t];- System.arraycopy (mterms, 0, newTerms, 0, t);- mterms = newTerms;- }-- StringIndex value = new StringIndex (retArray, mterms);- //System.out.println("FC: done\n");- return value;+ // maybe an int-only impl?+ return new DocTermsImpl(bytes.freeze(), docToOffset.getMutable());}}-private volatile PrintStream infoStream;public void setInfoStream(PrintStream stream) {diff --git a/lucene/src/java/org/apache/lucene/search/FieldCacheRangeFilter.java b/lucene/src/java/org/apache/lucene/search/FieldCacheRangeFilter.javaindex 7e460f7d6ae..13f12505f6a 100644--- a/lucene/src/java/org/apache/lucene/search/FieldCacheRangeFilter.java+++ b/lucene/src/java/org/apache/lucene/search/FieldCacheRangeFilter.java@@ -22,6 +22,7 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.MultiFields;import org.apache.lucene.util.NumericUtils;import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.document.NumericField; // for javadocs/**@@ -83,10 +84,11 @@ public abstract class FieldCacheRangeFilter<T> extends Filter {return new FieldCacheRangeFilter<String>(field, null, lowerVal, upperVal, includeLower, includeUpper) {@Overridepublic DocIdSet getDocIdSet(IndexReader reader) throws IOException {- final FieldCache.StringIndex fcsi = FieldCache.DEFAULT.getStringIndex(reader, field);- final int lowerPoint = fcsi.binarySearchLookup(lowerVal);- final int upperPoint = fcsi.binarySearchLookup(upperVal);-+ final FieldCache.DocTermsIndex fcsi = FieldCache.DEFAULT.getTermsIndex(reader, field);+ final BytesRef spare = new BytesRef();+ final int lowerPoint = fcsi.binarySearchLookup(lowerVal == null ? null : new BytesRef(lowerVal), spare);+ final int upperPoint = fcsi.binarySearchLookup(upperVal == null ? null : new BytesRef(upperVal), spare);+final int inclusiveLowerPoint, inclusiveUpperPoint;// Hints:@@ -125,7 +127,8 @@ public abstract class FieldCacheRangeFilter<T> extends Filter {return new FieldCacheDocIdSet(reader, true) {@Overridefinal boolean matchDoc(int doc) {- return fcsi.order[doc] >= inclusiveLowerPoint && fcsi.order[doc] <= inclusiveUpperPoint;+ final int docOrd = fcsi.getOrd(doc);+ return docOrd >= inclusiveLowerPoint && docOrd <= inclusiveUpperPoint;}};}diff --git a/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java b/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.javaindex 07e578eacb1..7456c8531fb 100644--- a/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java+++ b/lucene/src/java/org/apache/lucene/search/FieldCacheTermsFilter.java@@ -21,6 +21,7 @@ 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/**@@ -108,19 +109,20 @@ public class FieldCacheTermsFilter extends Filter {@Overridepublic DocIdSet getDocIdSet(IndexReader reader) throws IOException {- return new FieldCacheTermsFilterDocIdSet(getFieldCache().getStringIndex(reader, field));+ return new FieldCacheTermsFilterDocIdSet(getFieldCache().getTermsIndex(reader, field));}protected class FieldCacheTermsFilterDocIdSet extends DocIdSet {- private FieldCache.StringIndex fcsi;+ private FieldCache.DocTermsIndex fcsi;private OpenBitSet openBitSet;- public FieldCacheTermsFilterDocIdSet(FieldCache.StringIndex fcsi) {+ public FieldCacheTermsFilterDocIdSet(FieldCache.DocTermsIndex fcsi) {this.fcsi = fcsi;- openBitSet = new OpenBitSet(this.fcsi.lookup.length);+ openBitSet = new OpenBitSet(this.fcsi.size());+ final BytesRef spare = new BytesRef();for (int i=0;i<terms.length;i++) {- int termNumber = this.fcsi.binarySearchLookup(terms[i]);+ int termNumber = this.fcsi.binarySearchLookup(new BytesRef(terms[i]), spare);if (termNumber > 0) {openBitSet.fastSet(termNumber);}@@ -149,7 +151,7 @@ public class FieldCacheTermsFilter extends Filter {@Overridepublic int nextDoc() {try {- while (!openBitSet.fastGet(fcsi.order[++doc])) {}+ while (!openBitSet.fastGet(fcsi.getOrd(++doc))) {}} catch (ArrayIndexOutOfBoundsException e) {doc = NO_MORE_DOCS;}@@ -160,7 +162,7 @@ public class FieldCacheTermsFilter extends Filter {public int advance(int target) {try {doc = target;- while (!openBitSet.fastGet(fcsi.order[doc])) {+ while (!openBitSet.fastGet(fcsi.getOrd(doc))) {doc++;}} catch (ArrayIndexOutOfBoundsException e) {diff --git a/lucene/src/java/org/apache/lucene/search/FieldComparator.java b/lucene/src/java/org/apache/lucene/search/FieldComparator.javaindex b003eddd3b3..d9c6ffd2287 100644--- a/lucene/src/java/org/apache/lucene/search/FieldComparator.java+++ b/lucene/src/java/org/apache/lucene/search/FieldComparator.java@@ -28,7 +28,9 @@ import org.apache.lucene.search.FieldCache.ByteParser;import org.apache.lucene.search.FieldCache.FloatParser;import org.apache.lucene.search.FieldCache.IntParser;import org.apache.lucene.search.FieldCache.ShortParser;-import org.apache.lucene.search.FieldCache.StringIndex;+import org.apache.lucene.search.FieldCache.DocTermsIndex;+import org.apache.lucene.search.FieldCache.DocTerms;+import org.apache.lucene.util.BytesRef;/*** Expert: a FieldComparator compares hits so as to determine their@@ -616,14 +618,19 @@ public abstract class FieldComparator {}/** Sorts by a field's value using the Collator for a- * given Locale.*/+ * given Locale.+ *+ * <p><b>WARNING</b>: this is likely very slow; you'll+ * get much better performance using the+ * CollationKeyAnalyzer or ICUCollationKeyAnalyzer. */public static final class StringComparatorLocale extends FieldComparator {private final String[] values;- private String[] currentReaderValues;+ private DocTerms currentDocTerms;private final String field;final Collator collator;private String bottom;+ private final BytesRef tempBR = new BytesRef();StringComparatorLocale(int numHits, String field, Locale locale) {values = new String[numHits];@@ -648,7 +655,7 @@ public abstract class FieldComparator {@Overridepublic int compareBottom(int doc) {- final String val2 = currentReaderValues[doc];+ final String val2 = currentDocTerms.getTerm(doc, tempBR).utf8ToString();if (bottom == null) {if (val2 == null) {return 0;@@ -662,12 +669,17 @@ public abstract class FieldComparator {@Overridepublic void copy(int slot, int doc) {- values[slot] = currentReaderValues[doc];+ final BytesRef br = currentDocTerms.getTerm(doc, tempBR);+ if (br == null) {+ values[slot] = null;+ } else {+ values[slot] = br.utf8ToString();+ }}@Overridepublic void setNextReader(IndexReader reader, int docBase) throws IOException {- currentReaderValues = FieldCache.DEFAULT.getStrings(reader, field);+ currentDocTerms = FieldCache.DEFAULT.getTerms(reader, field);}@Override@@ -677,39 +689,40 @@ public abstract class FieldComparator {@Overridepublic Comparable<?> value(int slot) {- return values[slot];+ final String s = values[slot];+ return s == null ? null : new BytesRef(values[slot]);}}- /** Sorts by field's natural String sort order, using+ /** Sorts by field's natural Term sort order, using* ordinals. This is functionally equivalent to {@link- * StringValComparator}, but it first resolves the string+ * TermValComparator}, but it first resolves the string* to their relative ordinal positions (using the index* returned by {@link FieldCache#getStringIndex}), and* does most comparisons using the ordinals. For medium* to large results, this comparator will be much faster- * than {@link StringValComparator}. For very small+ * than {@link TermValComparator}. For very small* result sets it may be slower. */- public static final class StringOrdValComparator extends FieldComparator {+ public static final class TermOrdValComparator extends FieldComparator {private final int[] ords;- private final String[] values;+ private final BytesRef[] values;private final int[] readerGen;private int currentReaderGen = -1;- private String[] lookup;- private int[] order;+ private DocTermsIndex termsIndex;private final String field;private int bottomSlot = -1;private int bottomOrd;- private String bottomValue;+ private BytesRef bottomValue;private final boolean reversed;private final int sortPos;+ private final BytesRef tempBR = new BytesRef();- public StringOrdValComparator(int numHits, String field, int sortPos, boolean reversed) {+ public TermOrdValComparator(int numHits, String field, int sortPos, boolean reversed) {ords = new int[numHits];- values = new String[numHits];+ values = new BytesRef[numHits];readerGen = new int[numHits];this.sortPos = sortPos;this.reversed = reversed;@@ -725,8 +738,8 @@ public abstract class FieldComparator {}}- final String val1 = values[slot1];- final String val2 = values[slot2];+ final BytesRef val1 = values[slot1];+ final BytesRef val2 = values[slot2];if (val1 == null) {if (val2 == null) {return 0;@@ -741,47 +754,48 @@ public abstract class FieldComparator {@Overridepublic int compareBottom(int doc) {assert bottomSlot != -1;- int order = this.order[doc];+ int order = termsIndex.getOrd(doc);final int cmp = bottomOrd - order;if (cmp != 0) {return cmp;}- final String val2 = lookup[order];if (bottomValue == null) {- if (val2 == null) {+ if (order == 0) {+ // unsetreturn 0;}// bottom winsreturn -1;- } else if (val2 == null) {+ } else if (order == 0) {// doc winsreturn 1;}- return bottomValue.compareTo(val2);+ termsIndex.lookup(order, tempBR);+ return bottomValue.compareTo(tempBR);}private void convert(int slot) {readerGen[slot] = currentReaderGen;int index = 0;- String value = values[slot];+ BytesRef value = values[slot];if (value == null) {- ords[slot] = 0;+ // 0 ord is null for all segments+ assert ords[slot] == 0;return;}if (sortPos == 0 && bottomSlot != -1 && bottomSlot != slot) {// Since we are the primary sort, the entries in the// queue are bounded by bottomOrd:- assert bottomOrd < lookup.length;if (reversed) {- index = binarySearch(lookup, value, bottomOrd, lookup.length-1);+ index = binarySearch(tempBR, termsIndex, value, bottomOrd, termsIndex.numOrd()-1);} else {- index = binarySearch(lookup, value, 0, bottomOrd);+ index = binarySearch(tempBR, termsIndex, value, 0, bottomOrd);}} else {// Full binary search- index = binarySearch(lookup, value);+ index = binarySearch(tempBR, termsIndex, value);}if (index < 0) {@@ -792,20 +806,24 @@ public abstract class FieldComparator {@Overridepublic void copy(int slot, int doc) {- final int ord = order[doc];- ords[slot] = ord;- assert ord >= 0;- values[slot] = lookup[ord];+ final int ord = termsIndex.getOrd(doc);+ if (ord == 0) {+ values[slot] = null;+ } else {+ ords[slot] = ord;+ assert ord >= 0;+ if (values[slot] == null) {+ values[slot] = new BytesRef();+ }+ termsIndex.lookup(ord, values[slot]);+ }readerGen[slot] = currentReaderGen;}@Overridepublic void setNextReader(IndexReader reader, int docBase) throws IOException {- StringIndex currentReaderValues = FieldCache.DEFAULT.getStringIndex(reader, field);+ termsIndex = FieldCache.DEFAULT.getTermsIndex(reader, field);currentReaderGen++;- order = currentReaderValues.order;- lookup = currentReaderValues.lookup;- assert lookup.length > 0;if (bottomSlot != -1) {convert(bottomSlot);bottomOrd = ords[bottomSlot];@@ -819,8 +837,6 @@ public abstract class FieldComparator {convert(bottomSlot);}bottomOrd = ords[bottom];- assert bottomOrd >= 0;- assert bottomOrd < lookup.length;bottomValue = values[bottom];}@@ -829,10 +845,6 @@ public abstract class FieldComparator {return values[slot];}- public String[] getValues() {- return values;- }-public int getBottomSlot() {return bottomSlot;}@@ -842,26 +854,27 @@ public abstract class FieldComparator {}}- /** Sorts by field's natural String sort order. All- * comparisons are done using String.compareTo, which is+ /** Sorts by field's natural Term sort order. All+ * comparisons are done using BytesRef.compareTo, which is* slow for medium to large result sets but possibly* very fast for very small results sets. */- public static final class StringValComparator extends FieldComparator {+ public static final class TermValComparator extends FieldComparator {- private String[] values;- private String[] currentReaderValues;+ private BytesRef[] values;+ private DocTerms docTerms;private final String field;- private String bottom;+ private BytesRef bottom;+ private final BytesRef tempBR = new BytesRef();- StringValComparator(int numHits, String field) {- values = new String[numHits];+ TermValComparator(int numHits, String field) {+ values = new BytesRef[numHits];this.field = field;}@Overridepublic int compare(int slot1, int slot2) {- final String val1 = values[slot1];- final String val2 = values[slot2];+ final BytesRef val1 = values[slot1];+ final BytesRef val2 = values[slot2];if (val1 == null) {if (val2 == null) {return 0;@@ -876,7 +889,7 @@ public abstract class FieldComparator {@Overridepublic int compareBottom(int doc) {- final String val2 = currentReaderValues[doc];+ BytesRef val2 = docTerms.getTerm(doc, tempBR);if (bottom == null) {if (val2 == null) {return 0;@@ -890,12 +903,15 @@ public abstract class FieldComparator {@Overridepublic void copy(int slot, int doc) {- values[slot] = currentReaderValues[doc];+ if (values[slot] == null) {+ values[slot] = new BytesRef();+ }+ docTerms.getTerm(doc, values[slot]);}@Overridepublic void setNextReader(IndexReader reader, int docBase) throws IOException {- currentReaderValues = FieldCache.DEFAULT.getStrings(reader, field);+ docTerms = FieldCache.DEFAULT.getTerms(reader, field);}@Override@@ -909,15 +925,15 @@ public abstract class FieldComparator {}}- final protected static int binarySearch(String[] a, String key) {- return binarySearch(a, key, 0, a.length-1);+ final protected static int binarySearch(BytesRef br, DocTermsIndex a, BytesRef key) {+ return binarySearch(br, a, key, 1, a.numOrd()-1);}- final protected static int binarySearch(String[] a, String key, int low, int high) {+ final protected static int binarySearch(BytesRef br, DocTermsIndex a, BytesRef key, int low, int high) {while (low <= high) {int mid = (low + high) >>> 1;- String midVal = a[mid];+ BytesRef midVal = a.lookup(mid, br);int cmp;if (midVal != null) {cmp = midVal.compareTo(key);diff --git a/lucene/src/java/org/apache/lucene/search/FieldDocSortedHitQueue.java b/lucene/src/java/org/apache/lucene/search/FieldDocSortedHitQueue.javaindex edea2e3190c..f60f202deb7 100644--- a/lucene/src/java/org/apache/lucene/search/FieldDocSortedHitQueue.java+++ b/lucene/src/java/org/apache/lucene/search/FieldDocSortedHitQueue.java@@ -18,6 +18,7 @@ package org.apache.lucene.search;*/import org.apache.lucene.util.PriorityQueue;+import org.apache.lucene.util.BytesRef;import java.text.Collator;import java.util.Locale;@@ -99,8 +100,8 @@ class FieldDocSortedHitQueue extends PriorityQueue<FieldDoc> {for (int i=0; i<n && c==0; ++i) {final int type = fields[i].getType();if (type == SortField.STRING) {- final String s1 = (String) docA.fields[i];- final String s2 = (String) docB.fields[i];+ final BytesRef s1 = (BytesRef) docA.fields[i];+ final BytesRef s2 = (BytesRef) docB.fields[i];// null values need to be sorted first, because of how FieldCache.getStringIndex()// works - in that routine, any documents without a value in the given field are// put first. If both are null, the next SortField is used@@ -111,7 +112,7 @@ class FieldDocSortedHitQueue extends PriorityQueue<FieldDoc> {} else if (fields[i].getLocale() == null) {c = s1.compareTo(s2);} else {- c = collators[i].compare(s1, s2);+ c = collators[i].compare(s1.utf8ToString(), s2.utf8ToString());}} else {c = docA.fields[i].compareTo(docB.fields[i]);diff --git a/lucene/src/java/org/apache/lucene/search/SortField.java b/lucene/src/java/org/apache/lucene/search/SortField.javaindex 3144958a467..b2ef3c47b51 100644--- a/lucene/src/java/org/apache/lucene/search/SortField.java+++ b/lucene/src/java/org/apache/lucene/search/SortField.java@@ -83,10 +83,6 @@ implements Serializable {* uses ordinals to do the sorting. */public static final int STRING_VAL = 11;- // IMPLEMENTATION NOTE: the FieldCache.STRING_INDEX is in the same "namespace"- // as the above static int values. Any new values must not have the same value- // as FieldCache.STRING_INDEX.-/** Represents sorting by document score (relevancy). */public static final SortField FIELD_SCORE = new SortField (null, SCORE);@@ -413,10 +409,10 @@ implements Serializable {return comparatorSource.newComparator(field, numHits, sortPos, reverse);case SortField.STRING:- return new FieldComparator.StringOrdValComparator(numHits, field, sortPos, reverse);+ return new FieldComparator.TermOrdValComparator(numHits, field, sortPos, reverse);case SortField.STRING_VAL:- return new FieldComparator.StringValComparator(numHits, field);+ return new FieldComparator.TermValComparator(numHits, field);default:throw new IllegalStateException("Illegal sort type: " + type);diff --git a/lucene/src/java/org/apache/lucene/search/function/OrdFieldSource.java b/lucene/src/java/org/apache/lucene/search/function/OrdFieldSource.javaindex 05032a012fe..218375d2d5b 100644--- a/lucene/src/java/org/apache/lucene/search/function/OrdFieldSource.java+++ b/lucene/src/java/org/apache/lucene/search/function/OrdFieldSource.java@@ -19,6 +19,7 @@ package org.apache.lucene.search.function;import org.apache.lucene.index.IndexReader;import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.FieldCache.DocTermsIndex;import java.io.IOException;@@ -69,18 +70,18 @@ public class OrdFieldSource extends ValueSource {/*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */@Overridepublic DocValues getValues(IndexReader reader) throws IOException {- final int[] arr = FieldCache.DEFAULT.getStringIndex(reader, field).order;+ final DocTermsIndex termsIndex = FieldCache.DEFAULT.getTermsIndex(reader, field);return new DocValues() {/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */@Overridepublic float floatVal(int doc) {- return arr[doc];+ return termsIndex.getOrd(doc);}/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#strVal(int) */@Overridepublic String strVal(int doc) {// the string value of the ordinal, not the string itself- return Integer.toString(arr[doc]);+ return Integer.toString(termsIndex.getOrd(doc));}/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */@Override@@ -90,7 +91,7 @@ public class OrdFieldSource extends ValueSource {/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */@OverrideObject getInnerArray() {- return arr;+ return termsIndex;}};}diff --git a/lucene/src/java/org/apache/lucene/search/function/ReverseOrdFieldSource.java b/lucene/src/java/org/apache/lucene/search/function/ReverseOrdFieldSource.javaindex d2938093f60..517c37a7675 100644--- a/lucene/src/java/org/apache/lucene/search/function/ReverseOrdFieldSource.java+++ b/lucene/src/java/org/apache/lucene/search/function/ReverseOrdFieldSource.java@@ -70,21 +70,20 @@ public class ReverseOrdFieldSource extends ValueSource {/*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */@Overridepublic DocValues getValues(IndexReader reader) throws IOException {- final FieldCache.StringIndex sindex = FieldCache.DEFAULT.getStringIndex(reader, field);+ final FieldCache.DocTermsIndex termsIndex = FieldCache.DEFAULT.getTermsIndex(reader, field);- final int arr[] = sindex.order;- final int end = sindex.lookup.length;+ final int end = termsIndex.numOrd();return new DocValues() {/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */@Overridepublic float floatVal(int doc) {- return (end - arr[doc]);+ return (end - termsIndex.getOrd(doc));}/* (non-Javadoc) @see org.apache.lucene.search.function.DocValues#intVal(int) */@Overridepublic int intVal(int doc) {- return end - arr[doc];+ return end - termsIndex.getOrd(doc);}/* (non-Javadoc) @see org.apache.lucene.search.function.DocValues#strVal(int) */@Override@@ -100,7 +99,7 @@ public class ReverseOrdFieldSource extends ValueSource {/*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */@OverrideObject getInnerArray() {- return arr;+ return termsIndex;}};}diff --git a/lucene/src/java/org/apache/lucene/util/BytesRef.java b/lucene/src/java/org/apache/lucene/util/BytesRef.javaindex 218fc168140..ca8466f4a2d 100644--- a/lucene/src/java/org/apache/lucene/util/BytesRef.java+++ b/lucene/src/java/org/apache/lucene/util/BytesRef.java@@ -19,12 +19,17 @@ package org.apache.lucene.util;import java.util.Comparator;import java.io.UnsupportedEncodingException;+import java.io.ObjectInput;+import java.io.ObjectOutput;+import java.io.Externalizable;+import java.io.IOException;/** Represents byte[], as a slice (offset + length) into an* existing byte[].** @lucene.experimental */-public final class BytesRef implements Comparable<BytesRef> {+public final class BytesRef implements Comparable<BytesRef>, Externalizable {+public static final byte[] EMPTY_BYTES = new byte[0];/** The contents of the BytesRef. Should never be {@code null}. */@@ -78,6 +83,19 @@ public final class BytesRef implements Comparable<BytesRef> {copy(other);}+ /* // maybe?+ public BytesRef(BytesRef other, boolean shallow) {+ this();+ if (shallow) {+ offset = other.offset;+ length = other.length;+ bytes = other.bytes;+ } else {+ copy(other);+ }+ }+ */+/*** Copies the UTF8 bytes for this string.*@@ -316,4 +334,25 @@ public final class BytesRef implements Comparable<BytesRef> {return this == other;}}++ public void writeExternal(ObjectOutput out)+ throws IOException+ {+ out.writeInt(length);+ if (length > 0) {+ out.write(bytes, offset, length);+ }+ }++ public void readExternal( ObjectInput in ) throws+ IOException, ClassNotFoundException {+ length = in.readInt();+ offset = 0;+ if (length > 0) {+ bytes = new byte[length];+ in.read(bytes, 0, length);+ } else {+ bytes = null;+ }+ }}diff --git a/lucene/src/java/org/apache/lucene/util/PagedBytes.java b/lucene/src/java/org/apache/lucene/util/PagedBytes.javanew file mode 100644index 00000000000..5fc3d24e86a--- /dev/null+++ b/lucene/src/java/org/apache/lucene/util/PagedBytes.java@@ -0,0 +1,221 @@+package org.apache.lucene.util;++/**+ * 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.store.IndexInput;++import java.util.List;+import java.util.ArrayList;+import java.io.Closeable;+import java.io.IOException;++/** Represents a logical byte[] as a series of pages. You+ * can write-once into the logical byte[] (append only),+ * using copy, and then retrieve slices (BytesRef) into it+ * using fill.+ *+ * <p>@lucene.internal</p>*/+public final class PagedBytes {+ private final List<byte[]> blocks = new ArrayList<byte[]>();+ private final int blockSize;+ private final int blockBits;+ private final int blockMask;+ private int upto;+ private byte[] currentBlock;++ private static final byte[] EMPTY_BYTES = new byte[0];++ public final static class Reader implements Closeable {+ private final byte[][] blocks;+ private final int blockBits;+ private final int blockMask;+ private final int blockSize;+ private final CloseableThreadLocal<byte[]> threadBuffers = new CloseableThreadLocal<byte[]>();++ public Reader(PagedBytes pagedBytes) {+ blocks = new byte[pagedBytes.blocks.size()][];+ for(int i=0;i<blocks.length;i++) {+ blocks[i] = pagedBytes.blocks.get(i);+ }+ blockBits = pagedBytes.blockBits;+ blockMask = pagedBytes.blockMask;+ blockSize = pagedBytes.blockSize;+ }++ /** Get a slice out of the byte array. */+ public BytesRef fill(BytesRef b, long start, int length) {+ assert length >= 0: "length=" + length;+ final int index = (int) (start >> blockBits);+ final int offset = (int) (start & blockMask);+ b.length = length;+ if (blockSize - offset >= length) {+ // Within block+ b.bytes = blocks[index];+ b.offset = offset;+ } else {+ // Split+ byte[] buffer = threadBuffers.get();+ if (buffer == null) {+ buffer = new byte[length];+ threadBuffers.set(buffer);+ } else if (buffer.length < length) {+ buffer = ArrayUtil.grow(buffer, length);+ threadBuffers.set(buffer);+ }+ b.bytes = buffer;+ b.offset = 0;+ System.arraycopy(blocks[index], offset, buffer, 0, blockSize-offset);+ System.arraycopy(blocks[1+index], 0, buffer, blockSize-offset, length-(blockSize-offset));+ }+ return b;+ }++ /** Reads length as 1 or 2 byte vInt prefix, starting @ start */+ public BytesRef fillUsingLengthPrefix(BytesRef b, long start) {+ final int index = (int) (start >> blockBits);+ final int offset = (int) (start & blockMask);+ final byte[] block = b.bytes = blocks[index];++ if ((block[offset] & 128) == 0) {+ b.length = block[offset];+ b.offset = offset+1;+ } else {+ b.length = (((int) (block[offset] & 0x7f)) << 8) | (block[1+offset] & 0xff);+ b.offset = offset+2;+ assert b.length > 0;+ }+ return b;+ }++ public void close() {+ threadBuffers.close();+ }+ }++ /** 1<<blockBits must be bigger than biggest single+ * BytesRef slice that will be pulled */+ public PagedBytes(int blockBits) {+ this.blockSize = 1 << blockBits;+ this.blockBits = blockBits;+ blockMask = blockSize-1;+ upto = blockSize;+ }++ /** Read this many bytes from in */+ public void copy(IndexInput in, long byteCount) throws IOException {+ while (byteCount > 0) {+ int left = blockSize - upto;+ if (left == 0) {+ if (currentBlock != null) {+ blocks.add(currentBlock);+ }+ currentBlock = new byte[blockSize];+ upto = 0;+ left = blockSize;+ }+ if (left < byteCount) {+ in.readBytes(currentBlock, upto, left, false);+ upto = blockSize;+ byteCount -= left;+ } else {+ in.readBytes(currentBlock, upto, (int) byteCount, false);+ upto += byteCount;+ break;+ }+ }+ }++ /** Copy BytesRef in */+ public void copy(BytesRef bytes) throws IOException {+ int byteCount = bytes.length;+ int bytesUpto = bytes.offset;+ while (byteCount > 0) {+ int left = blockSize - upto;+ if (left == 0) {+ if (currentBlock != null) {+ blocks.add(currentBlock);+ }+ currentBlock = new byte[blockSize];+ upto = 0;+ left = blockSize;+ }+ if (left < byteCount) {+ System.arraycopy(bytes.bytes, bytesUpto, currentBlock, upto, left);+ upto = blockSize;+ byteCount -= left;+ bytesUpto += left;+ } else {+ System.arraycopy(bytes.bytes, bytesUpto, currentBlock, upto, (int) byteCount);+ upto += byteCount;+ break;+ }+ }+ }++ /** Commits final byte[], trimming it if necessary. */+ public Reader freeze() {+ if (upto < blockSize) {+ final byte[] newBlock = new byte[upto];+ System.arraycopy(currentBlock, 0, newBlock, 0, upto);+ currentBlock = newBlock;+ }+ if (currentBlock == null) {+ currentBlock = EMPTY_BYTES;+ }+ blocks.add(currentBlock);+ currentBlock = null;+ return new Reader(this);+ }++ public long getPointer() {+ if (currentBlock == null) {+ return 0;+ } else {+ return (blocks.size() * ((long) blockSize)) + upto;+ }+ }++ /** Copy bytes in, writing the length as a 1 or 2 byte+ * vInt prefix. */+ public long copyUsingLengthPrefix(BytesRef bytes) throws IOException {++ if (upto + bytes.length + 2 > blockSize) {+ if (bytes.length + 2 > blockSize) {+ throw new IllegalArgumentException("block size " + blockSize + " is too small to store length " + bytes.length + " bytes");+ }+ if (currentBlock != null) {+ blocks.add(currentBlock);+ }+ currentBlock = new byte[blockSize];+ upto = 0;+ }++ final long pointer = getPointer();++ if (bytes.length < 128) {+ currentBlock[upto++] = (byte) bytes.length;+ } else {+ currentBlock[upto++] = (byte) (0x80 | (bytes.length >> 8));+ currentBlock[upto++] = (byte) (bytes.length & 0xff);+ }+ System.arraycopy(bytes.bytes, bytes.offset, currentBlock, upto, bytes.length);+ upto += bytes.length;++ return pointer;+ }+}diff --git a/lucene/src/java/org/apache/lucene/util/packed/Direct16.java b/lucene/src/java/org/apache/lucene/util/packed/Direct16.javaindex c97cace0247..e34ec9641b2 100644--- a/lucene/src/java/org/apache/lucene/util/packed/Direct16.java+++ b/lucene/src/java/org/apache/lucene/util/packed/Direct16.java@@ -29,19 +29,19 @@ import java.util.Arrays;class Direct16 extends PackedInts.ReaderImplimplements PackedInts.Mutable {- private short[] blocks;+ private short[] values;private static final int BITS_PER_VALUE = 16;public Direct16(int valueCount) {super(valueCount, BITS_PER_VALUE);- blocks = new short[valueCount];+ values = new short[valueCount];}public Direct16(IndexInput in, int valueCount) throws IOException {super(valueCount, BITS_PER_VALUE);- short[] blocks = new short[valueCount];+ short[] values = new short[valueCount];for(int i=0;i<valueCount;i++) {- blocks[i] = in.readShort();+ values[i] = in.readShort();}final int mod = valueCount % 4;if (mod != 0) {@@ -52,35 +52,35 @@ class Direct16 extends PackedInts.ReaderImpl}}- this.blocks = blocks;+ this.values = values;}/**- * Creates an array backed by the given blocks.+ * Creates an array backed by the given values.* </p><p>- * Note: The blocks are used directly, so changes to the given block will+ * Note: The values are used directly, so changes to the values will* affect the structure.- * @param blocks used as the internal backing array.+ * @param values used as the internal backing array.*/- public Direct16(short[] blocks) {- super(blocks.length, BITS_PER_VALUE);- this.blocks = blocks;+ public Direct16(short[] values) {+ super(values.length, BITS_PER_VALUE);+ this.values = values;}public long get(final int index) {- return 0xFFFFL & blocks[index];+ return 0xFFFFL & values[index];}public void set(final int index, final long value) {- blocks[index] = (short)(value & 0xFFFF);+ values[index] = (short)(value & 0xFFFF);}public long ramBytesUsed() {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER +- blocks.length * RamUsageEstimator.NUM_BYTES_SHORT;+ values.length * RamUsageEstimator.NUM_BYTES_SHORT;}public void clear() {- Arrays.fill(blocks, (short)0);+ Arrays.fill(values, (short)0);}}diff --git a/lucene/src/java/org/apache/lucene/util/packed/Direct32.java b/lucene/src/java/org/apache/lucene/util/packed/Direct32.javaindex da3b33c5017..3ab4cd09506 100644--- a/lucene/src/java/org/apache/lucene/util/packed/Direct32.java+++ b/lucene/src/java/org/apache/lucene/util/packed/Direct32.java@@ -29,54 +29,54 @@ import java.util.Arrays;class Direct32 extends PackedInts.ReaderImplimplements PackedInts.Mutable {- private int[] blocks;+ private int[] values;private static final int BITS_PER_VALUE = 32;public Direct32(int valueCount) {super(valueCount, BITS_PER_VALUE);- blocks = new int[valueCount];+ values = new int[valueCount];}public Direct32(IndexInput in, int valueCount) throws IOException {super(valueCount, BITS_PER_VALUE);- int[] blocks = new int[valueCount];+ int[] values = new int[valueCount];for(int i=0;i<valueCount;i++) {- blocks[i] = in.readInt();+ values[i] = in.readInt();}final int mod = valueCount % 2;if (mod != 0) {in.readInt();}- this.blocks = blocks;+ this.values = values;}/**- * Creates an array backed by the given blocks.+ * Creates an array backed by the given values.* </p><p>- * Note: The blocks are used directly, so changes to the given block will+ * Note: The values are used directly, so changes to the given values will* affect the structure.- * @param blocks used as the internal backing array.+ * @param values used as the internal backing array.*/- public Direct32(int[] blocks) {- super(blocks.length, BITS_PER_VALUE);- this.blocks = blocks;+ public Direct32(int[] values) {+ super(values.length, BITS_PER_VALUE);+ this.values = values;}public long get(final int index) {- return 0xFFFFFFFFL & blocks[index];+ return 0xFFFFFFFFL & values[index];}public void set(final int index, final long value) {- blocks[index] = (int)(value & 0xFFFFFFFF);+ values[index] = (int)(value & 0xFFFFFFFF);}public long ramBytesUsed() {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER +- blocks.length * RamUsageEstimator.NUM_BYTES_INT;+ values.length * RamUsageEstimator.NUM_BYTES_INT;}public void clear() {- Arrays.fill(blocks, 0);+ Arrays.fill(values, 0);}}diff --git a/lucene/src/java/org/apache/lucene/util/packed/Direct64.java b/lucene/src/java/org/apache/lucene/util/packed/Direct64.javaindex cb6b9df343a..eaa1622a09c 100644--- a/lucene/src/java/org/apache/lucene/util/packed/Direct64.java+++ b/lucene/src/java/org/apache/lucene/util/packed/Direct64.java@@ -29,51 +29,51 @@ import java.util.Arrays;class Direct64 extends PackedInts.ReaderImplimplements PackedInts.Mutable {- private long[] blocks;+ private long[] values;private static final int BITS_PER_VALUE = 64;public Direct64(int valueCount) {super(valueCount, BITS_PER_VALUE);- blocks = new long[valueCount];+ values = new long[valueCount];}public Direct64(IndexInput in, int valueCount) throws IOException {super(valueCount, BITS_PER_VALUE);- long[] blocks = new long[valueCount];+ long[] values = new long[valueCount];for(int i=0;i<valueCount;i++) {- blocks[i] = in.readLong();+ values[i] = in.readLong();}- this.blocks = blocks;+ this.values = values;}/**- * Creates an array backed by the given blocks.+ * Creates an array backed by the given values.* </p><p>- * Note: The blocks are used directly, so changes to the given block will+ * Note: The values are used directly, so changes to the given values will* affect the structure.- * @param blocks used as the internal backing array.+ * @param values used as the internal backing array.*/- public Direct64(long[] blocks) {- super(blocks.length, BITS_PER_VALUE);- this.blocks = blocks;+ public Direct64(long[] values) {+ super(values.length, BITS_PER_VALUE);+ this.values = values;}public long get(final int index) {- return blocks[index];+ return values[index];}public void set(final int index, final long value) {- blocks[index] = value;+ values[index] = value;}public long ramBytesUsed() {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER +- blocks.length * RamUsageEstimator.NUM_BYTES_LONG;+ values.length * RamUsageEstimator.NUM_BYTES_LONG;}public void clear() {- Arrays.fill(blocks, 0L);+ Arrays.fill(values, 0L);}}diff --git a/lucene/src/java/org/apache/lucene/util/packed/Direct8.java b/lucene/src/java/org/apache/lucene/util/packed/Direct8.javaindex 128323b8667..72bf6f925a0 100644--- a/lucene/src/java/org/apache/lucene/util/packed/Direct8.java+++ b/lucene/src/java/org/apache/lucene/util/packed/Direct8.java@@ -29,20 +29,20 @@ import java.util.Arrays;class Direct8 extends PackedInts.ReaderImplimplements PackedInts.Mutable {- private byte[] blocks;+ private byte[] values;private static final int BITS_PER_VALUE = 8;public Direct8(int valueCount) {super(valueCount, BITS_PER_VALUE);- blocks = new byte[valueCount];+ values = new byte[valueCount];}public Direct8(IndexInput in, int valueCount)throws IOException {super(valueCount, BITS_PER_VALUE);- byte[] blocks = new byte[valueCount];+ byte[] values = new byte[valueCount];for(int i=0;i<valueCount;i++) {- blocks[i] = in.readByte();+ values[i] = in.readByte();}final int mod = valueCount % 8;if (mod != 0) {@@ -53,34 +53,34 @@ class Direct8 extends PackedInts.ReaderImpl}}- this.blocks = blocks;+ this.values = values;}/**- * Creates an array backed by the given blocks.+ * Creates an array backed by the given values.* </p><p>- * Note: The blocks are used directly, so changes to the given block will+ * Note: The values are used directly, so changes to the given values will* affect the structure.- * @param blocks used as the internal backing array.+ * @param values used as the internal backing array.*/- public Direct8(byte[] blocks) {- super(blocks.length, BITS_PER_VALUE);- this.blocks = blocks;+ public Direct8(byte[] values) {+ super(values.length, BITS_PER_VALUE);+ this.values = values;}public long get(final int index) {- return 0xFFL & blocks[index];+ return 0xFFL & values[index];}public void set(final int index, final long value) {- blocks[index] = (byte)(value & 0xFF);+ values[index] = (byte)(value & 0xFF);}public long ramBytesUsed() {- return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + blocks.length;+ return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.length;}public void clear() {- Arrays.fill(blocks, (byte)0);+ Arrays.fill(values, (byte)0);}}diff --git a/lucene/src/java/org/apache/lucene/util/packed/GrowableWriter.java b/lucene/src/java/org/apache/lucene/util/packed/GrowableWriter.javanew file mode 100644index 00000000000..499387041fe--- /dev/null+++ b/lucene/src/java/org/apache/lucene/util/packed/GrowableWriter.java@@ -0,0 +1,93 @@+package org.apache.lucene.util.packed;++/**+ * 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.+ */++/**+ * Implements {@link PackedInts.Mutable}, but grows the+ * bit count of the underlying packed ints on-demand.+ *+ * <p>@lucene.internal</p>+ */++public class GrowableWriter implements PackedInts.Mutable {++ private long currentMaxValue;+ private PackedInts.Mutable current;+ private final boolean roundFixedSize;++ public GrowableWriter(int startBitsPerValue, int valueCount, boolean roundFixedSize) {+ this.roundFixedSize = roundFixedSize;+ current = PackedInts.getMutable(valueCount, getSize(startBitsPerValue));+ currentMaxValue = PackedInts.maxValue(current.getBitsPerValue());+ }++ private final int getSize(int bpv) {+ if (roundFixedSize) {+ return PackedInts.getNextFixedSize(bpv);+ } else {+ return bpv;+ }+ }++ public long get(int index) {+ return current.get(index);+ }++ public int size() {+ return current.size();+ }++ public int getBitsPerValue() {+ return current.getBitsPerValue();+ }++ public PackedInts.Mutable getMutable() {+ return current;+ }++ public void set(int index, long value) {+ if (value >= currentMaxValue) {+ int bpv = getBitsPerValue();+ while(currentMaxValue <= value && currentMaxValue != Long.MAX_VALUE) {+ bpv++;+ currentMaxValue *= 2;+ }+ final int valueCount = size();+ PackedInts.Mutable next = PackedInts.getMutable(valueCount, getSize(bpv));+ for(int i=0;i<valueCount;i++) {+ next.set(i, current.get(i));+ }+ current = next;+ currentMaxValue = PackedInts.maxValue(current.getBitsPerValue());+ }+ current.set(index, value);+ }++ public void clear() {+ current.clear();+ }++ public GrowableWriter resize(int newSize) {+ GrowableWriter next = new GrowableWriter(getBitsPerValue(), newSize, roundFixedSize);+ final int limit = Math.min(size(), newSize);+ for(int i=0;i<limit;i++) {+ next.set(i, get(i));+ }+ return next;+ }+}diff --git a/lucene/src/java/org/apache/lucene/util/packed/PackedInts.java b/lucene/src/java/org/apache/lucene/util/packed/PackedInts.javaindex 405431b8de7..ac02e59a47c 100644--- a/lucene/src/java/org/apache/lucene/util/packed/PackedInts.java+++ b/lucene/src/java/org/apache/lucene/util/packed/PackedInts.java@@ -209,7 +209,7 @@ public class PackedInts {* @lucene.internal*/public static Mutable getMutable(- int valueCount, int bitsPerValue) throws IOException {+ int valueCount, int bitsPerValue) {switch (bitsPerValue) {case 8:return new Direct8(valueCount);diff --git a/lucene/src/test/org/apache/lucene/search/TestElevationComparator.java b/lucene/src/test/org/apache/lucene/search/TestElevationComparator.javaindex 931908e41d2..dc3eba31596 100644--- a/lucene/src/test/org/apache/lucene/search/TestElevationComparator.java+++ b/lucene/src/test/org/apache/lucene/search/TestElevationComparator.java@@ -24,13 +24,14 @@ import org.apache.lucene.index.*;import org.apache.lucene.search.FieldValueHitQueue.Entry;import org.apache.lucene.store.*;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;import java.io.IOException;import java.util.HashMap;import java.util.Map;public class TestElevationComparator extends LuceneTestCase {- private final Map<String,Integer> priority = new HashMap<String,Integer>();+ private final Map<BytesRef,Integer> priority = new HashMap<BytesRef,Integer>();//@Testpublic void testSorting() throws Throwable {@@ -109,7 +110,7 @@ public class TestElevationComparator extends LuceneTestCase {int max = (vals.length / 2) + 5;for (int i = 0; i < vals.length - 1; i += 2) {q.add(new TermQuery(new Term(vals[i], vals[i + 1])), BooleanClause.Occur.SHOULD);- priority.put(vals[i + 1], Integer.valueOf(max--));+ priority.put(new BytesRef(vals[i + 1]), Integer.valueOf(max--));// System.out.println(" pri doc=" + vals[i+1] + " pri=" + (1+max));}return q;@@ -125,9 +126,9 @@ public class TestElevationComparator extends LuceneTestCase {}class ElevationComparatorSource extends FieldComparatorSource {- private final Map<String,Integer> priority;+ private final Map<BytesRef,Integer> priority;- public ElevationComparatorSource(final Map<String,Integer> boosts) {+ public ElevationComparatorSource(final Map<BytesRef,Integer> boosts) {this.priority = boosts;}@@ -135,8 +136,9 @@ class ElevationComparatorSource extends FieldComparatorSource {public FieldComparator newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {return new FieldComparator() {- FieldCache.StringIndex idIndex;+ FieldCache.DocTermsIndex idIndex;private final int[] values = new int[numHits];+ private final BytesRef tempBR = new BytesRef();int bottomVal;@Override@@ -150,9 +152,14 @@ class ElevationComparatorSource extends FieldComparatorSource {}private int docVal(int doc) throws IOException {- String id = idIndex.lookup[idIndex.order[doc]];- Integer prio = priority.get(id);- return prio == null ? 0 : prio.intValue();+ int ord = idIndex.getOrd(doc);+ if (ord == 0) {+ return 0;+ } else {+ BytesRef id = idIndex.lookup(ord, tempBR);+ Integer prio = priority.get(id);+ return prio == null ? 0 : prio.intValue();+ }}@Override@@ -167,7 +174,7 @@ class ElevationComparatorSource extends FieldComparatorSource {@Overridepublic void setNextReader(IndexReader reader, int docBase) throws IOException {- idIndex = FieldCache.DEFAULT.getStringIndex(reader, fieldname);+ idIndex = FieldCache.DEFAULT.getTermsIndex(reader, fieldname);}@Overridediff --git a/lucene/src/test/org/apache/lucene/search/TestFieldCache.java b/lucene/src/test/org/apache/lucene/search/TestFieldCache.javaindex 6dac221d5ce..cbb58eef5f9 100644--- a/lucene/src/test/org/apache/lucene/search/TestFieldCache.java+++ b/lucene/src/test/org/apache/lucene/search/TestFieldCache.java@@ -23,14 +23,20 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.store.MockRAMDirectory;+import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util._TestUtil;+import org.apache.lucene.util.BytesRef;import java.io.IOException;+import java.util.Random;import java.io.ByteArrayOutputStream;import java.io.PrintStream;public class TestFieldCache extends LuceneTestCase {protected IndexReader reader;- private static final int NUM_DOCS = 1000;+ private int NUM_DOCS;+ private String[] unicodeStrings;public TestFieldCache(String s) {super(s);@@ -39,14 +45,17 @@ public class TestFieldCache extends LuceneTestCase {@Overrideprotected void setUp() throws Exception {super.setUp();+ Random r = newRandom();+ NUM_DOCS = 1000 * _TestUtil.getRandomMultiplier();RAMDirectory directory = new RAMDirectory();- IndexWriter writer= new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));+ IndexWriter writer= new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(500));long theLong = Long.MAX_VALUE;double theDouble = Double.MAX_VALUE;byte theByte = Byte.MAX_VALUE;short theShort = Short.MAX_VALUE;int theInt = Integer.MAX_VALUE;float theFloat = Float.MAX_VALUE;+ unicodeStrings = new String[NUM_DOCS];for (int i = 0; i < NUM_DOCS; i++){Document doc = new Document();doc.add(new Field("theLong", String.valueOf(theLong--), Field.Store.NO, Field.Index.NOT_ANALYZED));@@ -55,10 +64,28 @@ public class TestFieldCache extends LuceneTestCase {doc.add(new Field("theShort", String.valueOf(theShort--), Field.Store.NO, Field.Index.NOT_ANALYZED));doc.add(new Field("theInt", String.valueOf(theInt--), Field.Store.NO, Field.Index.NOT_ANALYZED));doc.add(new Field("theFloat", String.valueOf(theFloat--), Field.Store.NO, Field.Index.NOT_ANALYZED));++ // sometimes skip the field:+ if (r.nextInt(40) != 17) {+ String s = null;+ if (i > 0 && r.nextInt(3) == 1) {+ // reuse past string -- try to find one that's not null+ for(int iter=0;iter<10 && s==null;iter++) {+ s = unicodeStrings[r.nextInt(i)];+ }+ if (s == null) {+ s = _TestUtil.randomUnicodeString(r, 250);+ }+ } else {+ s = _TestUtil.randomUnicodeString(r, 250);+ }+ unicodeStrings[i] = s;+ doc.add(new Field("theRandomUnicodeString", unicodeStrings[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));+ }writer.addDocument(doc);}+ reader = writer.getReader();writer.close();- reader = IndexReader.open(directory, true);}public void testInfoStream() throws Exception {@@ -129,5 +156,43 @@ public class TestFieldCache extends LuceneTestCase {assertTrue(floats[i] + " does not equal: " + (Float.MAX_VALUE - i), floats[i] == (Float.MAX_VALUE - i));}++ // getTermsIndex+ FieldCache.DocTermsIndex termsIndex = cache.getTermsIndex(reader, "theRandomUnicodeString");+ assertSame("Second request to cache return same array", termsIndex, cache.getTermsIndex(reader, "theRandomUnicodeString"));+ assertTrue("doubles Size: " + termsIndex.size() + " is not: " + NUM_DOCS, termsIndex.size() == NUM_DOCS);+ final BytesRef br = new BytesRef();+ for (int i = 0; i < NUM_DOCS; i++) {+ final BytesRef term = termsIndex.getTerm(i, br);+ final String s = term == null ? null : term.utf8ToString();+ assertTrue("for doc " + i + ": " + s + " does not equal: " + unicodeStrings[i], unicodeStrings[i] == null || unicodeStrings[i].equals(s));+ }+ // test bad field+ termsIndex = cache.getTermsIndex(reader, "bogusfield");++ // getTerms+ FieldCache.DocTerms terms = cache.getTerms(reader, "theRandomUnicodeString");+ assertSame("Second request to cache return same array", terms, cache.getTerms(reader, "theRandomUnicodeString"));+ assertTrue("doubles Size: " + terms.size() + " is not: " + NUM_DOCS, terms.size() == NUM_DOCS);+ for (int i = 0; i < NUM_DOCS; i++) {+ final BytesRef term = terms.getTerm(i, br);+ final String s = term == null ? null : term.utf8ToString();+ assertTrue("for doc " + i + ": " + s + " does not equal: " + unicodeStrings[i], unicodeStrings[i] == null || unicodeStrings[i].equals(s));+ }++ // test bad field+ terms = cache.getTerms(reader, "bogusfield");++ FieldCache.DEFAULT.purge(reader);+ }++ public void testEmptyIndex() throws Exception {+ Directory dir = new MockRAMDirectory();+ IndexWriter writer= new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(500));+ IndexReader r = writer.getReader();+ FieldCache.DocTerms terms = FieldCache.DEFAULT.getTerms(r, "foobar");+ FieldCache.DocTermsIndex termsIndex = FieldCache.DEFAULT.getTermsIndex(r, "foobar");+ r.close();+ dir.close();}-}\ No newline at end of file+}diff --git a/lucene/src/test/org/apache/lucene/search/TestSort.java b/lucene/src/test/org/apache/lucene/search/TestSort.javaindex 5bd38a1be33..e664c8832c7 100644--- a/lucene/src/test/org/apache/lucene/search/TestSort.java+++ b/lucene/src/test/org/apache/lucene/search/TestSort.java@@ -43,6 +43,8 @@ import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.FieldValueHitQueue.Entry;import org.apache.lucene.store.LockObtainFailedException;import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.MockRAMDirectory;import org.apache.lucene.util.DocIdBitSet;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util._TestUtil;@@ -1012,4 +1014,29 @@ public class TestSort extends LuceneTestCase implements Serializable {}}+ public void testEmptyStringVsNullStringSort() throws Exception {+ Directory dir = new MockRAMDirectory();+ IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(+ TEST_VERSION_CURRENT, new MockAnalyzer()));+ Document doc = new Document();+ doc.add(new Field("f", "", Field.Store.NO, Field.Index.NOT_ANALYZED));+ doc.add(new Field("t", "1", Field.Store.NO, Field.Index.NOT_ANALYZED));+ w.addDocument(doc);+ w.commit();+ doc = new Document();+ doc.add(new Field("t", "1", Field.Store.NO, Field.Index.NOT_ANALYZED));+ w.addDocument(doc);++ IndexReader r = w.getReader();+ w.close();+ IndexSearcher s = new IndexSearcher(r);+ TopDocs hits = s.search(new TermQuery(new Term("t", "1")), null, 10, new Sort(new SortField("f", SortField.STRING)));+ assertEquals(2, hits.totalHits);+ // null sorts first+ assertEquals(1, hits.scoreDocs[0].doc);+ assertEquals(0, hits.scoreDocs[1].doc);+ r.close();+ dir.close();+ }+}diff --git a/lucene/src/test/org/apache/lucene/search/function/TestOrdValues.java b/lucene/src/test/org/apache/lucene/search/function/TestOrdValues.javaindex 2e0692088d7..9a1d02a673e 100644--- a/lucene/src/test/org/apache/lucene/search/function/TestOrdValues.java+++ b/lucene/src/test/org/apache/lucene/search/function/TestOrdValues.java@@ -207,7 +207,7 @@ public class TestOrdValues extends FunctionTestSetup {log("compare (should differ): " + innerArray + " to "+ q.valSrc.getValues(reader).getInnerArray());assertNotSame(- "different values shuold be loaded for a different field!",+ "different values should be loaded for a different field!",innerArray, q.valSrc.getValues(reader).getInnerArray());} catch (UnsupportedOperationException e) {if (!warned) {diff --git a/lucene/src/test/org/apache/lucene/util/TestFieldCacheSanityChecker.java b/lucene/src/test/org/apache/lucene/util/TestFieldCacheSanityChecker.javaindex 93397ee5463..99aaa809b23 100644--- a/lucene/src/test/org/apache/lucene/util/TestFieldCacheSanityChecker.java+++ b/lucene/src/test/org/apache/lucene/util/TestFieldCacheSanityChecker.java@@ -25,7 +25,6 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.MultiReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.FieldCacheSanityChecker.Insanity;import org.apache.lucene.util.FieldCacheSanityChecker.InsanityType;@@ -112,7 +111,7 @@ public class TestFieldCacheSanityChecker extends LuceneTestCase {cache.purgeAllCaches();cache.getInts(readerX, "theInt", FieldCache.DEFAULT_INT_PARSER);- cache.getStrings(readerX, "theInt");+ cache.getTerms(readerX, "theInt");cache.getBytes(readerX, "theByte");// // //@@ -135,9 +134,9 @@ public class TestFieldCacheSanityChecker extends LuceneTestCase {FieldCache cache = FieldCache.DEFAULT;cache.purgeAllCaches();- cache.getStrings(readerA, "theString");- cache.getStrings(readerB, "theString");- cache.getStrings(readerX, "theString");+ cache.getTerms(readerA, "theString");+ cache.getTerms(readerB, "theString");+ cache.getTerms(readerX, "theString");cache.getBytes(readerX, "theByte");diff --git a/lucene/src/test/org/apache/lucene/util/_TestUtil.java b/lucene/src/test/org/apache/lucene/util/_TestUtil.javaindex 44419149ae5..ab69de50de5 100644--- a/lucene/src/test/org/apache/lucene/util/_TestUtil.java+++ b/lucene/src/test/org/apache/lucene/util/_TestUtil.java@@ -118,7 +118,11 @@ public class _TestUtil {/** Returns random string, including full unicode range. */public static String randomUnicodeString(Random r) {- final int end = r.nextInt(20);+ return randomUnicodeString(r, 20);+ }++ public static String randomUnicodeString(Random r, int maxLength) {+ final int end = r.nextInt(maxLength);if (end == 0) {// allow 0 lengthreturn "";@@ -126,6 +130,7 @@ public class _TestUtil {final char[] buffer = new char[end];for (int i = 0; i < end; i++) {int t = r.nextInt(5);+ //buffer[i] = (char) (97 + r.nextInt(26));if (0 == t && i < end - 1) {// Make a surrogate pair// High surrogatediff --git a/solr/src/java/org/apache/solr/handler/component/FieldFacetStats.java b/solr/src/java/org/apache/solr/handler/component/FieldFacetStats.javaindex bf06779589e..c5555e110ce 100644--- a/solr/src/java/org/apache/solr/handler/component/FieldFacetStats.java+++ b/solr/src/java/org/apache/solr/handler/component/FieldFacetStats.java@@ -17,11 +17,11 @@ package org.apache.solr.handler.component;*/import org.apache.lucene.search.FieldCache;+import org.apache.lucene.util.BytesRef;import org.apache.solr.schema.FieldType;import java.util.ArrayList;import java.util.HashMap;-import java.util.Iterator;import java.util.List;import java.util.Map;@@ -37,12 +37,9 @@ import java.util.Map;public class FieldFacetStats {public final String name;- final FieldCache.StringIndex si;+ final FieldCache.DocTermsIndex si;final FieldType ft;- final String[] terms;- final int[] termNum;-final int startTermIndex;final int endTermIndex;final int nTerms;@@ -53,16 +50,16 @@ public class FieldFacetStats {final List<HashMap<String, Integer>> facetStatsTerms;- public FieldFacetStats(String name, FieldCache.StringIndex si, FieldType ft, int numStatsTerms) {+ private final BytesRef tempBR = new BytesRef();++ public FieldFacetStats(String name, FieldCache.DocTermsIndex si, FieldType ft, int numStatsTerms) {this.name = name;this.si = si;this.ft = ft;this.numStatsTerms = numStatsTerms;- terms = si.lookup;- termNum = si.order;startTermIndex = 1;- endTermIndex = terms.length;+ endTermIndex = si.numOrd();nTerms = endTermIndex - startTermIndex;facetStatsValues = new HashMap<String, StatsValues>();@@ -76,21 +73,27 @@ public class FieldFacetStats {}}- String getTermText(int docID) {- return terms[termNum[docID]];+ BytesRef getTermText(int docID, BytesRef ret) {+ final int ord = si.getOrd(docID);+ if (ord == 0) {+ return null;+ } else {+ return si.lookup(ord, ret);+ }}-public boolean facet(int docID, Double v) {- int term = termNum[docID];+ int term = si.getOrd(docID);int arrIdx = term - startTermIndex;if (arrIdx >= 0 && arrIdx < nTerms) {- String key = ft.indexedToReadable(terms[term]);+ final BytesRef br = si.lookup(term, tempBR);+ String key = ft.indexedToReadable(br == null ? null : br.utf8ToString());StatsValues stats = facetStatsValues.get(key);if (stats == null) {stats = new StatsValues();facetStatsValues.put(key, stats);}+if (v != null) {stats.accumulate(v);} else {@@ -107,10 +110,11 @@ public class FieldFacetStats {// Currently only used by UnInvertedField statspublic boolean facetTermNum(int docID, int statsTermNum) {- int term = termNum[docID];+ int term = si.getOrd(docID);int arrIdx = term - startTermIndex;if (arrIdx >= 0 && arrIdx < nTerms) {- String key = ft.indexedToReadable(terms[term]);+ final BytesRef br = si.lookup(term, tempBR);+ String key = br == null ? null : br.utf8ToString();HashMap<String, Integer> statsTermCounts = facetStatsTerms.get(statsTermNum);Integer statsTermCount = statsTermCounts.get(key);if (statsTermCount == null) {diff --git a/solr/src/java/org/apache/solr/handler/component/QueryComponent.java b/solr/src/java/org/apache/solr/handler/component/QueryComponent.javaindex c84b319d1c5..e52bc6295db 100644--- a/solr/src/java/org/apache/solr/handler/component/QueryComponent.java+++ b/solr/src/java/org/apache/solr/handler/component/QueryComponent.java@@ -24,6 +24,7 @@ import org.apache.lucene.search.FieldComparator;import org.apache.lucene.search.Query;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;+import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.apache.solr.common.SolrException;@@ -33,7 +34,6 @@ import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.StrUtils;-import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.schema.FieldType;@@ -259,6 +259,14 @@ public class QueryComponent extends SearchComponentval = ft.toObject(field);}+ // Must do the same conversion when sorting by a+ // String field in Lucene, which returns the terms+ // data as BytesRef:+ if (val instanceof BytesRef) {+ field.setValue(((BytesRef)val).utf8ToString());+ val = ft.toObject(field);+ }+vals.add(val);}diff --git a/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java b/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.javaindex f961cdd7dcd..91881a22834 100644--- a/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java+++ b/solr/src/java/org/apache/solr/handler/component/QueryElevationComponent.java@@ -44,6 +44,7 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;import org.apache.lucene.search.*;import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.DOMUtil;@@ -99,7 +100,7 @@ public class QueryElevationComponent extends SearchComponent implements SolrCorefinal String analyzed;final BooleanClause[] exclude;final BooleanQuery include;- final Map<String,Integer> priority;+ final Map<BytesRef,Integer> priority;// use singletons so hashCode/equals on Sort will just workfinal FieldComparatorSource comparatorSource;@@ -111,12 +112,12 @@ public class QueryElevationComponent extends SearchComponent implements SolrCorethis.include = new BooleanQuery();this.include.setBoost( 0 );- this.priority = new HashMap<String, Integer>();+ this.priority = new HashMap<BytesRef, Integer>();int max = elevate.size()+5;for( String id : elevate ) {TermQuery tq = new TermQuery( new Term( idField, id ) );include.add( tq, BooleanClause.Occur.SHOULD );- this.priority.put( id, max-- );+ this.priority.put( new BytesRef(id), max-- );}if( exclude == null || exclude.isEmpty() ) {@@ -445,18 +446,19 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore}class ElevationComparatorSource extends FieldComparatorSource {- private final Map<String,Integer> priority;+ private final Map<BytesRef,Integer> priority;- public ElevationComparatorSource( final Map<String,Integer> boosts) {+ public ElevationComparatorSource( final Map<BytesRef,Integer> boosts) {this.priority = boosts;}public FieldComparator newComparator(final String fieldname, final int numHits, int sortPos, boolean reversed) throws IOException {return new FieldComparator() {- FieldCache.StringIndex idIndex;+ FieldCache.DocTermsIndex idIndex;private final int[] values = new int[numHits];int bottomVal;+ private final BytesRef tempBR = new BytesRef();public int compare(int slot1, int slot2) {return values[slot2] - values[slot1]; // values will be small enough that there is no overflow concern@@ -467,7 +469,7 @@ class ElevationComparatorSource extends FieldComparatorSource {}private int docVal(int doc) throws IOException {- String id = idIndex.lookup[idIndex.order[doc]];+ BytesRef id = idIndex.getTerm(doc, tempBR);Integer prio = priority.get(id);return prio == null ? 0 : prio.intValue();}@@ -481,7 +483,7 @@ class ElevationComparatorSource extends FieldComparatorSource {}public void setNextReader(IndexReader reader, int docBase) throws IOException {- idIndex = FieldCache.DEFAULT.getStringIndex(reader, fieldname);+ idIndex = FieldCache.DEFAULT.getTermsIndex(reader, fieldname);}public Comparable value(int slot) {diff --git a/solr/src/java/org/apache/solr/handler/component/StatsComponent.java b/solr/src/java/org/apache/solr/handler/component/StatsComponent.javaindex 0c8df7121a3..8896d73d172 100644--- a/solr/src/java/org/apache/solr/handler/component/StatsComponent.java+++ b/solr/src/java/org/apache/solr/handler/component/StatsComponent.java@@ -22,15 +22,13 @@ import java.util.HashMap;import java.util.Map;import org.apache.lucene.search.FieldCache;-import org.apache.solr.common.SolrException;-import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.lucene.util.BytesRef;+import org.apache.noggit.CharArr;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.params.StatsParams;import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;-import org.apache.solr.handler.component.StatsValues;-import org.apache.solr.handler.component.FieldFacetStats;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.schema.FieldType;import org.apache.solr.schema.SchemaField;@@ -39,7 +37,6 @@ import org.apache.solr.search.DocIterator;import org.apache.solr.search.DocSet;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.request.UnInvertedField;-import org.apache.solr.core.SolrCore;/*** Stats component calculates simple statistics on numeric field values@@ -249,9 +246,9 @@ class SimpleStats {public NamedList getFieldCacheStats(String fieldName, String[] facet ) {FieldType ft = searcher.getSchema().getFieldType(fieldName);- FieldCache.StringIndex si = null;+ FieldCache.DocTermsIndex si = null;try {- si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), fieldName);+ si = FieldCache.DEFAULT.getTermsIndex(searcher.getReader(), fieldName);}catch (IOException e) {throw new RuntimeException( "failed to open field cache for: "+fieldName, e );@@ -266,23 +263,27 @@ class SimpleStats {for( String f : facet ) {ft = searcher.getSchema().getFieldType(f);try {- si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), f);+ si = FieldCache.DEFAULT.getTermsIndex(searcher.getReader(), f);}catch (IOException e) {throw new RuntimeException( "failed to open field cache for: "+f, e );}finfo[i++] = new FieldFacetStats( f, si, ft, 0 );}--++ final BytesRef tempBR = new BytesRef();+ final CharArr spare = new CharArr();+DocIterator iter = docs.iterator();while (iter.hasNext()) {int docID = iter.nextDoc();- String raw = all.getTermText(docID);+ BytesRef raw = all.getTermText(docID, tempBR);Double v = null;if( raw != null ) {- v = Double.parseDouble( all.ft.indexedToReadable(raw) );- allstats.accumulate( v );+ spare.reset();+ all.ft.indexedToReadable(raw, spare);+ v = Double.parseDouble(spare.toString());+ allstats.accumulate(v);}else {allstats.missing++;diff --git a/solr/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java b/solr/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.javaindex 82a743cfe67..f9fee77166b 100755--- a/solr/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java+++ b/solr/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java@@ -5,12 +5,11 @@ import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.search.FieldCache;import org.apache.lucene.search.Filter;import org.apache.lucene.util.PriorityQueue;+import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.FacetParams;import org.apache.solr.common.util.NamedList;-import org.apache.solr.core.SolrCore;import org.apache.solr.schema.FieldType;-import org.apache.solr.search.DocIterator;import org.apache.solr.search.DocSet;import org.apache.solr.search.SolrIndexReader;import org.apache.solr.search.SolrIndexSearcher;@@ -100,7 +99,7 @@ class PerSegmentSingleValuedFaceting {}@Overrideprotected boolean lessThan(SegFacet a, SegFacet b) {- return a.terms[a.pos].compareTo(b.terms[b.pos]) < 0;+ return a.si.lookup(a.pos, a.tempBR).compareTo(b.si.lookup(b.pos, b.tempBR)) < 0;}};@@ -150,9 +149,11 @@ class PerSegmentSingleValuedFaceting {collector = new IndexSortedFacetCollector(offset, limit, mincount);}+ final BytesRef tempBR = new BytesRef();+while (queue.size() > 0) {SegFacet seg = queue.top();- String val = seg.terms[seg.pos];+ BytesRef val = seg.si.lookup(seg.pos, tempBR);int count = 0;do {@@ -167,7 +168,7 @@ class PerSegmentSingleValuedFaceting {} else {seg = queue.updateTop();}- } while (seg != null && val.compareTo(seg.terms[seg.pos]) == 0);+ } while (seg != null && val.compareTo(seg.si.lookup(seg.pos, seg.tempBR)) == 0);boolean stop = collector.collect(val, count);if (stop) break;@@ -192,20 +193,6 @@ class PerSegmentSingleValuedFaceting {return res;}----- // first element of the fieldcache is null, so we need this comparator.- private static final Comparator nullStrComparator = new Comparator() {- public int compare(Object o1, Object o2) {- if (o1==null) return (o2==null) ? 0 : -1;- else if (o2==null) return 1;- return ((String)o1).compareTo((String)o2);- }- };--class SegFacet {SolrIndexReader reader;int readerOffset;@@ -215,32 +202,31 @@ class PerSegmentSingleValuedFaceting {this.readerOffset = readerOffset;}- int[] ords;- String[] terms;-+ FieldCache.DocTermsIndex si;int startTermIndex;int endTermIndex;int[] counts;int pos; // only used during merge with other segments+ final BytesRef tempBR = new BytesRef();+void countTerms() throws IOException {- FieldCache.StringIndex si = FieldCache.DEFAULT.getStringIndex(reader, fieldName);- final String[] terms = this.terms = si.lookup;- final int[] termNum = this.ords = si.order;+ si = FieldCache.DEFAULT.getTermsIndex(reader, fieldName);// SolrCore.log.info("reader= " + reader + " FC=" + System.identityHashCode(si));if (prefix!=null) {- startTermIndex = Arrays.binarySearch(terms,prefix,nullStrComparator);+ startTermIndex = si.binarySearchLookup(new BytesRef(prefix), tempBR);if (startTermIndex<0) startTermIndex=-startTermIndex-1;// find the end term. \uffff isn't a legal unicode char, but only compareTo// is used, so it should be fine, and is guaranteed to be bigger than legal chars.// TODO: switch to binarySearch version that takes start/end in Java6- endTermIndex = Arrays.binarySearch(terms,prefix+"\uffff\uffff\uffff\uffff",nullStrComparator);+ endTermIndex = si.binarySearchLookup(new BytesRef(prefix+"\uffff\uffff\uffff\uffff"), tempBR);+ assert endTermIndex < 0;endTermIndex = -endTermIndex-1;} else {startTermIndex=0;- endTermIndex=terms.length;+ endTermIndex=si.numOrd();}final int nTerms=endTermIndex-startTermIndex;@@ -251,17 +237,17 @@ class PerSegmentSingleValuedFaceting {DocIdSet idSet = baseSet.getDocIdSet(reader);DocIdSetIterator iter = idSet.iterator();- if (startTermIndex==0 && endTermIndex==terms.length) {+ if (startTermIndex==0 && endTermIndex==si.numOrd()) {// specialized version when collecting counts for all termsint doc;while ((doc = iter.nextDoc()) < DocIdSetIterator.NO_MORE_DOCS) {- counts[termNum[doc]]++;+ counts[si.getOrd(doc)]++;}} else {// version that adjusts term numbers because we aren't collecting the full rangeint doc;while ((doc = iter.nextDoc()) < DocIdSetIterator.NO_MORE_DOCS) {- int term = termNum[doc];+ int term = si.getOrd(doc);int arrIdx = term-startTermIndex;if (arrIdx>=0 && arrIdx<nTerms) counts[arrIdx]++;}@@ -276,7 +262,7 @@ class PerSegmentSingleValuedFaceting {abstract class FacetCollector {/*** return true to stop collection */- public abstract boolean collect(String term, int count);+ public abstract boolean collect(BytesRef term, int count);public abstract NamedList getFacetCounts();}@@ -299,12 +285,12 @@ class CountSortedFacetCollector extends FacetCollector {}@Override- public boolean collect(String term, int count) {+ public boolean collect(BytesRef term, int count) {if (count > min) {// NOTE: we use c>min rather than c>=min as an optimization because we are going in// index order, so we already know that the keys are ordered. This can be very// important if a lot of the counts are repeated (like zero counts would be).- queue.add(new SimpleFacets.CountPair<String,Integer>(term, count));+ queue.add(new SimpleFacets.CountPair<String,Integer>(term.utf8ToString(), count));if (queue.size()>=maxsize) min=queue.last().val;}return false;@@ -340,7 +326,7 @@ class IndexSortedFacetCollector extends FacetCollector {}@Override- public boolean collect(String term, int count) {+ public boolean collect(BytesRef term, int count) {if (count < mincount) {return false;}@@ -351,7 +337,7 @@ class IndexSortedFacetCollector extends FacetCollector {}if (limit > 0) {- res.add(term, count);+ res.add(term.utf8ToString(), count);limit--;}diff --git a/solr/src/java/org/apache/solr/request/SimpleFacets.java b/solr/src/java/org/apache/solr/request/SimpleFacets.javaindex 0dce2a10fe5..4bf8757a735 100644--- a/solr/src/java/org/apache/solr/request/SimpleFacets.java+++ b/solr/src/java/org/apache/solr/request/SimpleFacets.java@@ -21,7 +21,6 @@ import org.apache.lucene.index.*;import org.apache.lucene.queryParser.ParseException;import org.apache.lucene.search.*;import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.UnicodeUtil;import org.apache.noggit.CharArr;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.FacetParams;@@ -356,15 +355,6 @@ public class SimpleFacets {}- // first element of the fieldcache is null, so we need this comparator.- private static final Comparator nullStrComparator = new Comparator() {- public int compare(Object o1, Object o2) {- if (o1==null) return (o2==null) ? 0 : -1;- else if (o2==null) return 1;- return ((String)o1).compareTo((String)o2);- }- };-/*** Use the Lucene FieldCache to get counts for each unique field value in <code>docs</code>.* The field must have at most one indexed token per document.@@ -386,27 +376,38 @@ public class SimpleFacets {FieldType ft = searcher.getSchema().getFieldType(fieldName);NamedList res = new NamedList();- FieldCache.StringIndex si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), fieldName);- final String[] terms = si.lookup;- final int[] termNum = si.order;+ FieldCache.DocTermsIndex si = FieldCache.DEFAULT.getTermsIndex(searcher.getReader(), fieldName);- if (prefix!=null && prefix.length()==0) prefix=null;+ final BytesRef prefixRef;+ if (prefix == null) {+ prefixRef = null;+ } else if (prefix.length()==0) {+ prefix = null;+ prefixRef = null;+ } else {+ prefixRef = new BytesRef(prefix);+ }++ final BytesRef br = new BytesRef();int startTermIndex, endTermIndex;if (prefix!=null) {- startTermIndex = Arrays.binarySearch(terms,prefix,nullStrComparator);+ startTermIndex = si.binarySearchLookup(prefixRef, br);if (startTermIndex<0) startTermIndex=-startTermIndex-1;// find the end term. \uffff isn't a legal unicode char, but only compareTo// is used, so it should be fine, and is guaranteed to be bigger than legal chars.- endTermIndex = Arrays.binarySearch(terms,prefix+"\uffff\uffff\uffff\uffff",nullStrComparator);+ endTermIndex = si.binarySearchLookup(new BytesRef(prefix+"\uffff\uffff\uffff\uffff"), br);+ assert endTermIndex < 0;endTermIndex = -endTermIndex-1;} else {startTermIndex=1;- endTermIndex=terms.length;+ endTermIndex=si.numOrd();}final int nTerms=endTermIndex-startTermIndex;+ CharArr spare = new CharArr();+if (nTerms>0 && docs.size() >= mincount) {// count collection array only needs to be as big as the number of terms we are@@ -415,7 +416,7 @@ public class SimpleFacets {DocIterator iter = docs.iterator();while (iter.hasNext()) {- int term = termNum[iter.nextDoc()];+ int term = si.getOrd(iter.nextDoc());int arrIdx = term-startTermIndex;if (arrIdx>=0 && arrIdx<nTerms) counts[arrIdx]++;}@@ -429,7 +430,7 @@ public class SimpleFacets {if (sort.equals(FacetParams.FACET_SORT_COUNT) || sort.equals(FacetParams.FACET_SORT_COUNT_LEGACY)) {int maxsize = limit>0 ? offset+limit : Integer.MAX_VALUE-1;maxsize = Math.min(maxsize, nTerms);- final BoundedTreeSet<CountPair<String,Integer>> queue = new BoundedTreeSet<CountPair<String,Integer>>(maxsize);+ final BoundedTreeSet<CountPair<BytesRef,Integer>> queue = new BoundedTreeSet<CountPair<BytesRef,Integer>>(maxsize);int min=mincount-1; // the smallest value in the top 'N' valuesfor (int i=0; i<nTerms; i++) {int c = counts[i];@@ -437,15 +438,17 @@ public class SimpleFacets {// NOTE: we use c>min rather than c>=min as an optimization because we are going in// index order, so we already know that the keys are ordered. This can be very// important if a lot of the counts are repeated (like zero counts would be).- queue.add(new CountPair<String,Integer>(terms[startTermIndex+i], c));+ queue.add(new CountPair<BytesRef,Integer>(si.lookup(startTermIndex+i, new BytesRef()), c));if (queue.size()>=maxsize) min=queue.last().val;}}// now select the right page from the results- for (CountPair<String,Integer> p : queue) {+ for (CountPair<BytesRef,Integer> p : queue) {if (--off>=0) continue;if (--lim<0) break;- res.add(ft.indexedToReadable(p.key), p.val);+ spare.reset();+ ft.indexedToReadable(p.key, spare);+ res.add(spare.toString(), p.val);}} else {// add results in index order@@ -461,7 +464,9 @@ public class SimpleFacets {int c = counts[i];if (c<mincount || --off>=0) continue;if (--lim<0) break;- res.add(ft.indexedToReadable(terms[startTermIndex+i]), c);+ spare.reset();+ ft.indexedToReadable(si.lookup(startTermIndex+i, br), spare);+ res.add(spare.toString(), c);}}}diff --git a/solr/src/java/org/apache/solr/request/UnInvertedField.java b/solr/src/java/org/apache/solr/request/UnInvertedField.javaindex 5a595704108..017a1b18e40 100755--- a/solr/src/java/org/apache/solr/request/UnInvertedField.java+++ b/solr/src/java/org/apache/solr/request/UnInvertedField.java@@ -653,11 +653,11 @@ public class UnInvertedField {int i = 0;final FieldFacetStats[] finfo = new FieldFacetStats[facet.length];//Initialize facetstats, if facets have been passed in- FieldCache.StringIndex si;+ FieldCache.DocTermsIndex si;for (String f : facet) {FieldType facet_ft = searcher.getSchema().getFieldType(f);try {- si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), f);+ si = FieldCache.DEFAULT.getTermsIndex(searcher.getReader(), f);}catch (IOException e) {throw new RuntimeException("failed to open field cache for: " + f, e);diff --git a/solr/src/java/org/apache/solr/schema/DateField.java b/solr/src/java/org/apache/solr/schema/DateField.javaindex 1baa6c48877..a9395e3ff50 100644--- a/solr/src/java/org/apache/solr/schema/DateField.java+++ b/solr/src/java/org/apache/solr/schema/DateField.java@@ -443,7 +443,7 @@ class DateFieldSource extends FieldCacheSource {}public int intVal(int doc) {- int ord=order[doc];+ int ord=termsIndex.getOrd(doc);return ord;}@@ -456,8 +456,15 @@ class DateFieldSource extends FieldCacheSource {}public String strVal(int doc) {- int ord=order[doc];- return ft.indexedToReadable(lookup[ord]);+ int ord=termsIndex.getOrd(doc);+ if (ord == 0) {+ return null;+ } else {+ BytesRef br = termsIndex.lookup(ord, new BytesRef());+ CharArr spare = new CharArr();+ ft.indexedToReadable(br, spare);+ return spare.toString();+ }}public String toString(int doc) {diff --git a/solr/src/java/org/apache/solr/schema/SortableDoubleField.java b/solr/src/java/org/apache/solr/schema/SortableDoubleField.javaindex cb966df82f6..4ddfd131d64 100644--- a/solr/src/java/org/apache/solr/schema/SortableDoubleField.java+++ b/solr/src/java/org/apache/solr/schema/SortableDoubleField.java@@ -122,8 +122,8 @@ class SortableDoubleFieldSource extends FieldCacheSource {}public double doubleVal(int doc) {- int ord=order[doc];- return ord==0 ? def : NumberUtils.SortableStr2double(lookup[ord]);+ int ord=termsIndex.getOrd(doc);+ return ord==0 ? def : NumberUtils.SortableStr2double(termsIndex.lookup(ord, new BytesRef()));}public String strVal(int doc) {diff --git a/solr/src/java/org/apache/solr/schema/SortableFloatField.java b/solr/src/java/org/apache/solr/schema/SortableFloatField.javaindex 102f3d8b2b6..ebb33dd8340 100644--- a/solr/src/java/org/apache/solr/schema/SortableFloatField.java+++ b/solr/src/java/org/apache/solr/schema/SortableFloatField.java@@ -110,8 +110,8 @@ class SortableFloatFieldSource extends FieldCacheSource {}public float floatVal(int doc) {- int ord=order[doc];- return ord==0 ? def : NumberUtils.SortableStr2float(lookup[ord]);+ int ord=termsIndex.getOrd(doc);+ return ord==0 ? def : NumberUtils.SortableStr2float(termsIndex.lookup(ord, new BytesRef()));}public int intVal(int doc) {diff --git a/solr/src/java/org/apache/solr/schema/SortableIntField.java b/solr/src/java/org/apache/solr/schema/SortableIntField.javaindex 238a0b94384..24bafe29e29 100644--- a/solr/src/java/org/apache/solr/schema/SortableIntField.java+++ b/solr/src/java/org/apache/solr/schema/SortableIntField.java@@ -118,8 +118,8 @@ class SortableIntFieldSource extends FieldCacheSource {}public int intVal(int doc) {- int ord=order[doc];- return ord==0 ? def : NumberUtils.SortableStr2int(lookup[ord],0,3);+ int ord=termsIndex.getOrd(doc);+ return ord==0 ? def : NumberUtils.SortableStr2int(termsIndex.lookup(ord, new BytesRef()),0,3);}public long longVal(int doc) {diff --git a/solr/src/java/org/apache/solr/schema/SortableLongField.java b/solr/src/java/org/apache/solr/schema/SortableLongField.javaindex e7f8d6765dc..6bd0727ee9f 100644--- a/solr/src/java/org/apache/solr/schema/SortableLongField.java+++ b/solr/src/java/org/apache/solr/schema/SortableLongField.java@@ -119,8 +119,8 @@ class SortableLongFieldSource extends FieldCacheSource {}public long longVal(int doc) {- int ord=order[doc];- return ord==0 ? def : NumberUtils.SortableStr2long(lookup[ord],0,5);+ int ord=termsIndex.getOrd(doc);+ return ord==0 ? def : NumberUtils.SortableStr2long(termsIndex.lookup(ord, new BytesRef()),0,5);}public double doubleVal(int doc) {diff --git a/solr/src/java/org/apache/solr/schema/StrField.java b/solr/src/java/org/apache/solr/schema/StrField.javaindex 051a1532501..340769d7441 100644--- a/solr/src/java/org/apache/solr/schema/StrField.java+++ b/solr/src/java/org/apache/solr/schema/StrField.java@@ -20,6 +20,7 @@ package org.apache.solr.schema;import org.apache.lucene.search.SortField;import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.util.BytesRef;import org.apache.solr.response.TextResponseWriter;import org.apache.solr.response.XMLWriter;import org.apache.solr.search.function.ValueSource;@@ -77,7 +78,7 @@ class StrFieldSource extends FieldCacheSource {}public int intVal(int doc) {- int ord=order[doc];+ int ord=termsIndex.getOrd(doc);return ord;}@@ -90,8 +91,12 @@ class StrFieldSource extends FieldCacheSource {}public String strVal(int doc) {- int ord=order[doc];- return lookup[ord];+ int ord=termsIndex.getOrd(doc);+ if (ord == 0) {+ return null;+ } else {+ return termsIndex.lookup(ord, new BytesRef()).utf8ToString();+ }}public String toString(int doc) {diff --git a/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java b/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.javaindex 9dfcb2a1ae2..6b733f26025 100644--- a/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java+++ b/solr/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java@@ -19,6 +19,7 @@ package org.apache.solr.search;import org.apache.lucene.search.*;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.util.BytesRef;import java.io.IOException;@@ -53,33 +54,34 @@ public class MissingStringLastComparatorSource extends FieldComparatorSource {// be extended or have it's values accessed.class MissingLastOrdComparator extends FieldComparator {private static final int NULL_ORD = Integer.MAX_VALUE;- private final String nullVal;+ private final BytesRef nullVal;private final int[] ords;- private final String[] values;+ private final BytesRef[] values;private final int[] readerGen;private int currentReaderGen = -1;- private String[] lookup;- private int[] order;+ private FieldCache.DocTermsIndex termsIndex;private final String field;private int bottomSlot = -1;private int bottomOrd;- private String bottomValue;+ private BytesRef bottomValue;private final boolean reversed;private final int sortPos;+ private final BytesRef tempBR = new BytesRef();public MissingLastOrdComparator(int numHits, String field, int sortPos, boolean reversed, String nullVal) {ords = new int[numHits];- values = new String[numHits];+ values = new BytesRef[numHits];readerGen = new int[numHits];this.sortPos = sortPos;this.reversed = reversed;this.field = field;- this.nullVal = nullVal;+ this.nullVal = nullVal == null ? null : new BytesRef(nullVal);}+ @Overridepublic int compare(int slot1, int slot2) {if (readerGen[slot1] == readerGen[slot2]) {int cmp = ords[slot1] - ords[slot2];@@ -88,8 +90,8 @@ public class MissingStringLastComparatorSource extends FieldComparatorSource {}}- final String val1 = values[slot1];- final String val2 = values[slot2];+ final BytesRef val1 = values[slot1];+ final BytesRef val2 = values[slot2];if (val1 == null) {if (val2 == null) {@@ -104,43 +106,40 @@ public class MissingStringLastComparatorSource extends FieldComparatorSource {public int compareBottom(int doc) {assert bottomSlot != -1;- int order = this.order[doc];+ int order = termsIndex.getOrd(doc);int ord = (order == 0) ? NULL_ORD : order;final int cmp = bottomOrd - ord;if (cmp != 0) {return cmp;}- final String val2 = lookup[order];-// take care of the case where both vals are null- if (bottomValue == val2) return 0;-- return bottomValue.compareTo(val2);+ if (bottomOrd == NULL_ORD) return 0;+ return bottomValue.compareTo(termsIndex.lookup(order, tempBR));}private void convert(int slot) {readerGen[slot] = currentReaderGen;int index = 0;- String value = values[slot];+ BytesRef value = values[slot];if (value == null) {// should already be done- // ords[slot] = NULL_ORD;+ assert ords[slot] == NULL_ORD;return;}if (sortPos == 0 && bottomSlot != -1 && bottomSlot != slot) {// Since we are the primary sort, the entries in the// queue are bounded by bottomOrd:- assert bottomOrd < lookup.length;+ assert bottomOrd < termsIndex.numOrd();if (reversed) {- index = binarySearch(lookup, value, bottomOrd, lookup.length-1);+ index = binarySearch(tempBR, termsIndex, value, bottomOrd, termsIndex.numOrd()-1);} else {- index = binarySearch(lookup, value, 0, bottomOrd);+ index = binarySearch(tempBR, termsIndex, value, 0, bottomOrd);}} else {// Full binary search- index = binarySearch(lookup, value);+ index = binarySearch(tempBR, termsIndex, value);}if (index < 0) {@@ -149,26 +148,35 @@ public class MissingStringLastComparatorSource extends FieldComparatorSource {ords[slot] = index;}+ @Overridepublic void copy(int slot, int doc) {- final int ord = order[doc];- ords[slot] = ord == 0 ? NULL_ORD : ord;+ final int ord = termsIndex.getOrd(doc);assert ord >= 0;- values[slot] = lookup[ord];+ if (ord == 0) {+ ords[slot] = NULL_ORD;+ values[slot] = null;+ } else {+ ords[slot] = ord;+ if (values[slot] == null) {+ values[slot] = new BytesRef();+ }+ termsIndex.lookup(ord, values[slot]);+ }readerGen[slot] = currentReaderGen;}+ @Overridepublic void setNextReader(IndexReader reader, int docBase) throws IOException {- FieldCache.StringIndex currentReaderValues = FieldCache.DEFAULT.getStringIndex(reader, field);+ termsIndex = FieldCache.DEFAULT.getTermsIndex(reader, field);currentReaderGen++;- order = currentReaderValues.order;- lookup = currentReaderValues.lookup;- assert lookup.length > 0;+ assert termsIndex.numOrd() > 0;if (bottomSlot != -1) {convert(bottomSlot);bottomOrd = ords[bottomSlot];}}+ @Overridepublic void setBottom(final int bottom) {bottomSlot = bottom;if (readerGen[bottom] != currentReaderGen) {@@ -180,12 +188,13 @@ public class MissingStringLastComparatorSource extends FieldComparatorSource {bottomValue = values[bottom];}+ @Overridepublic Comparable value(int slot) {Comparable v = values[slot];return v==null ? nullVal : v;}- public String[] getValues() {+ public BytesRef[] getValues() {return values;}diff --git a/solr/src/java/org/apache/solr/search/function/DocValues.java b/solr/src/java/org/apache/solr/search/function/DocValues.javaindex 92e3ac6fd79..7ae0d51219a 100644--- a/solr/src/java/org/apache/solr/search/function/DocValues.java+++ b/solr/src/java/org/apache/solr/search/function/DocValues.java@@ -19,9 +19,6 @@ package org.apache.solr.search.function;import org.apache.lucene.search.*;import org.apache.lucene.index.IndexReader;-import org.apache.solr.util.NumberUtils;--import java.io.IOException;/*** Represents field values as different types.@@ -45,6 +42,7 @@ public abstract class DocValues {public int intVal(int doc) { throw new UnsupportedOperationException(); }public long longVal(int doc) { throw new UnsupportedOperationException(); }public double doubleVal(int doc) { throw new UnsupportedOperationException(); }+ // TODO: should we make a termVal, returns BytesRef?public String strVal(int doc) { throw new UnsupportedOperationException(); }public abstract String toString(int doc);@@ -56,6 +54,8 @@ public abstract class DocValues {public void intVal(int doc, int [] vals) { throw new UnsupportedOperationException(); }public void longVal(int doc, long [] vals) { throw new UnsupportedOperationException(); }public void doubleVal(int doc, double [] vals) { throw new UnsupportedOperationException(); }++ // TODO: should we make a termVal, fills BytesRef[]?public void strVal(int doc, String [] vals) { throw new UnsupportedOperationException(); }public Explanation explain(int doc) {diff --git a/solr/src/java/org/apache/solr/search/function/OrdFieldSource.java b/solr/src/java/org/apache/solr/search/function/OrdFieldSource.javaindex f3deed02d25..8e2d417a581 100644--- a/solr/src/java/org/apache/solr/search/function/OrdFieldSource.java+++ b/solr/src/java/org/apache/solr/search/function/OrdFieldSource.java@@ -18,8 +18,6 @@package org.apache.solr.search.function;import org.apache.lucene.index.IndexReader;-import org.apache.solr.search.function.DocValues;-import org.apache.solr.search.function.ValueSource;import java.io.IOException;import java.util.Map;@@ -61,24 +59,24 @@ public class OrdFieldSource extends ValueSource {}public float floatVal(int doc) {- return (float)order[doc];+ return (float)termsIndex.getOrd(doc);}public int intVal(int doc) {- return order[doc];+ return termsIndex.getOrd(doc);}public long longVal(int doc) {- return (long)order[doc];+ return (long)termsIndex.getOrd(doc);}public double doubleVal(int doc) {- return (double)order[doc];+ return (double)termsIndex.getOrd(doc);}public String strVal(int doc) {// the string value of the ordinal, not the string itself- return Integer.toString(order[doc]);+ return Integer.toString(termsIndex.getOrd(doc));}public String toString(int doc) {diff --git a/solr/src/java/org/apache/solr/search/function/ReverseOrdFieldSource.java b/solr/src/java/org/apache/solr/search/function/ReverseOrdFieldSource.javaindex 30e8836b67e..f669cb64ebd 100644--- a/solr/src/java/org/apache/solr/search/function/ReverseOrdFieldSource.java+++ b/solr/src/java/org/apache/solr/search/function/ReverseOrdFieldSource.java@@ -18,15 +18,13 @@package org.apache.solr.search.function;import org.apache.lucene.index.IndexReader;-import org.apache.solr.search.function.DocValues;-import org.apache.solr.search.function.ValueSource;import org.apache.lucene.search.FieldCache;import java.io.IOException;import java.util.Map;/**- * Obtains the ordinal of the field value from the default Lucene {@link org.apache.lucene.search.FieldCache} using getStringIndex()+ * Obtains the ordinal of the field value from the default Lucene {@link org.apache.lucene.search.FieldCache} using getTermsIndex()* and reverses the order.* <br>* The native lucene index order is used to assign an ordinal value for each field value.@@ -58,31 +56,30 @@ public class ReverseOrdFieldSource extends ValueSource {}public DocValues getValues(Map context, IndexReader reader) throws IOException {- final FieldCache.StringIndex sindex = FieldCache.DEFAULT.getStringIndex(reader, field);+ final FieldCache.DocTermsIndex sindex = FieldCache.DEFAULT.getTermsIndex(reader, field);- final int arr[] = sindex.order;- final int end = sindex.lookup.length;+ final int end = sindex.numOrd();return new DocValues() {public float floatVal(int doc) {- return (float)(end - arr[doc]);+ return (float)(end - sindex.getOrd(doc));}public int intVal(int doc) {- return (int)(end - arr[doc]);+ return (int)(end - sindex.getOrd(doc));}public long longVal(int doc) {- return (long)(end - arr[doc]);+ return (long)(end - sindex.getOrd(doc));}public double doubleVal(int doc) {- return (double)(end - arr[doc]);+ return (double)(end - sindex.getOrd(doc));}public String strVal(int doc) {// the string value of the ordinal, not the string itself- return Integer.toString((end - arr[doc]));+ return Integer.toString((end - sindex.getOrd(doc)));}public String toString(int doc) {diff --git a/solr/src/java/org/apache/solr/search/function/StringIndexDocValues.java b/solr/src/java/org/apache/solr/search/function/StringIndexDocValues.javaindex 980affe8cde..b983e31a208 100755--- a/solr/src/java/org/apache/solr/search/function/StringIndexDocValues.java+++ b/solr/src/java/org/apache/solr/search/function/StringIndexDocValues.java@@ -19,6 +19,7 @@ package org.apache.solr.search.function;import org.apache.lucene.search.FieldCache;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.util.BytesRef;import java.io.IOException;@@ -26,49 +27,47 @@ import java.io.IOException;* Serves as base class for DocValues based on StringIndex**/public abstract class StringIndexDocValues extends DocValues {- protected final FieldCache.StringIndex index;- protected final int[] order;- protected final String[] lookup;+ protected final FieldCache.DocTermsIndex termsIndex;protected final ValueSource vs;public StringIndexDocValues(ValueSource vs, IndexReader reader, String field) throws IOException {try {- index = FieldCache.DEFAULT.getStringIndex(reader, field);+ termsIndex = FieldCache.DEFAULT.getTermsIndex(reader, field);} catch (RuntimeException e) {throw new StringIndexException(field, e);}- order = index.order;- lookup = index.lookup;this.vs = vs;}protected abstract String toTerm(String readableValue);- @Override+ @Overridepublic ValueSourceScorer getRangeScorer(IndexReader reader, String lowerVal, String upperVal, boolean includeLower, boolean includeUpper) {// TODO: are lowerVal and upperVal in indexed form or not?lowerVal = lowerVal == null ? null : toTerm(lowerVal);upperVal = upperVal == null ? null : toTerm(upperVal);- int lower = Integer.MIN_VALUE;- if (lowerVal != null) {- lower = index.binarySearchLookup(lowerVal);- if (lower < 0) {- lower = -lower-1;- } else if (!includeLower) {- lower++;- }- }+ final BytesRef spare = new BytesRef();- int upper = Integer.MAX_VALUE;- if (upperVal != null) {- upper = index.binarySearchLookup(upperVal);- if (upper < 0) {- upper = -upper-2;- } else if (!includeUpper) {- upper--;- }- }+ int lower = Integer.MIN_VALUE;+ if (lowerVal != null) {+ lower = termsIndex.binarySearchLookup(new BytesRef(lowerVal), spare);+ if (lower < 0) {+ lower = -lower-1;+ } else if (!includeLower) {+ lower++;+ }+ }++ int upper = Integer.MAX_VALUE;+ if (upperVal != null) {+ upper = termsIndex.binarySearchLookup(new BytesRef(upperVal), spare);+ if (upper < 0) {+ upper = -upper-2;+ } else if (!includeUpper) {+ upper--;+ }+ }final int ll = lower;final int uu = upper;@@ -76,7 +75,7 @@ public abstract class StringIndexDocValues extends DocValues {return new ValueSourceScorer(reader, this) {@Overridepublic boolean matchesValue(int doc) {- int ord = order[doc];+ int ord = termsIndex.getOrd(doc);return ord >= ll && ord <= uu;}};diff --git a/solr/src/java/org/apache/solr/util/ByteUtils.java b/solr/src/java/org/apache/solr/util/ByteUtils.javaindex f6fdf7b6291..3e43c6c1746 100755--- a/solr/src/java/org/apache/solr/util/ByteUtils.java+++ b/solr/src/java/org/apache/solr/util/ByteUtils.java@@ -17,7 +17,6 @@package org.apache.solr.util;-import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.BytesRef;import org.apache.noggit.CharArr;@@ -31,8 +30,8 @@ public class ByteUtils {*/public static int UTF8toUTF16(byte[] utf8, int offset, int len, char[] out, int out_offset) {int out_start = out_offset;-- while (offset < len) {+ final int limit = offset + len;+ while (offset < limit) {int b = utf8[offset++]&0xff;if (b < 0xc0) {diff --git a/solr/src/java/org/apache/solr/util/NumberUtils.java b/solr/src/java/org/apache/solr/util/NumberUtils.javaindex 6ddc8b62143..2954a367eac 100644--- a/solr/src/java/org/apache/solr/util/NumberUtils.java+++ b/solr/src/java/org/apache/solr/util/NumberUtils.java@@ -17,6 +17,8 @@package org.apache.solr.util;+import org.apache.lucene.util.BytesRef;+/*** @version $Id$*/@@ -41,6 +43,11 @@ public class NumberUtils {return Integer.toString(ival);}+ public static String SortableStr2int(BytesRef val) {+ // TODO: operate directly on BytesRef+ return SortableStr2int(val.utf8ToString());+ }+public static String long2sortableStr(long val) {char[] arr = new char[5];@@ -57,6 +64,11 @@ public class NumberUtils {return Long.toString(ival);}+ public static String SortableStr2long(BytesRef val) {+ // TODO: operate directly on BytesRef+ return SortableStr2long(val.utf8ToString());+ }+//// IEEE floating point format is defined so that it sorts correctly// when interpreted as a signed integer (or signed long in the case@@ -85,6 +97,11 @@ public class NumberUtils {return Float.intBitsToFloat(f);}+ public static float SortableStr2float(BytesRef val) {+ // TODO: operate directly on BytesRef+ return SortableStr2float(val.utf8ToString());+ }+public static String SortableStr2floatStr(String val) {return Float.toString(SortableStr2float(val));}@@ -106,6 +123,11 @@ public class NumberUtils {return Double.longBitsToDouble(f);}+ public static double SortableStr2double(BytesRef val) {+ // TODO: operate directly on BytesRef+ return SortableStr2double(val.utf8ToString());+ }+public static String SortableStr2doubleStr(String val) {return Double.toString(SortableStr2double(val));}@@ -131,6 +153,11 @@ public class NumberUtils {return val;}+ public static int SortableStr2int(BytesRef sval, int offset, int len) {+ // TODO: operate directly on BytesRef+ return SortableStr2int(sval.utf8ToString(), offset, len);+ }+// uses binary representation of an int to build a string of// chars that will sort correctly. Only char ranges// less than 0xd800 will be used to avoid UCS-16 surrogates.@@ -155,5 +182,8 @@ public class NumberUtils {return val;}-+ public static long SortableStr2long(BytesRef sval, int offset, int len) {+ // TODO: operate directly on BytesRef+ return SortableStr2long(sval.utf8ToString(), offset, len);+ }}diff --git a/solr/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java b/solr/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.javaindex f45f81a2d73..f74af30c2f4 100644--- a/solr/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java+++ b/solr/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java@@ -18,7 +18,6 @@package org.apache.solr.handler.component;import java.io.File;-import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;@@ -26,6 +25,7 @@ import java.util.HashMap;import java.util.Map;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.util.BytesRef;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.MapSolrParams;@@ -34,7 +34,6 @@ import org.apache.solr.core.SolrCore;import org.apache.solr.handler.component.QueryElevationComponent.ElevationObj;import org.apache.solr.request.LocalSolrQueryRequest;import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.util.AbstractSolrTestCase;import org.junit.BeforeClass;import org.junit.Test;@@ -247,7 +246,7 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {IndexReader reader = core.getSearcher().get().getReader();Map<String, ElevationObj> map = comp.getElevationMap(reader, core);- assertTrue( map.get( "aaa" ).priority.containsKey( "A" ) );+ assertTrue( map.get( "aaa" ).priority.containsKey( new BytesRef("A") ) );assertNull( map.get( "bbb" ) );// now change the file@@ -258,6 +257,6 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {reader = core.getSearcher().get().getReader();map = comp.getElevationMap(reader, core);assertNull( map.get( "aaa" ) );- assertTrue( map.get( "bbb" ).priority.containsKey( "B" ) );+ assertTrue( map.get( "bbb" ).priority.containsKey( new BytesRef("B") ) );}}diff --git a/solr/src/test/org/apache/solr/search/TestIndexSearcher.java b/solr/src/test/org/apache/solr/search/TestIndexSearcher.javaindex 50e615f6c51..da9d715a27c 100755--- a/solr/src/test/org/apache/solr/search/TestIndexSearcher.java+++ b/solr/src/test/org/apache/solr/search/TestIndexSearcher.java@@ -21,7 +21,6 @@ import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.schema.SchemaField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.DocValues;-import org.apache.lucene.search.FieldCache;import java.util.Map;import java.io.IOException;@@ -32,18 +31,6 @@ public class TestIndexSearcher extends AbstractSolrTestCase {public String getSolrConfigFile() { return "solrconfig.xml"; }public String getCoreName() { return "basic"; }-- public void setUp() throws Exception {- // if you override setUp or tearDown, you better call- // the super classes version- super.setUp();- }- public void tearDown() throws Exception {- // if you override setUp or tearDown, you better call- // the super classes version- super.tearDown();- }-private String getStringVal(SolrQueryRequest sqr, String field, int doc) throws IOException {SchemaField sf = sqr.getSchema().getField(field);ValueSource vs = sf.getType().getValueSource(sf, null);@@ -80,9 +67,6 @@ public class TestIndexSearcher extends AbstractSolrTestCase {// Didn't work w/ older versions of lucene2.9 going from segment -> multiassertEquals(r1.getLeafReaders()[0], r2.getLeafReaders()[0]);- // make sure the String returned is the exact same instance (i.e. same FieldCache instance)- assertTrue(sval1 == getStringVal(sr2,"v_s",0));-assertU(adoc("id","5", "v_f","3.14159"));assertU(adoc("id","6", "v_f","8983", "v_s","string6"));assertU(commit());@@ -121,7 +105,6 @@ public class TestIndexSearcher extends AbstractSolrTestCase {SolrQueryRequest sr5 = req("q","foo");SolrIndexReader r5 = sr5.getSearcher().getReader();- String beforeDelete = getStringVal(sr5, "v_s",1);assertU(delI("1"));assertU(commit());@@ -129,8 +112,6 @@ public class TestIndexSearcher extends AbstractSolrTestCase {SolrIndexReader r6 = sr4.getSearcher().getReader();assertEquals(1, r6.getLeafReaders()[0].numDocs()); // only a single doc left in the first segmentassertTrue( !r5.getLeafReaders()[0].equals(r6.getLeafReaders()[0]) ); // readers now different- String afterDelete = getStringVal(sr6, "v_s",1);- assertTrue( beforeDelete == afterDelete ); // same field cache is used even though deletions are differentsr5.close();sr6.close();diff --git a/solr/src/test/org/apache/solr/search/TestSort.java b/solr/src/test/org/apache/solr/search/TestSort.javaindex 8d60d66c7de..d5c59a3b0a7 100755--- a/solr/src/test/org/apache/solr/search/TestSort.java+++ b/solr/src/test/org/apache/solr/search/TestSort.java@@ -115,7 +115,6 @@ public class TestSort extends AbstractSolrTestCase {if (r.nextBoolean()) sfields.add( new SortField(null, SortField.SCORE));// hit both use-cases of sort-missing-lastsfields.add( Sorting.getStringSortField("f", reverse, sortMissingLast, !sortMissingLast) );- int sortIdx = sfields.size() - 1;if (r.nextBoolean()) sfields.add( new SortField(null, SortField.SCORE));Sort sort = new Sort(sfields.toArray(new SortField[sfields.size()]));@@ -174,7 +173,6 @@ public class TestSort extends AbstractSolrTestCase {ScoreDoc[] sdocs = topDocs.scoreDocs;for (int j=0; j<sdocs.length; j++) {int id = sdocs[j].doc;- String s = (String)((FieldDoc)sdocs[j]).fields[sortIdx];if (id != collectedDocs.get(j).doc) {log.error("Error at pos " + j);}