Apache Lucene open-source search software
LUCENE-5819: add terms dict and postings format that implement term ordinals
Michael McCandless80fe3c277f30
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex e526295a70a..c8b8fa3f9a0 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -118,6 +118,11 @@ New Features"any" term) are allowed. This is a generalization ofMultiPhraseQuery and span queries, and enables "correct" (includingposition) length search-time graph synonyms. (Mike McCandless)++* LUCENE-5819: Add OrdsLucene41 block tree terms dict and postings+ format, to include term ordinals in the index so the optional+ TermsEnum.ord() and TermsEnum.seekExact(long ord) APIs work. (Mike+ McCandless)API Changesdiff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/FSTOrdsOutputs.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/FSTOrdsOutputs.javanew file mode 100644index 00000000000..6c5778a8291--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/FSTOrdsOutputs.java@@ -0,0 +1,233 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.store.DataInput;+import org.apache.lucene.store.DataOutput;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.fst.Outputs;++/** A custom FST outputs implementation that stores block data+ * (BytesRef), long ordStart, long numTerms. */++final class FSTOrdsOutputs extends Outputs<FSTOrdsOutputs.Output> {++ public static final Output NO_OUTPUT = new Output(new BytesRef(), 0, 0);++ private static final BytesRef NO_BYTES = new BytesRef();++ public static final class Output {+ public final BytesRef bytes;+ // Inclusive:+ public final long startOrd;+ // Inclusive:+ public final long endOrd;++ public Output(BytesRef bytes, long startOrd, long endOrd) {+ assert startOrd >= 0: "startOrd=" + startOrd;+ assert endOrd >= 0: "endOrd=" + endOrd;+ this.bytes = bytes;+ this.startOrd = startOrd;+ this.endOrd = endOrd;+ }++ @Override+ public String toString() {+ long x;+ if (endOrd > Long.MAX_VALUE/2) {+ x = Long.MAX_VALUE-endOrd;+ } else {+ assert endOrd >= 0;+ x = -endOrd;+ }+ return startOrd + " to " + x;+ }++ @Override+ public int hashCode() {+ int hash = bytes.hashCode();+ hash = (int) (hash ^ startOrd);+ hash = (int) (hash ^ endOrd);+ return hash;+ }++ @Override+ public boolean equals(Object _other) {+ if (_other instanceof Output) {+ Output other = (Output) _other;+ return bytes.equals(other.bytes) && startOrd == other.startOrd && endOrd == other.endOrd;+ } else {+ return false;+ }+ }+ }++ @Override+ public Output common(Output output1, Output output2) {+ BytesRef bytes1 = output1.bytes;+ BytesRef bytes2 = output2.bytes;++ assert bytes1 != null;+ assert bytes2 != null;++ int pos1 = bytes1.offset;+ int pos2 = bytes2.offset;+ int stopAt1 = pos1 + Math.min(bytes1.length, bytes2.length);+ while(pos1 < stopAt1) {+ if (bytes1.bytes[pos1] != bytes2.bytes[pos2]) {+ break;+ }+ pos1++;+ pos2++;+ }++ BytesRef prefixBytes;++ if (pos1 == bytes1.offset) {+ // no common prefix+ prefixBytes = NO_BYTES;+ } else if (pos1 == bytes1.offset + bytes1.length) {+ // bytes1 is a prefix of bytes2+ prefixBytes = bytes1;+ } else if (pos2 == bytes2.offset + bytes2.length) {+ // bytes2 is a prefix of bytes1+ prefixBytes = bytes2;+ } else {+ prefixBytes = new BytesRef(bytes1.bytes, bytes1.offset, pos1-bytes1.offset);+ }++ return newOutput(prefixBytes,+ Math.min(output1.startOrd, output2.startOrd),+ Math.min(output1.endOrd, output2.endOrd));+ }++ @Override+ public Output subtract(Output output, Output inc) {+ assert output != null;+ assert inc != null;+ if (inc == NO_OUTPUT) {+ // no prefix removed+ return output;+ } else {+ assert StringHelper.startsWith(output.bytes, inc.bytes);+ BytesRef suffix;+ if (inc.bytes.length == output.bytes.length) {+ // entire output removed+ suffix = NO_BYTES;+ } else if (inc.bytes.length == 0) {+ suffix = output.bytes;+ } else {+ assert inc.bytes.length < output.bytes.length: "inc.length=" + inc.bytes.length + " vs output.length=" + output.bytes.length;+ assert inc.bytes.length > 0;+ suffix = new BytesRef(output.bytes.bytes, output.bytes.offset + inc.bytes.length, output.bytes.length-inc.bytes.length);+ }+ assert output.startOrd >= inc.startOrd;+ assert output.endOrd >= inc.endOrd;+ return newOutput(suffix, output.startOrd-inc.startOrd, output.endOrd - inc.endOrd);+ }+ }++ @Override+ public Output add(Output prefix, Output output) {+ assert prefix != null;+ assert output != null;+ if (prefix == NO_OUTPUT) {+ return output;+ } else if (output == NO_OUTPUT) {+ return prefix;+ } else {+ BytesRef bytes = new BytesRef(prefix.bytes.length + output.bytes.length);+ System.arraycopy(prefix.bytes.bytes, prefix.bytes.offset, bytes.bytes, 0, prefix.bytes.length);+ System.arraycopy(output.bytes.bytes, output.bytes.offset, bytes.bytes, prefix.bytes.length, output.bytes.length);+ bytes.length = prefix.bytes.length + output.bytes.length;+ return newOutput(bytes, prefix.startOrd + output.startOrd, prefix.endOrd + output.endOrd);+ }+ }++ @Override+ public void write(Output prefix, DataOutput out) throws IOException {+ out.writeVInt(prefix.bytes.length);+ out.writeBytes(prefix.bytes.bytes, prefix.bytes.offset, prefix.bytes.length);+ out.writeVLong(prefix.startOrd);+ out.writeVLong(prefix.endOrd);+ }++ @Override+ public Output read(DataInput in) throws IOException {+ int len = in.readVInt();+ BytesRef bytes;+ if (len == 0) {+ bytes = NO_BYTES;+ } else {+ bytes = new BytesRef(len);+ in.readBytes(bytes.bytes, 0, len);+ bytes.length = len;+ }++ long startOrd = in.readVLong();+ long endOrd = in.readVLong();++ Output result = newOutput(bytes, startOrd, endOrd);++ return result;+ }++ @Override+ public void skipOutput(DataInput in) throws IOException {+ int len = in.readVInt();+ in.skipBytes(len);+ in.readVLong();+ in.readVLong();+ }++ @Override+ public void skipFinalOutput(DataInput in) throws IOException {+ skipOutput(in);+ }++ @Override+ public Output getNoOutput() {+ return NO_OUTPUT;+ }++ @Override+ public String outputToString(Output output) {+ if ((output.endOrd == 0 || output.endOrd == Long.MAX_VALUE) && output.startOrd == 0) {+ return "";+ } else {+ return output.toString();+ }+ }++ public Output newOutput(BytesRef bytes, long startOrd, long endOrd) {+ if (bytes.length == 0 && startOrd == 0 && endOrd == 0) {+ return NO_OUTPUT;+ } else {+ return new Output(bytes, startOrd, endOrd);+ }+ }++ @Override+ public long ramBytesUsed(Output output) {+ return 2 * RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 2 * RamUsageEstimator.NUM_BYTES_LONG + 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + 2 * RamUsageEstimator.NUM_BYTES_INT + output.bytes.length;+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/Ords41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/Ords41PostingsFormat.javanew file mode 100644index 00000000000..07021e948f8--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/Ords41PostingsFormat.java@@ -0,0 +1,111 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.FieldsConsumer;+import org.apache.lucene.codecs.FieldsProducer;+import org.apache.lucene.codecs.PostingsFormat;+import org.apache.lucene.codecs.PostingsReaderBase;+import org.apache.lucene.codecs.PostingsWriterBase;+import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;+import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.util.IOUtils;++/** Uses {@link OrdsBlockTreeTermsWriter} with {@link Lucene41PostingsWriter}. */+public class Ords41PostingsFormat extends PostingsFormat {++ private final int minTermBlockSize;+ private final int maxTermBlockSize;++ /**+ * Fixed packed block size, number of integers encoded in+ * a single packed block.+ */+ // NOTE: must be multiple of 64 because of PackedInts long-aligned encoding/decoding+ public final static int BLOCK_SIZE = 128;++ /** Creates {@code Lucene41PostingsFormat} with default+ * settings. */+ public Ords41PostingsFormat() {+ this(OrdsBlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, OrdsBlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);+ }++ /** Creates {@code Lucene41PostingsFormat} with custom+ * values for {@code minBlockSize} and {@code+ * maxBlockSize} passed to block terms dictionary.+ * @see OrdsBlockTreeTermsWriter#OrdsBlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int) */+ public Ords41PostingsFormat(int minTermBlockSize, int maxTermBlockSize) {+ super("OrdsLucene41");+ this.minTermBlockSize = minTermBlockSize;+ assert minTermBlockSize > 1;+ this.maxTermBlockSize = maxTermBlockSize;+ assert minTermBlockSize <= maxTermBlockSize;+ }++ @Override+ public String toString() {+ return getName() + "(blocksize=" + BLOCK_SIZE + ")";+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {+ PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state);++ boolean success = false;+ try {+ FieldsConsumer ret = new OrdsBlockTreeTermsWriter(state,+ postingsWriter,+ minTermBlockSize,+ maxTermBlockSize);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(postingsWriter);+ }+ }+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {+ PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.directory,+ state.fieldInfos,+ state.segmentInfo,+ state.context,+ state.segmentSuffix);+ boolean success = false;+ try {+ FieldsProducer ret = new OrdsBlockTreeTermsReader(state.directory,+ state.fieldInfos,+ state.segmentInfo,+ postingsReader,+ state.context,+ state.segmentSuffix);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(postingsReader);+ }+ }+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.javanew file mode 100644index 00000000000..adce3e12011--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java@@ -0,0 +1,246 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.Collections;+import java.util.Iterator;+import java.util.TreeMap;++import org.apache.lucene.codecs.CodecUtil;+import org.apache.lucene.codecs.FieldsProducer;+import org.apache.lucene.codecs.PostingsReaderBase;+import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.CorruptIndexException;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;+import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.SegmentInfo;+import org.apache.lucene.index.Terms;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IOUtils;++/**+ * See {@link OrdsBlockTreeTermsWriter}.+ *+ * @lucene.experimental+ */++public final class OrdsBlockTreeTermsReader extends FieldsProducer {++ // Open input to the main terms dict file (_X.tiv)+ final IndexInput in;++ //private static final boolean DEBUG = BlockTreeTermsWriter.DEBUG;++ // Reads the terms dict entries, to gather state to+ // produce DocsEnum on demand+ final PostingsReaderBase postingsReader;++ private final TreeMap<String,OrdsFieldReader> fields = new TreeMap<>();++ /** File offset where the directory starts in the terms file. */+ private long dirOffset;++ /** File offset where the directory starts in the index file. */+ private long indexDirOffset;++ final String segment;++ private final int version;++ /** Sole constructor. */+ public OrdsBlockTreeTermsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo info,+ PostingsReaderBase postingsReader, IOContext ioContext,+ String segmentSuffix)+ throws IOException {++ this.postingsReader = postingsReader;++ this.segment = info.name;+ in = dir.openInput(IndexFileNames.segmentFileName(segment, segmentSuffix, OrdsBlockTreeTermsWriter.TERMS_EXTENSION),+ ioContext);++ boolean success = false;+ IndexInput indexIn = null;++ try {+ version = CodecUtil.checkHeader(in,+ OrdsBlockTreeTermsWriter.TERMS_CODEC_NAME,+ OrdsBlockTreeTermsWriter.VERSION_START,+ OrdsBlockTreeTermsWriter.VERSION_CURRENT);+ indexIn = dir.openInput(IndexFileNames.segmentFileName(segment, segmentSuffix, OrdsBlockTreeTermsWriter.TERMS_INDEX_EXTENSION),+ ioContext);+ int indexVersion = CodecUtil.checkHeader(indexIn,+ OrdsBlockTreeTermsWriter.TERMS_INDEX_CODEC_NAME,+ OrdsBlockTreeTermsWriter.VERSION_START,+ OrdsBlockTreeTermsWriter.VERSION_CURRENT);+ if (indexVersion != version) {+ throw new CorruptIndexException("mixmatched version files: " + in + "=" + version + "," + indexIn + "=" + indexVersion);+ }++ // verify+ CodecUtil.checksumEntireFile(indexIn);++ // Have PostingsReader init itself+ postingsReader.init(in);++ // Read per-field details+ seekDir(in, dirOffset);+ seekDir(indexIn, indexDirOffset);++ final int numFields = in.readVInt();+ if (numFields < 0) {+ throw new CorruptIndexException("invalid numFields: " + numFields + " (resource=" + in + ")");+ }++ for(int i=0;i<numFields;i++) {+ final int field = in.readVInt();+ final long numTerms = in.readVLong();+ assert numTerms >= 0;+ // System.out.println("read field=" + field + " numTerms=" + numTerms + " i=" + i);+ final int numBytes = in.readVInt();+ final BytesRef code = new BytesRef(new byte[numBytes]);+ in.readBytes(code.bytes, 0, numBytes);+ code.length = numBytes;+ final Output rootCode = OrdsBlockTreeTermsWriter.FST_OUTPUTS.newOutput(code, 0, numTerms);+ final FieldInfo fieldInfo = fieldInfos.fieldInfo(field);+ assert fieldInfo != null: "field=" + field;+ assert numTerms <= Integer.MAX_VALUE;+ final long sumTotalTermFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS_ONLY ? -1 : in.readVLong();+ final long sumDocFreq = in.readVLong();+ final int docCount = in.readVInt();+ final int longsSize = in.readVInt();+ // System.out.println(" longsSize=" + longsSize);++ BytesRef minTerm = readBytesRef(in);+ BytesRef maxTerm = readBytesRef(in);+ if (docCount < 0 || docCount > info.getDocCount()) { // #docs with field must be <= #docs+ throw new CorruptIndexException("invalid docCount: " + docCount + " maxDoc: " + info.getDocCount() + " (resource=" + in + ")");+ }+ if (sumDocFreq < docCount) { // #postings must be >= #docs with field+ throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount + " (resource=" + in + ")");+ }+ if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings+ throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq + " (resource=" + in + ")");+ }+ final long indexStartFP = indexIn.readVLong();+ OrdsFieldReader previous = fields.put(fieldInfo.name,+ new OrdsFieldReader(this, fieldInfo, numTerms, rootCode, sumTotalTermFreq, sumDocFreq, docCount,+ indexStartFP, longsSize, indexIn, minTerm, maxTerm));+ if (previous != null) {+ throw new CorruptIndexException("duplicate field: " + fieldInfo.name + " (resource=" + in + ")");+ }+ }+ indexIn.close();++ success = true;+ } finally {+ if (!success) {+ // this.close() will close in:+ IOUtils.closeWhileHandlingException(indexIn, this);+ }+ }+ }++ private static BytesRef readBytesRef(IndexInput in) throws IOException {+ BytesRef bytes = new BytesRef();+ bytes.length = in.readVInt();+ bytes.bytes = new byte[bytes.length];+ in.readBytes(bytes.bytes, 0, bytes.length);+ return bytes;+ }++ /** Seek {@code input} to the directory offset. */+ private void seekDir(IndexInput input, long dirOffset)+ throws IOException {+ input.seek(input.length() - CodecUtil.footerLength() - 8);+ dirOffset = input.readLong();+ input.seek(dirOffset);+ }++ // for debugging+ // private static String toHex(int v) {+ // return "0x" + Integer.toHexString(v);+ // }++ @Override+ public void close() throws IOException {+ try {+ IOUtils.close(in, postingsReader);+ } finally {+ // Clear so refs to terms index is GCable even if+ // app hangs onto us:+ fields.clear();+ }+ }++ @Override+ public Iterator<String> iterator() {+ return Collections.unmodifiableSet(fields.keySet()).iterator();+ }++ @Override+ public Terms terms(String field) throws IOException {+ assert field != null;+ return fields.get(field);+ }++ @Override+ public int size() {+ return fields.size();+ }++ // for debugging+ String brToString(BytesRef b) {+ if (b == null) {+ return "null";+ } else {+ try {+ return b.utf8ToString() + " " + b;+ } catch (Throwable t) {+ // If BytesRef isn't actually UTF8, or it's eg a+ // prefix of UTF8 that ends mid-unicode-char, we+ // fallback to hex:+ return b.toString();+ }+ }+ }++ @Override+ public long ramBytesUsed() {+ long sizeInByes = ((postingsReader!=null) ? postingsReader.ramBytesUsed() : 0);+ for (OrdsFieldReader reader : fields.values()) {+ sizeInByes += reader.ramBytesUsed();+ }+ return sizeInByes;+ }++ @Override+ public void checkIntegrity() throws IOException {+ // term dictionary+ CodecUtil.checksumEntireFile(in);++ // postings+ postingsReader.checkIntegrity();+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.javanew file mode 100644index 00000000000..155bf6d0976--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java@@ -0,0 +1,1101 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.CodecUtil;+import org.apache.lucene.codecs.FieldsConsumer;+import org.apache.lucene.codecs.PostingsWriterBase;+import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;+import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;+import org.apache.lucene.index.Fields;+import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.RAMOutputStream;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.FixedBitSet;+import org.apache.lucene.util.IOUtils;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.fst.Builder;+import org.apache.lucene.util.fst.BytesRefFSTEnum;+import org.apache.lucene.util.fst.FST;+import org.apache.lucene.util.fst.NoOutputs;+import org.apache.lucene.util.fst.Util;+import org.apache.lucene.util.packed.PackedInts;++/*+ TODO:++ - Currently there is a one-to-one mapping of indexed+ term to term block, but we could decouple the two, ie,+ put more terms into the index than there are blocks.+ The index would take up more RAM but then it'd be able+ to avoid seeking more often and could make PK/FuzzyQ+ faster if the additional indexed terms could store+ the offset into the terms block.++ - The blocks are not written in true depth-first+ order, meaning if you just next() the file pointer will+ sometimes jump backwards. For example, block foo* will+ be written before block f* because it finished before.+ This could possibly hurt performance if the terms dict is+ not hot, since OSs anticipate sequential file access. We+ could fix the writer to re-order the blocks as a 2nd+ pass.++ - Each block encodes the term suffixes packed+ sequentially using a separate vInt per term, which is+ 1) wasteful and 2) slow (must linear scan to find a+ particular suffix). We should instead 1) make+ random-access array so we can directly access the Nth+ suffix, and 2) bulk-encode this array using bulk int[]+ codecs; then at search time we can binary search when+ we seek a particular term.+*/++/**+ * This is just like {@link BlockTreeTermsWriter}, except it also stores a version per term, and adds a method to its TermsEnum+ * implementation to seekExact only if the version is >= the specified version. The version is added to the terms index to avoid seeking if+ * no term in the block has a high enough version. The term blocks file is .tiv and the terms index extension is .tipv.+ *+ * @lucene.experimental+ */++public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {++ // private static boolean DEBUG = IDOrdsSegmentTermsEnum.DEBUG;++ static final FSTOrdsOutputs FST_OUTPUTS = new FSTOrdsOutputs();++ static final Output NO_OUTPUT = FST_OUTPUTS.getNoOutput();++ /** Suggested default value for the {@code+ * minItemsInBlock} parameter to {@link+ * #OrdsBlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)}. */+ public final static int DEFAULT_MIN_BLOCK_SIZE = 25;++ /** Suggested default value for the {@code+ * maxItemsInBlock} parameter to {@link+ * #OrdsBlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)}. */+ public final static int DEFAULT_MAX_BLOCK_SIZE = 48;++ //public final static boolean DEBUG = false;+ //private final static boolean SAVE_DOT_FILES = false;++ static final int OUTPUT_FLAGS_NUM_BITS = 2;+ static final int OUTPUT_FLAGS_MASK = 0x3;+ static final int OUTPUT_FLAG_IS_FLOOR = 0x1;+ static final int OUTPUT_FLAG_HAS_TERMS = 0x2;++ /** Extension of terms file */+ static final String TERMS_EXTENSION = "tio";+ final static String TERMS_CODEC_NAME = "BLOCK_TREE_ORDS_TERMS_DICT";++ /** Initial terms format. */+ public static final int VERSION_START = 0;++ /** Current terms format. */+ public static final int VERSION_CURRENT = VERSION_START;++ /** Extension of terms index file */+ static final String TERMS_INDEX_EXTENSION = "tipo";+ final static String TERMS_INDEX_CODEC_NAME = "BLOCK_TREE_ORDS_TERMS_INDEX";++ private final IndexOutput out;+ private final IndexOutput indexOut;+ final int maxDoc;+ final int minItemsInBlock;+ final int maxItemsInBlock;++ final PostingsWriterBase postingsWriter;+ final FieldInfos fieldInfos;++ private static class FieldMetaData {+ public final FieldInfo fieldInfo;+ public final Output rootCode;+ public final long numTerms;+ public final long indexStartFP;+ public final long sumTotalTermFreq;+ public final long sumDocFreq;+ public final int docCount;+ private final int longsSize;+ public final BytesRef minTerm;+ public final BytesRef maxTerm;++ public FieldMetaData(FieldInfo fieldInfo, Output rootCode, long numTerms, long indexStartFP,+ long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize,+ BytesRef minTerm, BytesRef maxTerm) {+ assert numTerms > 0;+ this.fieldInfo = fieldInfo;+ assert rootCode != null: "field=" + fieldInfo.name + " numTerms=" + numTerms;+ this.rootCode = rootCode;+ this.indexStartFP = indexStartFP;+ this.numTerms = numTerms;+ this.sumTotalTermFreq = sumTotalTermFreq;+ this.sumDocFreq = sumDocFreq;+ this.docCount = docCount;+ this.longsSize = longsSize;+ this.minTerm = minTerm;+ this.maxTerm = maxTerm;+ }+ }++ private final List<FieldMetaData> fields = new ArrayList<>();++ // private final String segment;++ /** Create a new writer. The number of items (terms or+ * sub-blocks) per block will aim to be between+ * minItemsPerBlock and maxItemsPerBlock, though in some+ * cases the blocks may be smaller than the min. */+ public OrdsBlockTreeTermsWriter(+ SegmentWriteState state,+ PostingsWriterBase postingsWriter,+ int minItemsInBlock,+ int maxItemsInBlock)+ throws IOException+ {+ if (minItemsInBlock <= 1) {+ throw new IllegalArgumentException("minItemsInBlock must be >= 2; got " + minItemsInBlock);+ }+ if (maxItemsInBlock <= 0) {+ throw new IllegalArgumentException("maxItemsInBlock must be >= 1; got " + maxItemsInBlock);+ }+ if (minItemsInBlock > maxItemsInBlock) {+ throw new IllegalArgumentException("maxItemsInBlock must be >= minItemsInBlock; got maxItemsInBlock=" + maxItemsInBlock + " minItemsInBlock=" + minItemsInBlock);+ }+ if (2*(minItemsInBlock-1) > maxItemsInBlock) {+ throw new IllegalArgumentException("maxItemsInBlock must be at least 2*(minItemsInBlock-1); got maxItemsInBlock=" + maxItemsInBlock + " minItemsInBlock=" + minItemsInBlock);+ }++ maxDoc = state.segmentInfo.getDocCount();++ final String termsFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_EXTENSION);+ out = state.directory.createOutput(termsFileName, state.context);+ boolean success = false;+ IndexOutput indexOut = null;+ try {+ fieldInfos = state.fieldInfos;+ this.minItemsInBlock = minItemsInBlock;+ this.maxItemsInBlock = maxItemsInBlock;+ CodecUtil.writeHeader(out, TERMS_CODEC_NAME, VERSION_CURRENT);++ final String termsIndexFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_INDEX_EXTENSION);+ indexOut = state.directory.createOutput(termsIndexFileName, state.context);+ CodecUtil.writeHeader(indexOut, TERMS_INDEX_CODEC_NAME, VERSION_CURRENT);++ this.postingsWriter = postingsWriter;+ // segment = state.segmentInfo.name;++ // System.out.println("BTW.init seg=" + state.segmentName);++ postingsWriter.init(out); // have consumer write its format/header+ success = true;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(out, indexOut);+ }+ }+ this.indexOut = indexOut;+ }++ @Override+ public void write(Fields fields) throws IOException {++ String lastField = null;+ for(String field : fields) {+ assert lastField == null || lastField.compareTo(field) < 0;+ lastField = field;++ Terms terms = fields.terms(field);+ if (terms == null) {+ continue;+ }++ TermsEnum termsEnum = terms.iterator(null);++ TermsWriter termsWriter = new TermsWriter(fieldInfos.fieldInfo(field));+ BytesRef minTerm = null;+ BytesRef maxTerm = new BytesRef();+ while (true) {+ BytesRef term = termsEnum.next();+ if (term == null) {+ break;+ }+ if (minTerm == null) {+ minTerm = BytesRef.deepCopyOf(term);+ }+ maxTerm.copyBytes(term);+ termsWriter.write(term, termsEnum);+ }++ termsWriter.finish(minTerm, minTerm == null ? null : maxTerm);+ }+ }++ static long encodeOutput(long fp, boolean hasTerms, boolean isFloor) {+ assert fp < (1L << 62);+ return (fp << 2) | (hasTerms ? OUTPUT_FLAG_HAS_TERMS : 0) | (isFloor ? OUTPUT_FLAG_IS_FLOOR : 0);+ }++ private static class PendingEntry {+ public final boolean isTerm;++ protected PendingEntry(boolean isTerm) {+ this.isTerm = isTerm;+ }+ }++ private static final class PendingTerm extends PendingEntry {+ public final BytesRef term;+ // stats + metadata+ public final BlockTermState state;++ public PendingTerm(BytesRef term, BlockTermState state) {+ super(true);+ this.term = term;+ this.state = state;+ }++ @Override+ public String toString() {+ return term.utf8ToString();+ }+ }++ private static final class SubIndex {+ public final FST<Output> index;+ public final long termOrdStart;++ public SubIndex(FST<Output> index, long termOrdStart) {+ this.index = index;+ this.termOrdStart = termOrdStart;+ }+ }++ private static final class PendingBlock extends PendingEntry {+ public final BytesRef prefix;+ public final long fp;+ public FST<Output> index;+ public List<SubIndex> subIndices;+ public final boolean hasTerms;+ public final boolean isFloor;+ public final int floorLeadByte;+ public long totFloorTermCount;+ private final long totalTermCount;+ private final IntsRef scratchIntsRef = new IntsRef();++ public PendingBlock(BytesRef prefix, long fp, boolean hasTerms, long totalTermCount,+ boolean isFloor, int floorLeadByte, List<SubIndex> subIndices) {+ super(false);+ this.prefix = prefix;+ this.fp = fp;+ this.hasTerms = hasTerms;+ this.totalTermCount = totalTermCount;+ this.isFloor = isFloor;+ this.floorLeadByte = floorLeadByte;+ this.subIndices = subIndices;+ }++ @Override+ public String toString() {+ return "BLOCK: " + prefix.utf8ToString();+ }++ public void compileIndex(List<PendingBlock> floorBlocks, RAMOutputStream scratchBytes) throws IOException {++ assert (isFloor && floorBlocks != null && floorBlocks.size() != 0) || (!isFloor && floorBlocks == null): "isFloor=" + isFloor + " floorBlocks=" + floorBlocks;++ assert scratchBytes.getFilePointer() == 0;++ // TODO: try writing the leading vLong in MSB order+ // (opposite of what Lucene does today), for better+ // outputs sharing in the FST+ //System.out.println("\ncompileIndex isFloor=" + isFloor + " numTerms=" + totalTermCount);+ long lastSumTotalTermCount = 0;+ long sumTotalTermCount = totalTermCount;+ scratchBytes.writeVLong(encodeOutput(fp, hasTerms, isFloor));+ if (isFloor) {+ scratchBytes.writeVInt(floorBlocks.size());+ for (PendingBlock sub : floorBlocks) {+ assert sub.floorLeadByte != -1;+ //if (DEBUG) {+ // System.out.println(" write floorLeadByte=" + Integer.toHexString(sub.floorLeadByte&0xff));+ //}+ scratchBytes.writeByte((byte) sub.floorLeadByte);+ // System.out.println(" write floor byte=" + (byte) sub.floorLeadByte + " ordShift=" + sumTotalTermCount);+ scratchBytes.writeVLong(sumTotalTermCount - lastSumTotalTermCount);+ lastSumTotalTermCount = sumTotalTermCount;+ sumTotalTermCount += sub.totalTermCount;+ assert sub.fp > fp;+ scratchBytes.writeVLong((sub.fp - fp) << 1 | (sub.hasTerms ? 1 : 0));+ }+ }++ final Builder<Output> indexBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1,+ 0, 0, true, false, Integer.MAX_VALUE,+ FST_OUTPUTS, null, false,+ PackedInts.COMPACT, true, 15);+ //if (DEBUG) {+ // System.out.println(" compile index for prefix=" + prefix);+ //}+ //indexBuilder.DEBUG = false;+ final byte[] bytes = new byte[(int) scratchBytes.getFilePointer()];+ assert bytes.length > 0;+ // System.out.println(" bytes=" + bytes.length);+ scratchBytes.writeTo(bytes, 0);+ indexBuilder.add(Util.toIntsRef(prefix, scratchIntsRef),+ FST_OUTPUTS.newOutput(new BytesRef(bytes, 0, bytes.length),+ 0, Long.MAX_VALUE-(sumTotalTermCount-1)));+ scratchBytes.reset();++ // Copy over index for all sub-blocks++ if (subIndices != null) {+ for(SubIndex subIndex : subIndices) {+ //System.out.println(" append subIndex: termOrdStart=" + subIndex.termOrdStart);+ append(indexBuilder, subIndex.index, subIndex.termOrdStart);+ }+ }++ if (floorBlocks != null) {+ long termOrdOffset = totalTermCount;+ for (PendingBlock sub : floorBlocks) {+ if (sub.subIndices != null) {+ for(SubIndex subIndex : sub.subIndices) {+ append(indexBuilder, subIndex.index, termOrdOffset + subIndex.termOrdStart);+ }+ }+ sub.subIndices = null;+ termOrdOffset += sub.totalTermCount;+ }+ totFloorTermCount = termOrdOffset;+ } else {+ totFloorTermCount = sumTotalTermCount;+ }++ index = indexBuilder.finish();+ subIndices = null;++ /*+ Writer w = new OutputStreamWriter(new FileOutputStream("out.dot"));+ Util.toDot(index, w, false, false);+ System.out.println("SAVED to out.dot");+ w.close();+ */+ }++ // TODO: maybe we could add bulk-add method to+ // Builder? Takes FST and unions it w/ current+ // FST.+ private void append(Builder<Output> builder, FST<Output> subIndex, long termOrdOffset) throws IOException {+ final BytesRefFSTEnum<Output> subIndexEnum = new BytesRefFSTEnum<>(subIndex);+ BytesRefFSTEnum.InputOutput<Output> indexEnt;+ while ((indexEnt = subIndexEnum.next()) != null) {+ //if (DEBUG) {+ // System.out.println(" add sub=" + indexEnt.input + " " + indexEnt.input + " output=" + indexEnt.output);+ //}+ Output output = indexEnt.output;+ long blockTermCount = output.endOrd - output.startOrd + 1;+ Output newOutput = FST_OUTPUTS.newOutput(output.bytes, termOrdOffset+output.startOrd, output.endOrd-termOrdOffset);+ //System.out.println(" append sub=" + indexEnt.input + " output=" + indexEnt.output + " termOrdOffset=" + termOrdOffset + " blockTermCount=" + blockTermCount + " newOutput=" + newOutput + " endOrd=" + (termOrdOffset+Long.MAX_VALUE-output.endOrd));+ builder.add(Util.toIntsRef(indexEnt.input, scratchIntsRef), newOutput);+ }+ }+ }++ final RAMOutputStream scratchBytes = new RAMOutputStream();++ class TermsWriter {+ private final FieldInfo fieldInfo;+ private final int longsSize;+ private long numTerms;+ final FixedBitSet docsSeen;+ long sumTotalTermFreq;+ long sumDocFreq;+ long indexStartFP;++ // Used only to partition terms into the block tree; we+ // don't pull an FST from this builder:+ private final NoOutputs noOutputs;+ private final Builder<Object> blockBuilder;++ // PendingTerm or PendingBlock:+ private final List<PendingEntry> pending = new ArrayList<>();++ // Index into pending of most recently written block+ private int lastBlockIndex = -1;++ // Re-used when segmenting a too-large block into floor+ // blocks:+ private int[] subBytes = new int[10];+ private int[] subTermCounts = new int[10];+ private int[] subTermCountSums = new int[10];+ private int[] subSubCounts = new int[10];++ // This class assigns terms to blocks "naturally", ie,+ // according to the number of terms under a given prefix+ // that we encounter:+ private class FindBlocks extends Builder.FreezeTail<Object> {++ @Override+ public void freeze(final Builder.UnCompiledNode<Object>[] frontier, int prefixLenPlus1, final IntsRef lastInput) throws IOException {++ //if (DEBUG) System.out.println(" freeze prefixLenPlus1=" + prefixLenPlus1);++ for(int idx=lastInput.length; idx >= prefixLenPlus1; idx--) {+ final Builder.UnCompiledNode<Object> node = frontier[idx];++ long totCount = 0;++ if (node.isFinal) {+ totCount++;+ }++ for(int arcIdx=0;arcIdx<node.numArcs;arcIdx++) {+ @SuppressWarnings("unchecked") final Builder.UnCompiledNode<Object> target = (Builder.UnCompiledNode<Object>) node.arcs[arcIdx].target;+ totCount += target.inputCount;+ target.clear();+ node.arcs[arcIdx].target = null;+ }+ node.numArcs = 0;++ if (totCount >= minItemsInBlock || idx == 0) {+ // We are on a prefix node that has enough+ // entries (terms or sub-blocks) under it to let+ // us write a new block or multiple blocks (main+ // block + follow on floor blocks):+ //if (DEBUG) {+ // if (totCount < minItemsInBlock && idx != 0) {+ // System.out.println(" force block has terms");+ // }+ //}+ writeBlocks(lastInput, idx, (int) totCount);+ node.inputCount = 1;+ } else {+ // stragglers! carry count upwards+ node.inputCount = totCount;+ }+ frontier[idx] = new Builder.UnCompiledNode<>(blockBuilder, idx);+ }+ }+ }++ // Write the top count entries on the pending stack as+ // one or more blocks. Returns how many blocks were+ // written. If the entry count is <= maxItemsPerBlock+ // we just write a single block; else we break into+ // primary (initial) block and then one or more+ // following floor blocks:++ void writeBlocks(IntsRef prevTerm, int prefixLength, int count) throws IOException {+ if (count <= maxItemsInBlock) {+ // Easy case: not floor block. Eg, prefix is "foo",+ // and we found 30 terms/sub-blocks starting w/ that+ // prefix, and minItemsInBlock <= 30 <=+ // maxItemsInBlock.+ final PendingBlock nonFloorBlock = writeBlock(prevTerm, prefixLength, prefixLength, count, count, 0, false, -1, true);+ nonFloorBlock.compileIndex(null, scratchBytes);+ pending.add(nonFloorBlock);+ } else {+ // Floor block case. Eg, prefix is "foo" but we+ // have 100 terms/sub-blocks starting w/ that+ // prefix. We segment the entries into a primary+ // block and following floor blocks using the first+ // label in the suffix to assign to floor blocks.++ // TODO: we could store min & max suffix start byte+ // in each block, to make floor blocks authoritative++ /*+ if (DEBUG) {+ final BytesRef prefix = new BytesRef(prefixLength);+ for(int m=0;m<prefixLength;m++) {+ prefix.bytes[m] = (byte) prevTerm.ints[m];+ }+ prefix.length = prefixLength;+ //System.out.println("\nWBS count=" + count + " prefix=" + prefix.utf8ToString() + " " + prefix);+ System.out.println("writeBlocks: prefix=" + toString(prefix) + " " + prefix + " count=" + count + " pending.size()=" + pending.size());+ }+ */+ //System.out.println("\nwbs count=" + count);++ final int savLabel = prevTerm.ints[prevTerm.offset + prefixLength];++ // Count up how many items fall under+ // each unique label after the prefix.++ // TODO: this is wasteful since the builder had+ // already done this (partitioned these sub-terms+ // according to their leading prefix byte)++ final List<PendingEntry> slice = pending.subList(pending.size()-count, pending.size());+ int lastSuffixLeadLabel = -1;+ int termCount = 0;+ int subCount = 0;+ int numSubs = 0;++ for(PendingEntry ent : slice) {++ // First byte in the suffix of this term+ final int suffixLeadLabel;+ if (ent.isTerm) {+ PendingTerm term = (PendingTerm) ent;+ if (term.term.length == prefixLength) {+ // Suffix is 0, ie prefix 'foo' and term is+ // 'foo' so the term has empty string suffix+ // in this block+ assert lastSuffixLeadLabel == -1;+ assert numSubs == 0;+ suffixLeadLabel = -1;+ } else {+ suffixLeadLabel = term.term.bytes[term.term.offset + prefixLength] & 0xff;+ }+ } else {+ PendingBlock block = (PendingBlock) ent;+ assert block.prefix.length > prefixLength;+ suffixLeadLabel = block.prefix.bytes[block.prefix.offset + prefixLength] & 0xff;+ }++ if (suffixLeadLabel != lastSuffixLeadLabel && (termCount + subCount) != 0) {+ if (subBytes.length == numSubs) {+ subBytes = ArrayUtil.grow(subBytes);+ subTermCounts = ArrayUtil.grow(subTermCounts);+ subSubCounts = ArrayUtil.grow(subSubCounts);+ }+ subBytes[numSubs] = lastSuffixLeadLabel;+ lastSuffixLeadLabel = suffixLeadLabel;+ subTermCounts[numSubs] = termCount;+ subSubCounts[numSubs] = subCount;+ /*+ if (suffixLeadLabel == -1) {+ System.out.println(" sub " + -1 + " termCount=" + termCount + " subCount=" + subCount);+ } else {+ System.out.println(" sub " + Integer.toHexString(suffixLeadLabel) + " termCount=" + termCount + " subCount=" + subCount);+ }+ */+ termCount = subCount = 0;+ numSubs++;+ }++ if (ent.isTerm) {+ termCount++;+ } else {+ subCount++;+ }+ }++ if (subBytes.length == numSubs) {+ subBytes = ArrayUtil.grow(subBytes);+ subTermCounts = ArrayUtil.grow(subTermCounts);+ subSubCounts = ArrayUtil.grow(subSubCounts);+ }++ subBytes[numSubs] = lastSuffixLeadLabel;+ subTermCounts[numSubs] = termCount;+ subSubCounts[numSubs] = subCount;+ numSubs++;+ /*+ if (lastSuffixLeadLabel == -1) {+ System.out.println(" sub " + -1 + " termCount=" + termCount + " subCount=" + subCount);+ } else {+ System.out.println(" sub " + Integer.toHexString(lastSuffixLeadLabel) + " termCount=" + termCount + " subCount=" + subCount);+ }+ */++ if (subTermCountSums.length < numSubs) {+ subTermCountSums = ArrayUtil.grow(subTermCountSums, numSubs);+ }++ // Roll up (backwards) the termCounts; postings impl+ // needs this to know where to pull the term slice+ // from its pending terms stack:+ int sum = 0;+ for(int idx=numSubs-1;idx>=0;idx--) {+ sum += subTermCounts[idx];+ subTermCountSums[idx] = sum;+ }++ // TODO: make a better segmenter? It'd have to+ // absorb the too-small end blocks backwards into+ // the previous blocks++ // Naive greedy segmentation; this is not always+ // best (it can produce a too-small block as the+ // last block):+ int pendingCount = 0;+ int startLabel = subBytes[0];+ int curStart = count;+ subCount = 0;++ final List<PendingBlock> floorBlocks = new ArrayList<>();+ PendingBlock firstBlock = null;++ for(int sub=0;sub<numSubs;sub++) {+ pendingCount += subTermCounts[sub] + subSubCounts[sub];+ //System.out.println(" " + (subTermCounts[sub] + subSubCounts[sub]));+ subCount++;++ // Greedily make a floor block as soon as we've+ // crossed the min count+ if (pendingCount >= minItemsInBlock) {+ final int curPrefixLength;+ if (startLabel == -1) {+ curPrefixLength = prefixLength;+ } else {+ curPrefixLength = 1+prefixLength;+ // floor term:+ prevTerm.ints[prevTerm.offset + prefixLength] = startLabel;+ }+ //System.out.println(" " + subCount + " subs");+ final PendingBlock floorBlock = writeBlock(prevTerm, prefixLength, curPrefixLength, curStart, pendingCount, subTermCountSums[1+sub], true, startLabel, curStart == pendingCount);+ if (firstBlock == null) {+ firstBlock = floorBlock;+ } else {+ floorBlocks.add(floorBlock);+ }+ curStart -= pendingCount;+ //System.out.println(" = " + pendingCount);+ pendingCount = 0;++ assert minItemsInBlock == 1 || subCount > 1: "minItemsInBlock=" + minItemsInBlock + " subCount=" + subCount + " sub=" + sub + " of " + numSubs + " subTermCount=" + subTermCountSums[sub] + " subSubCount=" + subSubCounts[sub] + " depth=" + prefixLength;+ subCount = 0;+ startLabel = subBytes[sub+1];++ if (curStart == 0) {+ break;+ }++ if (curStart <= maxItemsInBlock) {+ // remainder is small enough to fit into a+ // block. NOTE that this may be too small (<+ // minItemsInBlock); need a true segmenter+ // here+ assert startLabel != -1;+ assert firstBlock != null;+ prevTerm.ints[prevTerm.offset + prefixLength] = startLabel;+ //System.out.println(" final " + (numSubs-sub-1) + " subs");+ /*+ for(sub++;sub < numSubs;sub++) {+ System.out.println(" " + (subTermCounts[sub] + subSubCounts[sub]));+ }+ System.out.println(" = " + curStart);+ if (curStart < minItemsInBlock) {+ System.out.println(" **");+ }+ */+ floorBlocks.add(writeBlock(prevTerm, prefixLength, prefixLength+1, curStart, curStart, 0, true, startLabel, true));+ break;+ }+ }+ }++ prevTerm.ints[prevTerm.offset + prefixLength] = savLabel;++ assert firstBlock != null;+ firstBlock.compileIndex(floorBlocks, scratchBytes);++ pending.add(firstBlock);+ //if (DEBUG) System.out.println(" done pending.size()=" + pending.size());+ }+ lastBlockIndex = pending.size()-1;+ }++ // BytesRef prefix;++ // for debugging+ @SuppressWarnings("unused")+ private String toString(BytesRef b) {+ try {+ return b.utf8ToString() + " " + b;+ } catch (Throwable t) {+ // If BytesRef isn't actually UTF8, or it's eg a+ // prefix of UTF8 that ends mid-unicode-char, we+ // fallback to hex:+ return b.toString();+ }+ }++ // Writes all entries in the pending slice as a single+ // block:+ private PendingBlock writeBlock(IntsRef prevTerm, int prefixLength, int indexPrefixLength, int startBackwards, int length,+ int futureTermCount, boolean isFloor, int floorLeadByte, boolean isLastInFloor) throws IOException {++ assert length > 0;++ final int start = pending.size()-startBackwards;++ assert start >= 0: "pending.size()=" + pending.size() + " startBackwards=" + startBackwards + " length=" + length;++ final List<PendingEntry> slice = pending.subList(start, start + length);++ final long startFP = out.getFilePointer();++ // System.out.println("\nwriteBlock field=" + fieldInfo.name + " seg=" + segment + " prefixLength=" + prefixLength + " floorLeadByte=" + floorLeadByte + " isLastInFloor=" + isLastInFloor + " length=" + length + " startFP=" + startFP);++ final BytesRef prefix = new BytesRef(indexPrefixLength);+ for(int m=0;m<indexPrefixLength;m++) {+ prefix.bytes[m] = (byte) prevTerm.ints[m];+ }+ prefix.length = indexPrefixLength;+ // System.out.println(" prefix=" + toString(prefix));+ // this.prefix = prefix;++ // Write block header:+ out.writeVInt((length<<1)|(isLastInFloor ? 1:0));++ // if (DEBUG) {+ // System.out.println(" writeBlock " + (isFloor ? "(floor) " : "") + "seg=" + segment + " pending.size()=" + pending.size() + " prefixLength=" + prefixLength + " indexPrefix=" + toString(prefix) + " entCount=" + length + " startFP=" + startFP + " futureTermCount=" + futureTermCount + (isFloor ? (" floorLeadByte=" + Integer.toHexString(floorLeadByte&0xff)) : "") + " isLastInFloor=" + isLastInFloor);+ // }++ // 1st pass: pack term suffix bytes into byte[] blob+ // TODO: cutover to bulk int codec... simple64?++ final boolean isLeafBlock;+ if (lastBlockIndex < start) {+ // This block definitely does not contain sub-blocks:+ isLeafBlock = true;+ //System.out.println("no scan true isFloor=" + isFloor);+ } else if (!isFloor) {+ // This block definitely does contain at least one sub-block:+ isLeafBlock = false;+ //System.out.println("no scan false " + lastBlockIndex + " vs start=" + start + " len=" + length);+ } else {+ // Must scan up-front to see if there is a sub-block+ boolean v = true;+ //System.out.println("scan " + lastBlockIndex + " vs start=" + start + " len=" + length);+ for (PendingEntry ent : slice) {+ if (!ent.isTerm) {+ v = false;+ break;+ }+ }+ isLeafBlock = v;+ }+ // System.out.println(" isLeaf=" + isLeafBlock);++ final List<SubIndex> subIndices;++ // Number of terms in this block+ int termCount;++ // Number of terms in this block and all sub-blocks (recursively)+ long totalTermCount;++ long[] longs = new long[longsSize];+ boolean absolute = true;++ int countx = 0;+ if (isLeafBlock) {+ subIndices = null;+ for (PendingEntry ent : slice) {+ assert ent.isTerm;+ PendingTerm term = (PendingTerm) ent;+ BlockTermState state = term.state;+ final int suffix = term.term.length - prefixLength;+ /*+ if (DEBUG) {+ BytesRef suffixBytes = new BytesRef(suffix);+ System.arraycopy(term.term.bytes, prefixLength, suffixBytes.bytes, 0, suffix);+ suffixBytes.length = suffix;+ System.out.println(" " + (countx++) + ": write term suffix=" + toString(suffixBytes));+ }+ */+ // For leaf block we write suffix straight+ suffixWriter.writeVInt(suffix);+ suffixWriter.writeBytes(term.term.bytes, prefixLength, suffix);++ // Write term stats, to separate byte[] blob:+ statsWriter.writeVInt(state.docFreq);+ if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {+ assert state.totalTermFreq >= state.docFreq: state.totalTermFreq + " vs " + state.docFreq;+ statsWriter.writeVLong(state.totalTermFreq - state.docFreq);+ }+ // System.out.println(" dF=" + state.docFreq + " tTF=" + state.totalTermFreq);++ // Write term meta data+ postingsWriter.encodeTerm(longs, bytesWriter, fieldInfo, state, absolute);+ for (int pos = 0; pos < longsSize; pos++) {+ assert longs[pos] >= 0;+ metaWriter.writeVLong(longs[pos]);+ }+ bytesWriter.writeTo(metaWriter);+ bytesWriter.reset();+ absolute = false;+ }+ termCount = length;+ totalTermCount = length;+ } else {+ subIndices = new ArrayList<>();+ termCount = 0;+ totalTermCount = 0;+ for (PendingEntry ent : slice) {+ if (ent.isTerm) {+ PendingTerm term = (PendingTerm) ent;+ BlockTermState state = term.state;+ final int suffix = term.term.length - prefixLength;+ /*+ if (DEBUG) {+ BytesRef suffixBytes = new BytesRef(suffix);+ System.arraycopy(term.term.bytes, prefixLength, suffixBytes.bytes, 0, suffix);+ suffixBytes.length = suffix;+ System.out.println(" " + (countx++) + ": write term suffix=" + toString(suffixBytes) + " termOrd=" + totalTermCount);+ }+ */+ // For non-leaf block we borrow 1 bit to record+ // if entry is term or sub-block+ suffixWriter.writeVInt(suffix<<1);+ suffixWriter.writeBytes(term.term.bytes, prefixLength, suffix);++ // Write term stats, to separate byte[] blob:+ statsWriter.writeVInt(state.docFreq);+ if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {+ assert state.totalTermFreq >= state.docFreq;+ statsWriter.writeVLong(state.totalTermFreq - state.docFreq);+ }++ // TODO: now that terms dict "sees" these longs,+ // we can explore better column-stride encodings+ // to encode all long[0]s for this block at+ // once, all long[1]s, etc., e.g. using+ // Simple64. Alternatively, we could interleave+ // stats + meta ... no reason to have them+ // separate anymore:++ // Write term meta data+ postingsWriter.encodeTerm(longs, bytesWriter, fieldInfo, state, absolute);+ for (int pos = 0; pos < longsSize; pos++) {+ assert longs[pos] >= 0;+ metaWriter.writeVLong(longs[pos]);+ }+ bytesWriter.writeTo(metaWriter);+ bytesWriter.reset();+ absolute = false;++ termCount++;+ totalTermCount++;+ } else {+ PendingBlock block = (PendingBlock) ent;+ final int suffix = block.prefix.length - prefixLength;++ assert suffix > 0;++ // For non-leaf block we steal 1 bit to record+ // if entry is term or sub-block+ suffixWriter.writeVInt((suffix<<1)|1);+ suffixWriter.writeBytes(block.prefix.bytes, prefixLength, suffix);+ assert block.fp < startFP;++ suffixWriter.writeVLong(startFP - block.fp);++ /*+ if (DEBUG) {+ BytesRef suffixBytes = new BytesRef(suffix);+ System.arraycopy(block.prefix.bytes, prefixLength, suffixBytes.bytes, 0, suffix);+ suffixBytes.length = suffix;+ System.out.println(" " + (countx++) + ": write sub-block suffix=" + toString(suffixBytes) + " subFP=" + block.fp + " subCode=" + (startFP-block.fp) + " floor=" + block.isFloor + " totFloorTermCount=" + block.totFloorTermCount);+ }+ */++ suffixWriter.writeVLong(block.totFloorTermCount);+ subIndices.add(new SubIndex(block.index, totalTermCount));+ totalTermCount += block.totFloorTermCount;+ }+ }++ assert subIndices.size() != 0;+ }++ // TODO: we could block-write the term suffix pointers;+ // this would take more space but would enable binary+ // search on lookup++ // Write suffixes byte[] blob to terms dict output:+ out.writeVInt((int) (suffixWriter.getFilePointer() << 1) | (isLeafBlock ? 1:0));+ suffixWriter.writeTo(out);+ suffixWriter.reset();++ // Write term stats byte[] blob+ out.writeVInt((int) statsWriter.getFilePointer());+ //System.out.println("write stats @ fp=" + out.getFilePointer());+ statsWriter.writeTo(out);+ statsWriter.reset();++ // Write term meta data byte[] blob+ out.writeVInt((int) metaWriter.getFilePointer());+ metaWriter.writeTo(out);+ metaWriter.reset();++ // Remove slice replaced by block:+ slice.clear();++ if (lastBlockIndex >= start) {+ if (lastBlockIndex < start+length) {+ lastBlockIndex = start;+ } else {+ lastBlockIndex -= length;+ }+ }++ // if (DEBUG) {+ // System.out.println(" fpEnd=" + out.getFilePointer());+ // }++ return new PendingBlock(prefix, startFP, termCount != 0, totalTermCount, isFloor, floorLeadByte, subIndices);+ }++ TermsWriter(FieldInfo fieldInfo) {+ this.fieldInfo = fieldInfo;+ docsSeen = new FixedBitSet(maxDoc);++ noOutputs = NoOutputs.getSingleton();++ // This Builder is just used transiently to fragment+ // terms into "good" blocks; we don't save the+ // resulting FST:+ blockBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1,+ 0, 0, true,+ true, Integer.MAX_VALUE,+ noOutputs,+ new FindBlocks(), false,+ PackedInts.COMPACT,+ true, 15);++ this.longsSize = postingsWriter.setField(fieldInfo);+ }++ private final IntsRef scratchIntsRef = new IntsRef();++ /** Writes one term's worth of postings. */+ public void write(BytesRef text, TermsEnum termsEnum) throws IOException {+ BlockTermState state = postingsWriter.writeTerm(text, termsEnum, docsSeen);+ if (state != null) {+ assert state.docFreq != 0;+ assert fieldInfo.getIndexOptions() == IndexOptions.DOCS_ONLY || state.totalTermFreq >= state.docFreq: "postingsWriter=" + postingsWriter;+ sumDocFreq += state.docFreq;+ sumTotalTermFreq += state.totalTermFreq;+ blockBuilder.add(Util.toIntsRef(text, scratchIntsRef), noOutputs.getNoOutput());++ PendingTerm term = new PendingTerm(BytesRef.deepCopyOf(text), state);+ pending.add(term);+ numTerms++;+ }+ }++ // Finishes all terms in this field+ public void finish(BytesRef minTerm, BytesRef maxTerm) throws IOException {+ if (numTerms > 0) {+ blockBuilder.finish();++ // We better have one final "root" block:+ assert pending.size() == 1 && !pending.get(0).isTerm: "pending.size()=" + pending.size() + " pending=" + pending;+ final PendingBlock root = (PendingBlock) pending.get(0);+ assert root.prefix.length == 0;+ assert root.index.getEmptyOutput() != null;++ // Write FST to index+ indexStartFP = indexOut.getFilePointer();+ root.index.save(indexOut);+ //System.out.println(" write FST " + indexStartFP + " field=" + fieldInfo.name);++ // if (SAVE_DOT_FILES || DEBUG) {+ // final String dotFileName = segment + "_" + fieldInfo.name + ".dot";+ // Writer w = new OutputStreamWriter(new FileOutputStream(dotFileName));+ // Util.toDot(root.index, w, false, false);+ // System.out.println("SAVED to " + dotFileName);+ // w.close();+ // }++ fields.add(new FieldMetaData(fieldInfo,+ ((PendingBlock) pending.get(0)).index.getEmptyOutput(),+ numTerms,+ indexStartFP,+ sumTotalTermFreq,+ sumDocFreq,+ docsSeen.cardinality(),+ longsSize,+ minTerm, maxTerm));+ } else {+ assert docsSeen.cardinality() == 0;+ }+ }++ private final RAMOutputStream suffixWriter = new RAMOutputStream();+ private final RAMOutputStream statsWriter = new RAMOutputStream();+ private final RAMOutputStream metaWriter = new RAMOutputStream();+ private final RAMOutputStream bytesWriter = new RAMOutputStream();+ }++ @Override+ public void close() throws IOException {++ boolean success = false;+ try {++ final long dirStart = out.getFilePointer();+ final long indexDirStart = indexOut.getFilePointer();++ out.writeVInt(fields.size());++ for(FieldMetaData field : fields) {+ // System.out.println(" field " + field.fieldInfo.name + " " + field.numTerms + " terms longsSize=" + field.longsSize);+ out.writeVInt(field.fieldInfo.number);+ assert field.numTerms > 0;+ out.writeVLong(field.numTerms);+ out.writeVInt(field.rootCode.bytes.length);+ out.writeBytes(field.rootCode.bytes.bytes, field.rootCode.bytes.offset, field.rootCode.bytes.length);+ if (field.fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {+ out.writeVLong(field.sumTotalTermFreq);+ }+ out.writeVLong(field.sumDocFreq);+ out.writeVInt(field.docCount);+ out.writeVInt(field.longsSize);+ indexOut.writeVLong(field.indexStartFP);+ writeBytesRef(out, field.minTerm);+ writeBytesRef(out, field.maxTerm);+ }+ out.writeLong(dirStart);+ CodecUtil.writeFooter(out);+ indexOut.writeLong(indexDirStart);+ CodecUtil.writeFooter(indexOut);+ success = true;+ } finally {+ if (success) {+ IOUtils.close(out, indexOut, postingsWriter);+ } else {+ IOUtils.closeWhileHandlingException(out, indexOut, postingsWriter);+ }+ }+ }++ private static void writeBytesRef(IndexOutput out, BytesRef bytes) throws IOException {+ out.writeVInt(bytes.length);+ out.writeBytes(bytes.bytes, bytes.offset, bytes.length);+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsFieldReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsFieldReader.javanew file mode 100644index 00000000000..44f4fbeaab8--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsFieldReader.java@@ -0,0 +1,173 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.Accountable;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.automaton.CompiledAutomaton;+import org.apache.lucene.util.fst.FST;++/** BlockTree's implementation of {@link Terms}. */+final class OrdsFieldReader extends Terms implements Accountable {+ final long numTerms;+ final FieldInfo fieldInfo;+ final long sumTotalTermFreq;+ final long sumDocFreq;+ final int docCount;+ final long indexStartFP;+ final long rootBlockFP;+ final Output rootCode;+ final BytesRef minTerm;+ final BytesRef maxTerm;+ final int longsSize;+ final OrdsBlockTreeTermsReader parent;++ final FST<Output> index;+ //private boolean DEBUG;++ OrdsFieldReader(OrdsBlockTreeTermsReader parent, FieldInfo fieldInfo, long numTerms,+ Output rootCode, long sumTotalTermFreq, long sumDocFreq, int docCount,+ long indexStartFP, int longsSize, IndexInput indexIn, BytesRef minTerm, BytesRef maxTerm) throws IOException {+ assert numTerms > 0;+ this.fieldInfo = fieldInfo;+ //DEBUG = BlockTreeTermsReader.DEBUG && fieldInfo.name.equals("id");+ this.parent = parent;+ this.numTerms = numTerms;+ this.sumTotalTermFreq = sumTotalTermFreq;+ this.sumDocFreq = sumDocFreq;+ this.docCount = docCount;+ this.indexStartFP = indexStartFP;+ this.rootCode = rootCode;+ this.longsSize = longsSize;+ this.minTerm = minTerm;+ this.maxTerm = maxTerm;+ // if (DEBUG) {+ // System.out.println("BTTR: seg=" + segment + " field=" + fieldInfo.name + " rootBlockCode=" + rootCode + " divisor=" + indexDivisor);+ // }++ rootBlockFP = (new ByteArrayDataInput(rootCode.bytes.bytes,+ rootCode.bytes.offset,+ rootCode.bytes.length)).readVLong() >>> OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS;++ if (indexIn != null) {+ final IndexInput clone = indexIn.clone();+ //System.out.println("start=" + indexStartFP + " field=" + fieldInfo.name);+ clone.seek(indexStartFP);+ index = new FST<>(clone, OrdsBlockTreeTermsWriter.FST_OUTPUTS);++ /*+ if (true) {+ final String dotFileName = "/tmp/" + parent.segment + "_" + fieldInfo.name + ".dot";+ Writer w = new OutputStreamWriter(new FileOutputStream(dotFileName));+ Util.toDot(index, w, false, false);+ System.out.println("FST INDEX: SAVED to " + dotFileName);+ w.close();+ }+ */+ } else {+ index = null;+ }+ }++ @Override+ public BytesRef getMin() throws IOException {+ if (minTerm == null) {+ // Older index that didn't store min/maxTerm+ return super.getMin();+ } else {+ return minTerm;+ }+ }++ @Override+ public BytesRef getMax() throws IOException {+ if (maxTerm == null) {+ // Older index that didn't store min/maxTerm+ return super.getMax();+ } else {+ return maxTerm;+ }+ }++ @Override+ public boolean hasFreqs() {+ return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;+ }++ @Override+ public boolean hasOffsets() {+ return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;+ }++ @Override+ public boolean hasPositions() {+ return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;+ }++ @Override+ public boolean hasPayloads() {+ return fieldInfo.hasPayloads();+ }++ @Override+ public TermsEnum iterator(TermsEnum reuse) throws IOException {+ return new OrdsSegmentTermsEnum(this);+ }++ @Override+ public long size() {+ return numTerms;+ }++ @Override+ public long getSumTotalTermFreq() {+ return sumTotalTermFreq;+ }++ @Override+ public long getSumDocFreq() {+ return sumDocFreq;+ }++ @Override+ public int getDocCount() {+ return docCount;+ }++ @Override+ public TermsEnum intersect(CompiledAutomaton compiled, BytesRef startTerm) throws IOException {+ if (compiled.type != CompiledAutomaton.AUTOMATON_TYPE.NORMAL) {+ throw new IllegalArgumentException("please use CompiledAutomaton.getTermsEnum instead");+ }+ return new OrdsIntersectTermsEnum(this, compiled, startTerm);+ }++ @Override+ public long ramBytesUsed() {+ return ((index!=null)? index.ramBytesUsed() : 0);+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnum.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnum.javanew file mode 100644index 00000000000..24d01ec3a0f--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnum.java@@ -0,0 +1,485 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.TermState;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.StringHelper;+import org.apache.lucene.util.automaton.CompiledAutomaton;+import org.apache.lucene.util.automaton.RunAutomaton;+import org.apache.lucene.util.fst.FST;++// NOTE: cannot seek!+final class OrdsIntersectTermsEnum extends TermsEnum {+ final IndexInput in;++ private OrdsIntersectTermsEnumFrame[] stack;++ @SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<Output>[] arcs = new FST.Arc[5];++ final RunAutomaton runAutomaton;+ final CompiledAutomaton compiledAutomaton;++ private OrdsIntersectTermsEnumFrame currentFrame;++ private final BytesRef term = new BytesRef();++ private final FST.BytesReader fstReader;++ final OrdsFieldReader fr;++ private BytesRef savedStartTerm;++ // TODO: in some cases we can filter by length? eg+ // regexp foo*bar must be at least length 6 bytes+ public OrdsIntersectTermsEnum(OrdsFieldReader fr, CompiledAutomaton compiled, BytesRef startTerm) throws IOException {+ // if (DEBUG) {+ // System.out.println("\nintEnum.init seg=" + segment + " commonSuffix=" + brToString(compiled.commonSuffixRef));+ // }+ this.fr = fr;+ runAutomaton = compiled.runAutomaton;+ compiledAutomaton = compiled;+ in = fr.parent.in.clone();+ stack = new OrdsIntersectTermsEnumFrame[5];+ for(int idx=0;idx<stack.length;idx++) {+ stack[idx] = new OrdsIntersectTermsEnumFrame(this, idx);+ }+ for(int arcIdx=0;arcIdx<arcs.length;arcIdx++) {+ arcs[arcIdx] = new FST.Arc<>();+ }++ if (fr.index == null) {+ fstReader = null;+ } else {+ fstReader = fr.index.getBytesReader();+ }++ // TODO: if the automaton is "smallish" we really+ // should use the terms index to seek at least to+ // the initial term and likely to subsequent terms+ // (or, maybe just fallback to ATE for such cases).+ // Else the seek cost of loading the frames will be+ // too costly.++ final FST.Arc<Output> arc = fr.index.getFirstArc(arcs[0]);+ // Empty string prefix must have an output in the index!+ assert arc.isFinal();++ // Special pushFrame since it's the first one:+ final OrdsIntersectTermsEnumFrame f = stack[0];+ f.fp = f.fpOrig = fr.rootBlockFP;+ f.prefix = 0;+ f.setState(runAutomaton.getInitialState());+ f.arc = arc;+ f.outputPrefix = arc.output;+ f.load(fr.rootCode);++ // for assert:+ assert setSavedStartTerm(startTerm);++ currentFrame = f;+ if (startTerm != null) {+ seekToStartTerm(startTerm);+ }+ }++ // only for assert:+ private boolean setSavedStartTerm(BytesRef startTerm) {+ savedStartTerm = startTerm == null ? null : BytesRef.deepCopyOf(startTerm);+ return true;+ }++ @Override+ public TermState termState() throws IOException {+ currentFrame.decodeMetaData();+ return currentFrame.termState.clone();+ }++ private OrdsIntersectTermsEnumFrame getFrame(int ord) throws IOException {+ if (ord >= stack.length) {+ final OrdsIntersectTermsEnumFrame[] next = new OrdsIntersectTermsEnumFrame[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];+ System.arraycopy(stack, 0, next, 0, stack.length);+ for(int stackOrd=stack.length;stackOrd<next.length;stackOrd++) {+ next[stackOrd] = new OrdsIntersectTermsEnumFrame(this, stackOrd);+ }+ stack = next;+ }+ assert stack[ord].ord == ord;+ return stack[ord];+ }++ private FST.Arc<Output> getArc(int ord) {+ if (ord >= arcs.length) {+ @SuppressWarnings({"rawtypes","unchecked"}) final FST.Arc<Output>[] next =+ new FST.Arc[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];+ System.arraycopy(arcs, 0, next, 0, arcs.length);+ for(int arcOrd=arcs.length;arcOrd<next.length;arcOrd++) {+ next[arcOrd] = new FST.Arc<>();+ }+ arcs = next;+ }+ return arcs[ord];+ }++ private OrdsIntersectTermsEnumFrame pushFrame(int state) throws IOException {+ final OrdsIntersectTermsEnumFrame f = getFrame(currentFrame == null ? 0 : 1+currentFrame.ord);++ f.fp = f.fpOrig = currentFrame.lastSubFP;+ f.prefix = currentFrame.prefix + currentFrame.suffix;+ // if (DEBUG) System.out.println(" pushFrame state=" + state + " prefix=" + f.prefix);+ f.setState(state);++ // Walk the arc through the index -- we only+ // "bother" with this so we can get the floor data+ // from the index and skip floor blocks when+ // possible:+ FST.Arc<Output> arc = currentFrame.arc;+ int idx = currentFrame.prefix;+ assert currentFrame.suffix > 0;+ Output output = currentFrame.outputPrefix;+ while (idx < f.prefix) {+ final int target = term.bytes[idx] & 0xff;+ // TODO: we could be more efficient for the next()+ // case by using current arc as starting point,+ // passed to findTargetArc+ arc = fr.index.findTargetArc(target, arc, getArc(1+idx), fstReader);+ assert arc != null;+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ idx++;+ }++ f.arc = arc;+ f.outputPrefix = output;+ assert arc.isFinal();+ f.load(OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput));+ return f;+ }++ @Override+ public BytesRef term() {+ return term;+ }++ // TODO: do we need ord() here? OrdsIntersectTermsEnumFrame tracks termOrd but it may be buggy!++ @Override+ public int docFreq() throws IOException {+ //if (DEBUG) System.out.println("BTIR.docFreq");+ currentFrame.decodeMetaData();+ //if (DEBUG) System.out.println(" return " + currentFrame.termState.docFreq);+ return currentFrame.termState.docFreq;+ }++ @Override+ public long totalTermFreq() throws IOException {+ currentFrame.decodeMetaData();+ return currentFrame.termState.totalTermFreq;+ }++ @Override+ public DocsEnum docs(Bits skipDocs, DocsEnum reuse, int flags) throws IOException {+ currentFrame.decodeMetaData();+ return fr.parent.postingsReader.docs(fr.fieldInfo, currentFrame.termState, skipDocs, reuse, flags);+ }++ @Override+ public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {+ if (fr.fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {+ // Positions were not indexed:+ return null;+ }++ currentFrame.decodeMetaData();+ return fr.parent.postingsReader.docsAndPositions(fr.fieldInfo, currentFrame.termState, skipDocs, reuse, flags);+ }++ private int getState() {+ int state = currentFrame.state;+ for(int idx=0;idx<currentFrame.suffix;idx++) {+ state = runAutomaton.step(state, currentFrame.suffixBytes[currentFrame.startBytePos+idx] & 0xff);+ assert state != -1;+ }+ return state;+ }++ // NOTE: specialized to only doing the first-time+ // seek, but we could generalize it to allow+ // arbitrary seekExact/Ceil. Note that this is a+ // seekFloor!+ private void seekToStartTerm(BytesRef target) throws IOException {+ //if (DEBUG) System.out.println("seek to startTerm=" + target.utf8ToString());+ assert currentFrame.ord == 0;+ if (term.length < target.length) {+ term.bytes = ArrayUtil.grow(term.bytes, target.length);+ }+ FST.Arc<Output> arc = arcs[0];+ assert arc == currentFrame.arc;++ for(int idx=0;idx<=target.length;idx++) {++ while (true) {+ final int savePos = currentFrame.suffixesReader.getPosition();+ final int saveStartBytePos = currentFrame.startBytePos;+ final int saveSuffix = currentFrame.suffix;+ final long saveLastSubFP = currentFrame.lastSubFP;+ final int saveTermBlockOrd = currentFrame.termState.termBlockOrd;++ final boolean isSubBlock = currentFrame.next();++ //if (DEBUG) System.out.println(" cycle ent=" + currentFrame.nextEnt + " (of " + currentFrame.entCount + ") prefix=" + currentFrame.prefix + " suffix=" + currentFrame.suffix + " isBlock=" + isSubBlock + " firstLabel=" + (currentFrame.suffix == 0 ? "" : (currentFrame.suffixBytes[currentFrame.startBytePos])&0xff));+ term.length = currentFrame.prefix + currentFrame.suffix;+ if (term.bytes.length < term.length) {+ term.bytes = ArrayUtil.grow(term.bytes, term.length);+ }+ System.arraycopy(currentFrame.suffixBytes, currentFrame.startBytePos, term.bytes, currentFrame.prefix, currentFrame.suffix);++ if (isSubBlock && StringHelper.startsWith(target, term)) {+ // Recurse+ //if (DEBUG) System.out.println(" recurse!");+ currentFrame = pushFrame(getState());+ break;+ } else {+ final int cmp = term.compareTo(target);+ if (cmp < 0) {+ if (currentFrame.nextEnt == currentFrame.entCount) {+ if (!currentFrame.isLastInFloor) {+ //if (DEBUG) System.out.println(" load floorBlock");+ currentFrame.loadNextFloorBlock();+ continue;+ } else {+ //if (DEBUG) System.out.println(" return term=" + brToString(term));+ return;+ }+ }+ continue;+ } else if (cmp == 0) {+ //if (DEBUG) System.out.println(" return term=" + brToString(term));+ return;+ } else {+ // Fallback to prior entry: the semantics of+ // this method is that the first call to+ // next() will return the term after the+ // requested term+ currentFrame.nextEnt--;+ currentFrame.lastSubFP = saveLastSubFP;+ currentFrame.startBytePos = saveStartBytePos;+ currentFrame.suffix = saveSuffix;+ currentFrame.suffixesReader.setPosition(savePos);+ currentFrame.termState.termBlockOrd = saveTermBlockOrd;+ System.arraycopy(currentFrame.suffixBytes, currentFrame.startBytePos, term.bytes, currentFrame.prefix, currentFrame.suffix);+ term.length = currentFrame.prefix + currentFrame.suffix;+ // If the last entry was a block we don't+ // need to bother recursing and pushing to+ // the last term under it because the first+ // next() will simply skip the frame anyway+ return;+ }+ }+ }+ }++ assert false;+ }++ @Override+ public BytesRef next() throws IOException {++ // if (DEBUG) {+ // System.out.println("\nintEnum.next seg=" + segment);+ // System.out.println(" frame ord=" + currentFrame.ord + " prefix=" + brToString(new BytesRef(term.bytes, term.offset, currentFrame.prefix)) + " state=" + currentFrame.state + " lastInFloor?=" + currentFrame.isLastInFloor + " fp=" + currentFrame.fp + " trans=" + (currentFrame.transitions.length == 0 ? "n/a" : currentFrame.transitions[currentFrame.transitionIndex]) + " outputPrefix=" + currentFrame.outputPrefix);+ // }++ nextTerm:+ while(true) {+ // Pop finished frames+ while (currentFrame.nextEnt == currentFrame.entCount) {+ if (!currentFrame.isLastInFloor) {+ //if (DEBUG) System.out.println(" next-floor-block");+ currentFrame.loadNextFloorBlock();+ //if (DEBUG) System.out.println("\n frame ord=" + currentFrame.ord + " prefix=" + brToString(new BytesRef(term.bytes, term.offset, currentFrame.prefix)) + " state=" + currentFrame.state + " lastInFloor?=" + currentFrame.isLastInFloor + " fp=" + currentFrame.fp + " trans=" + (currentFrame.transitions.length == 0 ? "n/a" : currentFrame.transitions[currentFrame.transitionIndex]) + " outputPrefix=" + currentFrame.outputPrefix);+ } else {+ //if (DEBUG) System.out.println(" pop frame");+ if (currentFrame.ord == 0) {+ return null;+ }+ final long lastFP = currentFrame.fpOrig;+ currentFrame = stack[currentFrame.ord-1];+ assert currentFrame.lastSubFP == lastFP;+ //if (DEBUG) System.out.println("\n frame ord=" + currentFrame.ord + " prefix=" + brToString(new BytesRef(term.bytes, term.offset, currentFrame.prefix)) + " state=" + currentFrame.state + " lastInFloor?=" + currentFrame.isLastInFloor + " fp=" + currentFrame.fp + " trans=" + (currentFrame.transitions.length == 0 ? "n/a" : currentFrame.transitions[currentFrame.transitionIndex]) + " outputPrefix=" + currentFrame.outputPrefix);+ }+ }++ final boolean isSubBlock = currentFrame.next();+ // if (DEBUG) {+ // final BytesRef suffixRef = new BytesRef();+ // suffixRef.bytes = currentFrame.suffixBytes;+ // suffixRef.offset = currentFrame.startBytePos;+ // suffixRef.length = currentFrame.suffix;+ // System.out.println(" " + (isSubBlock ? "sub-block" : "term") + " " + currentFrame.nextEnt + " (of " + currentFrame.entCount + ") suffix=" + brToString(suffixRef));+ // }++ if (currentFrame.suffix != 0) {+ final int label = currentFrame.suffixBytes[currentFrame.startBytePos] & 0xff;+ while (label > currentFrame.curTransitionMax) {+ if (currentFrame.transitionIndex >= currentFrame.transitionCount-1) {+ // Stop processing this frame -- no further+ // matches are possible because we've moved+ // beyond what the max transition will allow+ //if (DEBUG) System.out.println(" break: trans=" + (currentFrame.transitions.length == 0 ? "n/a" : currentFrame.transitions[currentFrame.transitionIndex]));++ // sneaky! forces a pop above+ currentFrame.isLastInFloor = true;+ currentFrame.nextEnt = currentFrame.entCount;+ continue nextTerm;+ }+ currentFrame.transitionIndex++;+ compiledAutomaton.automaton.getNextTransition(currentFrame.transition);+ currentFrame.curTransitionMax = currentFrame.transition.max;+ //if (DEBUG) System.out.println(" next trans=" + currentFrame.transitions[currentFrame.transitionIndex]);+ }+ }++ // First test the common suffix, if set:+ if (compiledAutomaton.commonSuffixRef != null && !isSubBlock) {+ final int termLen = currentFrame.prefix + currentFrame.suffix;+ if (termLen < compiledAutomaton.commonSuffixRef.length) {+ // No match+ // if (DEBUG) {+ // System.out.println(" skip: common suffix length");+ // }+ continue nextTerm;+ }++ final byte[] suffixBytes = currentFrame.suffixBytes;+ final byte[] commonSuffixBytes = compiledAutomaton.commonSuffixRef.bytes;++ final int lenInPrefix = compiledAutomaton.commonSuffixRef.length - currentFrame.suffix;+ assert compiledAutomaton.commonSuffixRef.offset == 0;+ int suffixBytesPos;+ int commonSuffixBytesPos = 0;++ if (lenInPrefix > 0) {+ // A prefix of the common suffix overlaps with+ // the suffix of the block prefix so we first+ // test whether the prefix part matches:+ final byte[] termBytes = term.bytes;+ int termBytesPos = currentFrame.prefix - lenInPrefix;+ assert termBytesPos >= 0;+ final int termBytesPosEnd = currentFrame.prefix;+ while (termBytesPos < termBytesPosEnd) {+ if (termBytes[termBytesPos++] != commonSuffixBytes[commonSuffixBytesPos++]) {+ // if (DEBUG) {+ // System.out.println(" skip: common suffix mismatch (in prefix)");+ // }+ continue nextTerm;+ }+ }+ suffixBytesPos = currentFrame.startBytePos;+ } else {+ suffixBytesPos = currentFrame.startBytePos + currentFrame.suffix - compiledAutomaton.commonSuffixRef.length;+ }++ // Test overlapping suffix part:+ final int commonSuffixBytesPosEnd = compiledAutomaton.commonSuffixRef.length;+ while (commonSuffixBytesPos < commonSuffixBytesPosEnd) {+ if (suffixBytes[suffixBytesPos++] != commonSuffixBytes[commonSuffixBytesPos++]) {+ // if (DEBUG) {+ // System.out.println(" skip: common suffix mismatch");+ // }+ continue nextTerm;+ }+ }+ }++ // TODO: maybe we should do the same linear test+ // that AutomatonTermsEnum does, so that if we+ // reach a part of the automaton where .* is+ // "temporarily" accepted, we just blindly .next()+ // until the limit++ // See if the term prefix matches the automaton:+ int state = currentFrame.state;+ for (int idx=0;idx<currentFrame.suffix;idx++) {+ state = runAutomaton.step(state, currentFrame.suffixBytes[currentFrame.startBytePos+idx] & 0xff);+ if (state == -1) {+ // No match+ //System.out.println(" no s=" + state);+ continue nextTerm;+ } else {+ //System.out.println(" c s=" + state);+ }+ }++ if (isSubBlock) {+ // Match! Recurse:+ //if (DEBUG) System.out.println(" sub-block match to state=" + state + "; recurse fp=" + currentFrame.lastSubFP);+ copyTerm();+ currentFrame = pushFrame(state);+ //if (DEBUG) System.out.println("\n frame ord=" + currentFrame.ord + " prefix=" + brToString(new BytesRef(term.bytes, term.offset, currentFrame.prefix)) + " state=" + currentFrame.state + " lastInFloor?=" + currentFrame.isLastInFloor + " fp=" + currentFrame.fp + " trans=" + (currentFrame.transitions.length == 0 ? "n/a" : currentFrame.transitions[currentFrame.transitionIndex]) + " outputPrefix=" + currentFrame.outputPrefix);+ } else if (runAutomaton.isAccept(state)) {+ copyTerm();+ //if (DEBUG) System.out.println(" term match to state=" + state + "; return term=" + brToString(term));+ assert savedStartTerm == null || term.compareTo(savedStartTerm) > 0: "saveStartTerm=" + savedStartTerm.utf8ToString() + " term=" + term.utf8ToString();+ return term;+ } else {+ //System.out.println(" no s=" + state);+ }+ }+ }++ private void copyTerm() {+ //System.out.println(" copyTerm cur.prefix=" + currentFrame.prefix + " cur.suffix=" + currentFrame.suffix + " first=" + (char) currentFrame.suffixBytes[currentFrame.startBytePos]);+ final int len = currentFrame.prefix + currentFrame.suffix;+ if (term.bytes.length < len) {+ term.bytes = ArrayUtil.grow(term.bytes, len);+ }+ System.arraycopy(currentFrame.suffixBytes, currentFrame.startBytePos, term.bytes, currentFrame.prefix, currentFrame.suffix);+ term.length = len;+ }++ @Override+ public boolean seekExact(BytesRef text) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void seekExact(long ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public long ord() {+ throw new UnsupportedOperationException();+ }++ @Override+ public SeekStatus seekCeil(BytesRef text) {+ throw new UnsupportedOperationException();+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.javanew file mode 100644index 00000000000..187e76068fe--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java@@ -0,0 +1,310 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.automaton.Transition;+import org.apache.lucene.util.fst.FST;++// TODO: can we share this with the frame in STE?+final class OrdsIntersectTermsEnumFrame {+ final int ord;+ long fp;+ long fpOrig;+ long fpEnd;+ long lastSubFP;++ // State in automaton+ int state;++ int metaDataUpto;++ byte[] suffixBytes = new byte[128];+ final ByteArrayDataInput suffixesReader = new ByteArrayDataInput();++ byte[] statBytes = new byte[64];+ final ByteArrayDataInput statsReader = new ByteArrayDataInput();++ byte[] floorData = new byte[32];+ final ByteArrayDataInput floorDataReader = new ByteArrayDataInput();++ // Length of prefix shared by all terms in this block+ int prefix;++ // Number of entries (term or sub-block) in this block+ int entCount;++ // Which term we will next read+ int nextEnt;++ // Starting termOrd for this frame, used to reset termOrd in rewind()+ long termOrdOrig;++ // 1 + ordinal of the current term+ long termOrd;++ // True if this block is either not a floor block,+ // or, it's the last sub-block of a floor block+ boolean isLastInFloor;++ // True if all entries are terms+ boolean isLeafBlock;++ int numFollowFloorBlocks;+ int nextFloorLabel;++ Transition transition = new Transition();+ int curTransitionMax;+ int transitionIndex;+ int transitionCount;++ FST.Arc<Output> arc;++ final BlockTermState termState;++ // metadata buffer, holding monotonic values+ public long[] longs;+ // metadata buffer, holding general values+ public byte[] bytes;+ ByteArrayDataInput bytesReader;++ // Cumulative output so far+ Output outputPrefix;++ int startBytePos;+ int suffix;++ private final OrdsIntersectTermsEnum ite;++ public OrdsIntersectTermsEnumFrame(OrdsIntersectTermsEnum ite, int ord) throws IOException {+ this.ite = ite;+ this.ord = ord;+ this.termState = ite.fr.parent.postingsReader.newTermState();+ this.termState.totalTermFreq = -1;+ this.longs = new long[ite.fr.longsSize];+ }++ void loadNextFloorBlock() throws IOException {+ assert numFollowFloorBlocks > 0;+ //if (DEBUG) System.out.println(" loadNextFoorBlock trans=" + transitions[transitionIndex]);++ do {+ fp = fpOrig + (floorDataReader.readVLong() >>> 1);+ numFollowFloorBlocks--;+ // if (DEBUG) System.out.println(" skip floor block2! nextFloorLabel=" + (char) nextFloorLabel + " vs target=" + (char) transitions[transitionIndex].getMin() + " newFP=" + fp + " numFollowFloorBlocks=" + numFollowFloorBlocks);+ if (numFollowFloorBlocks != 0) {+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ termOrd += floorDataReader.readVLong();+ } else {+ nextFloorLabel = 256;+ }+ // if (DEBUG) System.out.println(" nextFloorLabel=" + (char) nextFloorLabel);+ } while (numFollowFloorBlocks != 0 && nextFloorLabel <= transition.min);++ load(null);+ }++ public void setState(int state) {+ this.state = state;+ transitionIndex = 0;+ transitionCount = ite.compiledAutomaton.automaton.getNumTransitions(state);+ if (transitionCount != 0) {+ ite.compiledAutomaton.automaton.initTransition(state, transition);+ ite.compiledAutomaton.automaton.getNextTransition(transition);+ curTransitionMax = transition.max;+ } else {+ curTransitionMax = -1;+ }+ }++ void load(Output output) throws IOException {++ // if (DEBUG) System.out.println(" load fp=" + fp + " fpOrig=" + fpOrig + " frameIndexData=" + frameIndexData + " trans=" + (transitions.length != 0 ? transitions[0] : "n/a" + " state=" + state));++ if (output != null && output.bytes != null && transitionCount != 0) {+ BytesRef frameIndexData = output.bytes;++ // Floor frame+ if (floorData.length < frameIndexData.length) {+ this.floorData = new byte[ArrayUtil.oversize(frameIndexData.length, 1)];+ }+ System.arraycopy(frameIndexData.bytes, frameIndexData.offset, floorData, 0, frameIndexData.length);+ floorDataReader.reset(floorData, 0, frameIndexData.length);+ final long code = floorDataReader.readVLong();+ if ((code & OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR) != 0) {+ numFollowFloorBlocks = floorDataReader.readVInt();+ nextFloorLabel = floorDataReader.readByte() & 0xff;++ termOrd = termOrdOrig + floorDataReader.readVLong();++ // if (DEBUG) System.out.println(" numFollowFloorBlocks=" + numFollowFloorBlocks + " nextFloorLabel=" + nextFloorLabel);++ // If current state is accept, we must process+ // first block in case it has empty suffix:+ if (!ite.runAutomaton.isAccept(state)) {+ // Maybe skip floor blocks:+ assert transitionIndex == 0: "transitionIndex=" + transitionIndex;+ while (numFollowFloorBlocks != 0 && nextFloorLabel <= transition.min) {+ fp = fpOrig + (floorDataReader.readVLong() >>> 1);+ numFollowFloorBlocks--;+ // if (DEBUG) System.out.println(" skip floor block! nextFloorLabel=" + (char) nextFloorLabel + " vs target=" + (char) transitions[0].getMin() + " newFP=" + fp + " numFollowFloorBlocks=" + numFollowFloorBlocks);+ if (numFollowFloorBlocks != 0) {+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ termOrd += floorDataReader.readVLong();+ } else {+ nextFloorLabel = 256;+ }+ }+ }+ }+ }++ ite.in.seek(fp);+ int code = ite.in.readVInt();+ entCount = code >>> 1;+ assert entCount > 0;+ isLastInFloor = (code & 1) != 0;++ // term suffixes:+ code = ite.in.readVInt();+ isLeafBlock = (code & 1) != 0;+ int numBytes = code >>> 1;+ // if (DEBUG) System.out.println(" entCount=" + entCount + " lastInFloor?=" + isLastInFloor + " leafBlock?=" + isLeafBlock + " numSuffixBytes=" + numBytes);+ if (suffixBytes.length < numBytes) {+ suffixBytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ ite.in.readBytes(suffixBytes, 0, numBytes);+ suffixesReader.reset(suffixBytes, 0, numBytes);++ // stats+ numBytes = ite.in.readVInt();+ if (statBytes.length < numBytes) {+ statBytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ ite.in.readBytes(statBytes, 0, numBytes);+ statsReader.reset(statBytes, 0, numBytes);+ metaDataUpto = 0;++ termState.termBlockOrd = 0;+ nextEnt = 0;++ // metadata+ numBytes = ite.in.readVInt();+ if (bytes == null) {+ bytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ bytesReader = new ByteArrayDataInput();+ } else if (bytes.length < numBytes) {+ bytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ ite.in.readBytes(bytes, 0, numBytes);+ bytesReader.reset(bytes, 0, numBytes);++ if (!isLastInFloor) {+ // Sub-blocks of a single floor block are always+ // written one after another -- tail recurse:+ fpEnd = ite.in.getFilePointer();+ }+ }++ // TODO: maybe add scanToLabel; should give perf boost++ public boolean next() {+ return isLeafBlock ? nextLeaf() : nextNonLeaf();+ }++ // Decodes next entry; returns true if it's a sub-block+ public boolean nextLeaf() {+ //if (DEBUG) System.out.println(" frame.next ord=" + ord + " nextEnt=" + nextEnt + " entCount=" + entCount);+ assert nextEnt != -1 && nextEnt < entCount: "nextEnt=" + nextEnt + " entCount=" + entCount + " fp=" + fp;+ nextEnt++;+ suffix = suffixesReader.readVInt();+ startBytePos = suffixesReader.getPosition();+ suffixesReader.skipBytes(suffix);+ return false;+ }++ public boolean nextNonLeaf() {+ //if (DEBUG) System.out.println(" frame.next ord=" + ord + " nextEnt=" + nextEnt + " entCount=" + entCount);+ assert nextEnt != -1 && nextEnt < entCount: "nextEnt=" + nextEnt + " entCount=" + entCount + " fp=" + fp;+ nextEnt++;+ final int code = suffixesReader.readVInt();+ suffix = code >>> 1;+ startBytePos = suffixesReader.getPosition();+ suffixesReader.skipBytes(suffix);+ if ((code & 1) == 0) {+ // A normal term+ termState.termBlockOrd++;+ return false;+ } else {+ // A sub-block; make sub-FP absolute:+ lastSubFP = fp - suffixesReader.readVLong();+ // Skip term ord+ suffixesReader.readVLong();+ return true;+ }+ }++ public int getTermBlockOrd() {+ return isLeafBlock ? nextEnt : termState.termBlockOrd;+ }++ public void decodeMetaData() throws IOException {++ // lazily catch up on metadata decode:+ final int limit = getTermBlockOrd();+ boolean absolute = metaDataUpto == 0;+ assert limit > 0;++ // TODO: better API would be "jump straight to term=N"???+ while (metaDataUpto < limit) {++ // TODO: we could make "tiers" of metadata, ie,+ // decode docFreq/totalTF but don't decode postings+ // metadata; this way caller could get+ // docFreq/totalTF w/o paying decode cost for+ // postings++ // TODO: if docFreq were bulk decoded we could+ // just skipN here:++ // stats+ termState.docFreq = statsReader.readVInt();+ //if (DEBUG) System.out.println(" dF=" + state.docFreq);+ if (ite.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {+ termState.totalTermFreq = termState.docFreq + statsReader.readVLong();+ //if (DEBUG) System.out.println(" totTF=" + state.totalTermFreq);+ }+ // metadata+ for (int i = 0; i < ite.fr.longsSize; i++) {+ longs[i] = bytesReader.readVLong();+ }+ ite.fr.parent.postingsReader.decodeTerm(longs, bytesReader, ite.fr.fieldInfo, termState, absolute);++ metaDataUpto++;+ absolute = false;+ }+ termState.termBlockOrd = metaDataUpto;+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.javanew file mode 100644index 00000000000..e33c13c301e--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java@@ -0,0 +1,1186 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++//import java.io.*;+//import java.nio.charset.StandardCharsets;++import java.io.IOException;+import java.io.PrintStream;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.TermState;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.fst.FST;+import org.apache.lucene.util.fst.Util;++/** Iterates through terms in this field. */+public final class OrdsSegmentTermsEnum extends TermsEnum {++ // Lazy init:+ IndexInput in;++ // static boolean DEBUG = true;++ private OrdsSegmentTermsEnumFrame[] stack;+ private final OrdsSegmentTermsEnumFrame staticFrame;+ OrdsSegmentTermsEnumFrame currentFrame;+ boolean termExists;+ final OrdsFieldReader fr;++ private int targetBeforeCurrentLength;++ private final ByteArrayDataInput scratchReader = new ByteArrayDataInput();++ // What prefix of the current term was present in the index:+ private int validIndexPrefix;++ // assert only:+ private boolean eof;++ final BytesRef term = new BytesRef();+ private final FST.BytesReader fstReader;++ @SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<Output>[] arcs =+ new FST.Arc[1];++ boolean positioned;++ OrdsSegmentTermsEnum(OrdsFieldReader fr) throws IOException {+ this.fr = fr;++ //if (DEBUG) System.out.println("BTTR.init seg=" + segment);+ stack = new OrdsSegmentTermsEnumFrame[0];++ // Used to hold seek by TermState, or cached seek+ staticFrame = new OrdsSegmentTermsEnumFrame(this, -1);++ if (fr.index == null) {+ fstReader = null;+ } else {+ fstReader = fr.index.getBytesReader();+ }++ // Init w/ root block; don't use index since it may+ // not (and need not) have been loaded+ for(int arcIdx=0;arcIdx<arcs.length;arcIdx++) {+ arcs[arcIdx] = new FST.Arc<>();+ }++ currentFrame = staticFrame;+ final FST.Arc<Output> arc;+ if (fr.index != null) {+ arc = fr.index.getFirstArc(arcs[0]);+ // Empty string prefix must have an output in the index!+ assert arc.isFinal();+ } else {+ arc = null;+ }+ //currentFrame = pushFrame(arc, rootCode, 0);+ //currentFrame.loadBlock();+ validIndexPrefix = 0;+ // if (DEBUG) {+ // System.out.println("init frame state " + currentFrame.ord);+ // printSeekState();+ // }++ //System.out.println();+ // computeBlockStats().print(System.out);+ }++ // Not private to avoid synthetic access$NNN methods+ void initIndexInput() {+ if (this.in == null) {+ this.in = fr.parent.in.clone();+ }+ }++ private OrdsSegmentTermsEnumFrame getFrame(int ord) throws IOException {+ if (ord >= stack.length) {+ final OrdsSegmentTermsEnumFrame[] next = new OrdsSegmentTermsEnumFrame[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];+ System.arraycopy(stack, 0, next, 0, stack.length);+ for(int stackOrd=stack.length;stackOrd<next.length;stackOrd++) {+ next[stackOrd] = new OrdsSegmentTermsEnumFrame(this, stackOrd);+ }+ stack = next;+ }+ assert stack[ord].ord == ord;+ return stack[ord];+ }++ private FST.Arc<Output> getArc(int ord) {+ if (ord >= arcs.length) {+ @SuppressWarnings({"rawtypes","unchecked"}) final FST.Arc<Output>[] next =+ new FST.Arc[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];+ System.arraycopy(arcs, 0, next, 0, arcs.length);+ for(int arcOrd=arcs.length;arcOrd<next.length;arcOrd++) {+ next[arcOrd] = new FST.Arc<>();+ }+ arcs = next;+ }+ return arcs[ord];+ }++ // Pushes a frame we seek'd to+ OrdsSegmentTermsEnumFrame pushFrame(FST.Arc<Output> arc, Output frameData, int length) throws IOException {+ scratchReader.reset(frameData.bytes.bytes, frameData.bytes.offset, frameData.bytes.length);+ final long code = scratchReader.readVLong();+ final long fpSeek = code >>> OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS;+ // System.out.println(" fpSeek=" + fpSeek);+ final OrdsSegmentTermsEnumFrame f = getFrame(1+currentFrame.ord);+ f.hasTerms = (code & OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS) != 0;+ f.hasTermsOrig = f.hasTerms;+ f.isFloor = (code & OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR) != 0;++ // Must setFloorData before pushFrame in case pushFrame tries to rewind:+ if (f.isFloor) {+ f.termOrdOrig = frameData.startOrd;+ f.setFloorData(scratchReader, frameData.bytes);+ }++ pushFrame(arc, fpSeek, length, frameData.startOrd);++ return f;+ }++ // Pushes next'd frame or seek'd frame; we later+ // lazy-load the frame only when needed+ OrdsSegmentTermsEnumFrame pushFrame(FST.Arc<Output> arc, long fp, int length, long termOrd) throws IOException {+ final OrdsSegmentTermsEnumFrame f = getFrame(1+currentFrame.ord);+ f.arc = arc;+ // System.out.println("pushFrame termOrd= " + termOrd + " fpOrig=" + f.fpOrig + " fp=" + fp + " nextEnt=" + f.nextEnt);+ if (f.fpOrig == fp && f.nextEnt != -1) {+ //if (DEBUG) System.out.println(" push reused frame ord=" + f.ord + " fp=" + f.fp + " isFloor?=" + f.isFloor + " hasTerms=" + f.hasTerms + " pref=" + term + " nextEnt=" + f.nextEnt + " targetBeforeCurrentLength=" + targetBeforeCurrentLength + " term.length=" + term.length + " vs prefix=" + f.prefix);+ if (f.prefix > targetBeforeCurrentLength) {+ // System.out.println(" do rewind!");+ f.rewind();+ } else {+ // if (DEBUG) {+ // System.out.println(" skip rewind!");+ // }+ }+ assert length == f.prefix;+ } else {+ f.nextEnt = -1;+ f.prefix = length;+ f.state.termBlockOrd = 0;+ f.termOrdOrig = termOrd;+ // System.out.println("set termOrdOrig=" + termOrd);+ f.termOrd = termOrd;+ f.fpOrig = f.fp = fp;+ f.lastSubFP = -1;+ // if (DEBUG) {+ // final int sav = term.length;+ // term.length = length;+ // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term));+ // term.length = sav;+ // }+ }++ return f;+ }++ // asserts only+ private boolean clearEOF() {+ eof = false;+ return true;+ }++ // asserts only+ private boolean setEOF() {+ eof = true;+ return true;+ }++ // for debugging+ @SuppressWarnings("unused")+ static String brToString(BytesRef b) {+ try {+ return b.utf8ToString() + " " + b;+ } catch (Throwable t) {+ // If BytesRef isn't actually UTF8, or it's eg a+ // prefix of UTF8 that ends mid-unicode-char, we+ // fallback to hex:+ return b.toString();+ }+ }++ @Override+ public boolean seekExact(final BytesRef target) throws IOException {++ if (fr.index == null) {+ throw new IllegalStateException("terms index was not loaded");+ }++ if (term.bytes.length <= target.length) {+ term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);+ }++ assert clearEOF();++ /*+ if (DEBUG) {+ System.out.println("\nBTTR.seekExact seg=" + fr.parent.segment + " target=" + fr.fieldInfo.name + ":" + brToString(target) + " current=" + brToString(term) + " (exists?=" + termExists + ") validIndexPrefix=" + validIndexPrefix);+ printSeekState(System.out);+ }+ */++ FST.Arc<Output> arc;+ int targetUpto;+ Output output;++ targetBeforeCurrentLength = currentFrame.ord;++ if (positioned && currentFrame != staticFrame) {++ // We are already seek'd; find the common+ // prefix of new seek term vs current term and+ // re-use the corresponding seek state. For+ // example, if app first seeks to foobar, then+ // seeks to foobaz, we can re-use the seek state+ // for the first 5 bytes.++ // if (DEBUG) {+ // System.out.println(" re-use current seek state validIndexPrefix=" + validIndexPrefix);+ // }++ arc = arcs[0];+ assert arc.isFinal();+ output = arc.output;+ targetUpto = 0;++ OrdsSegmentTermsEnumFrame lastFrame = stack[0];+ assert validIndexPrefix <= term.length;++ final int targetLimit = Math.min(target.length, validIndexPrefix);++ int cmp = 0;++ // TODO: reverse vLong byte order for better FST+ // prefix output sharing++ // First compare up to valid seek frames:+ while (targetUpto < targetLimit) {+ cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);+ // if (DEBUG) {+ // System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);+ // }+ if (cmp != 0) {+ break;+ }+ arc = arcs[1+targetUpto];+ assert arc.label == (target.bytes[target.offset + targetUpto] & 0xFF): "arc.label=" + (char) arc.label + " targetLabel=" + (char) (target.bytes[target.offset + targetUpto] & 0xFF);+ if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ }+ if (arc.isFinal()) {+ lastFrame = stack[1+lastFrame.ord];+ }+ targetUpto++;+ }++ if (cmp == 0) {+ final int targetUptoMid = targetUpto;++ // Second compare the rest of the term, but+ // don't save arc/output/frame; we only do this+ // to find out if the target term is before,+ // equal or after the current term+ final int targetLimit2 = Math.min(target.length, term.length);+ while (targetUpto < targetLimit2) {+ cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);+ // if (DEBUG) {+ // System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");+ // }+ if (cmp != 0) {+ break;+ }+ targetUpto++;+ }++ if (cmp == 0) {+ cmp = term.length - target.length;+ }+ targetUpto = targetUptoMid;+ }++ if (cmp < 0) {+ // Common case: target term is after current+ // term, ie, app is seeking multiple terms+ // in sorted order+ // if (DEBUG) {+ // System.out.println(" target is after current (shares prefixLen=" + targetUpto + "); frame.ord=" + lastFrame.ord);+ // }+ currentFrame = lastFrame;++ } else if (cmp > 0) {+ // Uncommon case: target term+ // is before current term; this means we can+ // keep the currentFrame but we must rewind it+ // (so we scan from the start)+ targetBeforeCurrentLength = lastFrame.ord;+ // if (DEBUG) {+ // System.out.println(" target is before current (shares prefixLen=" + targetUpto + "); rewind frame ord=" + lastFrame.ord);+ // }+ currentFrame = lastFrame;+ currentFrame.rewind();+ } else {+ // Target is exactly the same as current term+ assert term.length == target.length;+ if (termExists) {+ // if (DEBUG) {+ // System.out.println(" target is same as current; return true");+ // }+ return true;+ } else {+ // if (DEBUG) {+ // System.out.println(" target is same as current but term doesn't exist");+ // }+ }+ //validIndexPrefix = currentFrame.depth;+ //term.length = target.length;+ //return termExists;+ }++ } else {++ targetBeforeCurrentLength = -1;+ arc = fr.index.getFirstArc(arcs[0]);++ // Empty string prefix must have an output (block) in the index!+ assert arc.isFinal();+ assert arc.output != null;++ // if (DEBUG) {+ // System.out.println(" no seek state; push root frame");+ // }++ output = arc.output;++ currentFrame = staticFrame;++ //term.length = 0;+ targetUpto = 0;+ currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), 0);+ }++ positioned = true;++ // if (DEBUG) {+ // System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);+ // }++ // We are done sharing the common prefix with the incoming target and where we are currently seek'd; now continue walking the index:+ while (targetUpto < target.length) {++ final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;++ final FST.Arc<Output> nextArc = fr.index.findTargetArc(targetLabel, arc, getArc(1+targetUpto), fstReader);++ if (nextArc == null) {++ // Index is exhausted+ // if (DEBUG) {+ // System.out.println(" index: index exhausted label=" + ((char) targetLabel) + " " + toHex(targetLabel));+ // }++ validIndexPrefix = currentFrame.prefix;+ //validIndexPrefix = targetUpto;++ currentFrame.scanToFloorFrame(target);++ if (!currentFrame.hasTerms) {+ termExists = false;+ term.bytes[targetUpto] = (byte) targetLabel;+ term.length = 1+targetUpto;+ // if (DEBUG) {+ // System.out.println(" FAST NOT_FOUND term=" + brToString(term));+ // }+ return false;+ }++ currentFrame.loadBlock();++ final SeekStatus result = currentFrame.scanToTerm(target, true);+ if (result == SeekStatus.FOUND) {+ // if (DEBUG) {+ // System.out.println(" return FOUND term=" + term.utf8ToString() + " " + term);+ // }+ return true;+ } else {+ // if (DEBUG) {+ // System.out.println(" got " + result + "; return NOT_FOUND term=" + brToString(term));+ // }+ return false;+ }+ } else {+ // Follow this arc+ arc = nextArc;+ term.bytes[targetUpto] = (byte) targetLabel;+ // Aggregate output as we go:+ assert arc.output != null;+ if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ }++ // if (DEBUG) {+ // System.out.println(" index: follow label=" + toHex(target.bytes[target.offset + targetUpto]&0xff) + " arc.output=" + arc.output + " arc.nfo=" + arc.nextFinalOutput);+ // }+ targetUpto++;++ if (arc.isFinal()) {+ //if (DEBUG) System.out.println(" arc is final!");+ currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), targetUpto);+ //if (DEBUG) System.out.println(" curFrame.ord=" + currentFrame.ord + " hasTerms=" + currentFrame.hasTerms);+ }+ }+ }++ //validIndexPrefix = targetUpto;+ validIndexPrefix = currentFrame.prefix;++ currentFrame.scanToFloorFrame(target);++ // Target term is entirely contained in the index:+ if (!currentFrame.hasTerms) {+ termExists = false;+ term.length = targetUpto;+ // if (DEBUG) {+ // System.out.println(" FAST NOT_FOUND term=" + brToString(term));+ // }+ return false;+ }++ currentFrame.loadBlock();++ final SeekStatus result = currentFrame.scanToTerm(target, true);+ if (result == SeekStatus.FOUND) {+ // if (DEBUG) {+ // System.out.println(" return FOUND term=" + term.utf8ToString() + " " + term);+ // }+ return true;+ } else {+ // if (DEBUG) {+ // System.out.println(" got result " + result + "; return NOT_FOUND term=" + term.utf8ToString());+ // }++ return false;+ }+ }++ @Override+ public SeekStatus seekCeil(final BytesRef target) throws IOException {+ if (fr.index == null) {+ throw new IllegalStateException("terms index was not loaded");+ }++ if (term.bytes.length <= target.length) {+ term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);+ }++ assert clearEOF();++ //if (DEBUG) {+ //System.out.println("\nBTTR.seekCeil seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + brToString(term) + " (exists?=" + termExists + ") validIndexPrefix= " + validIndexPrefix);+ //printSeekState();+ //}++ FST.Arc<Output> arc;+ int targetUpto;+ Output output;++ targetBeforeCurrentLength = currentFrame.ord;++ if (positioned && currentFrame != staticFrame) {++ // We are already seek'd; find the common+ // prefix of new seek term vs current term and+ // re-use the corresponding seek state. For+ // example, if app first seeks to foobar, then+ // seeks to foobaz, we can re-use the seek state+ // for the first 5 bytes.++ //if (DEBUG) {+ //System.out.println(" re-use current seek state validIndexPrefix=" + validIndexPrefix);+ //}++ arc = arcs[0];+ assert arc.isFinal();+ output = arc.output;+ targetUpto = 0;++ OrdsSegmentTermsEnumFrame lastFrame = stack[0];+ assert validIndexPrefix <= term.length;++ final int targetLimit = Math.min(target.length, validIndexPrefix);++ int cmp = 0;++ // TOOD: we should write our vLong backwards (MSB+ // first) to get better sharing from the FST++ // First compare up to valid seek frames:+ while (targetUpto < targetLimit) {+ cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);+ //if (DEBUG) {+ //System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);+ //}+ if (cmp != 0) {+ break;+ }+ arc = arcs[1+targetUpto];+ assert arc.label == (target.bytes[target.offset + targetUpto] & 0xFF): "arc.label=" + (char) arc.label + " targetLabel=" + (char) (target.bytes[target.offset + targetUpto] & 0xFF);+ // TOOD: we could save the outputs in local+ // byte[][] instead of making new objs ever+ // seek; but, often the FST doesn't have any+ // shared bytes (but this could change if we+ // reverse vLong byte order)+ if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ }+ if (arc.isFinal()) {+ lastFrame = stack[1+lastFrame.ord];+ }+ targetUpto++;+ }+++ if (cmp == 0) {+ final int targetUptoMid = targetUpto;+ // Second compare the rest of the term, but+ // don't save arc/output/frame:+ final int targetLimit2 = Math.min(target.length, term.length);+ while (targetUpto < targetLimit2) {+ cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);+ //if (DEBUG) {+ //System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");+ //}+ if (cmp != 0) {+ break;+ }+ targetUpto++;+ }++ if (cmp == 0) {+ cmp = term.length - target.length;+ }+ targetUpto = targetUptoMid;+ }++ if (cmp < 0) {+ // Common case: target term is after current+ // term, ie, app is seeking multiple terms+ // in sorted order+ //if (DEBUG) {+ //System.out.println(" target is after current (shares prefixLen=" + targetUpto + "); clear frame.scanned ord=" + lastFrame.ord);+ //}+ currentFrame = lastFrame;++ } else if (cmp > 0) {+ // Uncommon case: target term+ // is before current term; this means we can+ // keep the currentFrame but we must rewind it+ // (so we scan from the start)+ targetBeforeCurrentLength = 0;+ //if (DEBUG) {+ //System.out.println(" target is before current (shares prefixLen=" + targetUpto + "); rewind frame ord=" + lastFrame.ord);+ //}+ currentFrame = lastFrame;+ currentFrame.rewind();+ } else {+ // Target is exactly the same as current term+ assert term.length == target.length;+ if (termExists) {+ //if (DEBUG) {+ //System.out.println(" target is same as current; return FOUND");+ //}+ return SeekStatus.FOUND;+ } else {+ //if (DEBUG) {+ //System.out.println(" target is same as current but term doesn't exist");+ //}+ }+ }++ } else {++ targetBeforeCurrentLength = -1;+ arc = fr.index.getFirstArc(arcs[0]);++ // Empty string prefix must have an output (block) in the index!+ assert arc.isFinal();+ assert arc.output != null;++ //if (DEBUG) {+ //System.out.println(" no seek state; push root frame");+ //}++ output = arc.output;++ currentFrame = staticFrame;++ //term.length = 0;+ targetUpto = 0;+ currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), 0);+ }++ positioned = true;++ //if (DEBUG) {+ //System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord+1=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);+ //}++ // We are done sharing the common prefix with the incoming target and where we are currently seek'd; now continue walking the index:+ while (targetUpto < target.length) {++ final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;++ final FST.Arc<Output> nextArc = fr.index.findTargetArc(targetLabel, arc, getArc(1+targetUpto), fstReader);++ if (nextArc == null) {++ // Index is exhausted+ // if (DEBUG) {+ // System.out.println(" index: index exhausted label=" + ((char) targetLabel) + " " + toHex(targetLabel));+ // }++ validIndexPrefix = currentFrame.prefix;+ //validIndexPrefix = targetUpto;++ currentFrame.scanToFloorFrame(target);++ currentFrame.loadBlock();++ final SeekStatus result = currentFrame.scanToTerm(target, false);+ if (result == SeekStatus.END) {+ term.copyBytes(target);+ termExists = false;++ if (next() != null) {+ //if (DEBUG) {+ //System.out.println(" return NOT_FOUND term=" + brToString(term) + " " + term);+ //}+ return SeekStatus.NOT_FOUND;+ } else {+ //if (DEBUG) {+ //System.out.println(" return END");+ //}+ return SeekStatus.END;+ }+ } else {+ //if (DEBUG) {+ //System.out.println(" return " + result + " term=" + brToString(term) + " " + term);+ //}+ return result;+ }+ } else {+ // Follow this arc+ term.bytes[targetUpto] = (byte) targetLabel;+ arc = nextArc;+ // Aggregate output as we go:+ assert arc.output != null;+ if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ }++ //if (DEBUG) {+ //System.out.println(" index: follow label=" + toHex(target.bytes[target.offset + targetUpto]&0xff) + " arc.output=" + arc.output + " arc.nfo=" + arc.nextFinalOutput);+ //}+ targetUpto++;++ if (arc.isFinal()) {+ //if (DEBUG) System.out.println(" arc is final!");+ currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), targetUpto);+ //if (DEBUG) System.out.println(" curFrame.ord=" + currentFrame.ord + " hasTerms=" + currentFrame.hasTerms);+ }+ }+ }++ //validIndexPrefix = targetUpto;+ validIndexPrefix = currentFrame.prefix;++ currentFrame.scanToFloorFrame(target);++ currentFrame.loadBlock();++ final SeekStatus result = currentFrame.scanToTerm(target, false);++ if (result == SeekStatus.END) {+ term.copyBytes(target);+ termExists = false;+ if (next() != null) {+ //if (DEBUG) {+ //System.out.println(" return NOT_FOUND term=" + term.utf8ToString() + " " + term);+ //}+ return SeekStatus.NOT_FOUND;+ } else {+ //if (DEBUG) {+ //System.out.println(" return END");+ //}+ return SeekStatus.END;+ }+ } else {+ return result;+ }+ }++ @SuppressWarnings("unused")+ private void printSeekState(PrintStream out) throws IOException {+ if (currentFrame == staticFrame) {+ out.println(" no prior seek");+ } else {+ out.println(" prior seek state:");+ int ord = 0;+ boolean isSeekFrame = true;+ while(true) {+ OrdsSegmentTermsEnumFrame f = getFrame(ord);+ assert f != null;+ final BytesRef prefix = new BytesRef(term.bytes, 0, f.prefix);+ if (f.nextEnt == -1) {+ out.println(" frame " + (isSeekFrame ? "(seek)" : "(next)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd() + " termOrd=" + f.termOrd);+ } else {+ out.println(" frame " + (isSeekFrame ? "(seek, loaded)" : "(next, loaded)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + " nextEnt=" + f.nextEnt + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " lastSubFP=" + f.lastSubFP + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd() + " termOrd=" + f.termOrd);+ }+ if (fr.index != null) {+ assert !isSeekFrame || f.arc != null: "isSeekFrame=" + isSeekFrame + " f.arc=" + f.arc;+ if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.bytes[f.prefix-1]&0xFF)) {+ out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.bytes[f.prefix-1]&0xFF));+ throw new RuntimeException("seek state is broken");+ }+ Output output = Util.get(fr.index, prefix);+ if (output == null) {+ out.println(" broken seek state: prefix is not final in index");+ throw new RuntimeException("seek state is broken");+ } else if (isSeekFrame && !f.isFloor) {+ final ByteArrayDataInput reader = new ByteArrayDataInput(output.bytes.bytes, output.bytes.offset, output.bytes.length);+ final long codeOrig = reader.readVLong();+ final long code = (f.fp << OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) | (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) | (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0);+ if (codeOrig != code) {+ out.println(" broken seek state: output code=" + codeOrig + " doesn't match frame code=" + code);+ throw new RuntimeException("seek state is broken");+ }+ }+ }+ if (f == currentFrame) {+ break;+ }+ if (f.prefix == validIndexPrefix) {+ isSeekFrame = false;+ }+ ord++;+ }+ }+ }++ /* Decodes only the term bytes of the next term. If caller then asks for+ metadata, ie docFreq, totalTermFreq or pulls a D/&PEnum, we then (lazily)+ decode all metadata up to the current term. */+ @Override+ public BytesRef next() throws IOException {++ if (in == null) {+ // Fresh TermsEnum; seek to first term:+ final FST.Arc<Output> arc;+ if (fr.index != null) {+ arc = fr.index.getFirstArc(arcs[0]);+ // Empty string prefix must have an output in the index!+ assert arc.isFinal();+ } else {+ arc = null;+ }+ currentFrame = pushFrame(arc, fr.rootCode, 0);+ currentFrame.loadBlock();+ positioned = true;+ }++ targetBeforeCurrentLength = currentFrame.ord;++ assert !eof;+ //if (DEBUG) {+ //System.out.println("\nBTTR.next seg=" + segment + " term=" + brToString(term) + " termExists?=" + termExists + " field=" + fieldInfo.name + " termBlockOrd=" + currentFrame.state.termBlockOrd + " validIndexPrefix=" + validIndexPrefix);+ //printSeekState();+ //}++ if (currentFrame == staticFrame || positioned == false) {+ // If seek was previously called and the term was+ // cached, or seek(TermState) was called, usually+ // caller is just going to pull a D/&PEnum or get+ // docFreq, etc. But, if they then call next(),+ // this method catches up all internal state so next()+ // works properly:+ // if (DEBUG) System.out.println(" re-seek to pending term=" + term.utf8ToString() + " " + term);+ final boolean result = seekExact(term);+ assert result;+ }++ // Pop finished blocks+ while (currentFrame.nextEnt == currentFrame.entCount) {+ if (!currentFrame.isLastInFloor) {+ currentFrame.loadNextFloorBlock();+ } else {+ //if (DEBUG) System.out.println(" pop frame");+ if (currentFrame.ord == 0) {+ //if (DEBUG) System.out.println(" return null");+ assert setEOF();+ term.length = 0;+ validIndexPrefix = 0;+ currentFrame.rewind();+ termExists = false;+ positioned = false;+ return null;+ }+ final long lastFP = currentFrame.fpOrig;+ currentFrame = stack[currentFrame.ord-1];++ if (currentFrame.nextEnt == -1 || currentFrame.lastSubFP != lastFP) {+ // We popped into a frame that's not loaded+ // yet or not scan'd to the right entry+ currentFrame.scanToFloorFrame(term);+ currentFrame.loadBlock();+ currentFrame.scanToSubBlock(lastFP);+ }++ // Note that the seek state (last seek) has been+ // invalidated beyond this depth+ validIndexPrefix = Math.min(validIndexPrefix, currentFrame.prefix);+ //if (DEBUG) {+ //System.out.println(" reset validIndexPrefix=" + validIndexPrefix);+ //}+ }+ }++ while(true) {+ long prevTermOrd = currentFrame.termOrd;+ if (currentFrame.next()) {+ // Push to new block:+ //if (DEBUG) System.out.println(" push frame");+ currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length, prevTermOrd);+ // This is a "next" frame -- even if it's+ // floor'd we must pretend it isn't so we don't+ // try to scan to the right floor frame:+ currentFrame.isFloor = false;+ //currentFrame.hasTerms = true;+ currentFrame.loadBlock();+ } else {+ //if (DEBUG) System.out.println(" return term=" + term.utf8ToString() + " " + term + " currentFrame.ord=" + currentFrame.ord);+ positioned = true;+ return term;+ }+ }+ }++ @Override+ public BytesRef term() {+ assert !eof;+ return term;+ }++ @Override+ public long ord() {+ assert !eof;+ assert currentFrame.termOrd > 0;+ return currentFrame.termOrd-1;+ }++ @Override+ public int docFreq() throws IOException {+ assert !eof;+ //if (DEBUG) System.out.println("BTR.docFreq");+ currentFrame.decodeMetaData();+ //if (DEBUG) System.out.println(" return " + currentFrame.state.docFreq);+ return currentFrame.state.docFreq;+ }++ @Override+ public long totalTermFreq() throws IOException {+ assert !eof;+ currentFrame.decodeMetaData();+ return currentFrame.state.totalTermFreq;+ }++ @Override+ public DocsEnum docs(Bits skipDocs, DocsEnum reuse, int flags) throws IOException {+ assert !eof;+ //if (DEBUG) {+ //System.out.println("BTTR.docs seg=" + segment);+ //}+ currentFrame.decodeMetaData();+ //if (DEBUG) {+ //System.out.println(" state=" + currentFrame.state);+ //}+ return fr.parent.postingsReader.docs(fr.fieldInfo, currentFrame.state, skipDocs, reuse, flags);+ }++ @Override+ public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {+ if (fr.fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {+ // Positions were not indexed:+ return null;+ }++ assert !eof;+ currentFrame.decodeMetaData();+ return fr.parent.postingsReader.docsAndPositions(fr.fieldInfo, currentFrame.state, skipDocs, reuse, flags);+ }++ @Override+ public void seekExact(BytesRef target, TermState otherState) {+ // if (DEBUG) {+ // System.out.println("BTTR.seekExact termState seg=" + segment + " target=" + target.utf8ToString() + " " + target + " state=" + otherState);+ // }+ assert clearEOF();+ if (target.compareTo(term) != 0 || !termExists) {+ assert otherState != null && otherState instanceof BlockTermState;+ BlockTermState blockState = (BlockTermState) otherState;+ currentFrame = staticFrame;+ currentFrame.state.copyFrom(otherState);+ term.copyBytes(target);+ currentFrame.metaDataUpto = currentFrame.getTermBlockOrd();+ currentFrame.termOrd = blockState.ord+1;+ assert currentFrame.metaDataUpto > 0;+ validIndexPrefix = 0;+ } else {+ // if (DEBUG) {+ // System.out.println(" skip seek: already on target state=" + currentFrame.state);+ // }+ }+ positioned = true;+ }++ @Override+ public TermState termState() throws IOException {+ assert !eof;+ currentFrame.decodeMetaData();+ BlockTermState ts = (BlockTermState) currentFrame.state.clone();+ assert currentFrame.termOrd > 0;+ ts.ord = currentFrame.termOrd-1;+ //if (DEBUG) System.out.println("BTTR.termState seg=" + segment + " state=" + ts);+ return ts;+ }++ @Override+ public void seekExact(long targetOrd) throws IOException {+ // System.out.println("seekExact targetOrd=" + targetOrd);+ if (targetOrd < 0 || targetOrd >= fr.numTerms) {+ throw new IllegalArgumentException("targetOrd out of bounds (got: " + targetOrd + ", numTerms=" + fr.numTerms + ")");+ }++ assert clearEOF();++ // First do reverse lookup in the index to find the block that holds this term:+ InputOutput io = getByOutput(targetOrd);+ if (term.bytes.length < io.input.length) {+ term.bytes = ArrayUtil.grow(term.bytes, io.input.length);+ }++ Util.toBytesRef(io.input, term);+ if (io.input.length == 0) {+ currentFrame = staticFrame;+ } else {+ currentFrame = getFrame(io.input.length-1);+ }+ FST.Arc<Output> arc = getArc(io.input.length);++ // Don't force rewind based on term length; we rewind below based on ord:+ targetBeforeCurrentLength = Integer.MAX_VALUE;+ currentFrame = pushFrame(arc, io.output, io.input.length);+ if (currentFrame.termOrd > targetOrd) {+ //System.out.println(" do rewind: " + currentFrame.termOrd);+ currentFrame.rewind();+ }++ currentFrame.scanToFloorFrame(targetOrd);+ currentFrame.loadBlock();+ // System.out.println(" after loadBlock termOrd=" + currentFrame.termOrd + " vs " + targetOrd);++ while (currentFrame.termOrd <= targetOrd) {+ currentFrame.next();+ }++ assert currentFrame.termOrd == targetOrd+1: "currentFrame.termOrd=" + currentFrame.termOrd + " vs ord=" + targetOrd;+ assert termExists;++ // Leave enum fully unpositioned, because we didn't set frames for each byte leading up to current term:+ validIndexPrefix = 0;+ positioned = false;+ }++ @Override+ public String toString() {+ return "OrdsSegmentTermsEnum(seg=" + fr.parent.segment + ")";+ }++ /** Holds a single input (IntsRef) + output pair. */+ private static class InputOutput {+ public IntsRef input;+ public Output output;++ @Override+ public String toString() {+ return "InputOutput(input=" + input + " output=" + output + ")";+ }+ }++ private final FST.Arc<Output> arc = new FST.Arc<>();++ // TODO: this is similar to Util.getByOutput ... can we refactor/share?+ /** Specialized getByOutput that can understand the ranges (startOrd to endOrd) we use here, not just startOrd. */+ private InputOutput getByOutput(long targetOrd) throws IOException {++ final IntsRef result = new IntsRef();++ fr.index.getFirstArc(arc);+ Output output = arc.output;+ int upto = 0;++ int bestUpto = 0;+ Output bestOutput = null;++ /*+ Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot"));+ Util.toDot(fr.index, w, true, true);+ w.close();+ */++ // System.out.println("reverseLookup seg=" + fr.parent.segment + " output=" + targetOrd);++ while (true) {+ // System.out.println(" loop: output=" + output.startOrd + "-" + (Long.MAX_VALUE-output.endOrd) + " upto=" + upto + " arc=" + arc + " final?=" + arc.isFinal());+ if (arc.isFinal()) {+ final Output finalOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput);+ // System.out.println(" isFinal: " + finalOutput.startOrd + "-" + (Long.MAX_VALUE-finalOutput.endOrd));+ if (targetOrd >= finalOutput.startOrd && targetOrd <= Long.MAX_VALUE-finalOutput.endOrd) {+ // Only one range should match across all arc leaving this node+ //assert bestOutput == null;+ bestOutput = finalOutput;+ bestUpto = upto;+ }+ }++ if (FST.targetHasArcs(arc)) {+ // System.out.println(" targetHasArcs");+ if (result.ints.length == upto) {+ result.grow(1+upto);+ }++ fr.index.readFirstRealTargetArc(arc.target, arc, fstReader);++ if (arc.bytesPerArc != 0) {+ // System.out.println(" array arcs");++ int low = 0;+ int high = arc.numArcs-1;+ int mid = 0;+ //System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output);+ boolean found = false;+ while (low <= high) {+ mid = (low + high) >>> 1;+ fstReader.setPosition(arc.posArcsStart);+ fstReader.skipBytes(arc.bytesPerArc*mid);+ final byte flags = fstReader.readByte();+ fr.index.readLabel(fstReader);+ final Output minArcOutput;+ if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0) {+ minArcOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, OrdsBlockTreeTermsWriter.FST_OUTPUTS.read(fstReader));+ } else {+ minArcOutput = output;+ }+ // System.out.println(" cycle mid=" + mid + " targetOrd=" + targetOrd + " output=" + minArcOutput.startOrd + "-" + (Long.MAX_VALUE-minArcOutput.endOrd));+ if (targetOrd > Long.MAX_VALUE-minArcOutput.endOrd) {+ low = mid + 1;+ } else if (targetOrd < minArcOutput.startOrd) {+ high = mid - 1;+ } else {+ // System.out.println(" found!!");+ found = true;+ break;+ }+ }++ if (found) {+ // Keep recursing+ arc.arcIdx = mid-1;+ } else {+ result.length = bestUpto;+ InputOutput io = new InputOutput();+ io.input = result;+ io.output = bestOutput;+ // System.out.println(" ret0=" + io);+ return io;+ }++ fr.index.readNextRealArc(arc, fstReader);++ // Recurse on this arc:+ result.ints[upto++] = arc.label;+ output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);++ } else {+ // System.out.println(" non-array arc");++ while (true) {+ // System.out.println(" cycle label=" + arc.label + " output=" + arc.output);++ // This is the min output we'd hit if we follow+ // this arc:+ final Output minArcOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);+ long endOrd = Long.MAX_VALUE - minArcOutput.endOrd;+ // System.out.println(" endOrd=" + endOrd + " targetOrd=" + targetOrd);++ if (targetOrd >= minArcOutput.startOrd && targetOrd <= endOrd) {+ // Recurse on this arc:+ output = minArcOutput;+ result.ints[upto++] = arc.label;+ break;+ } else if (targetOrd < endOrd || arc.isLast()) {+ result.length = bestUpto;+ InputOutput io = new InputOutput();+ io.input = result;+ assert bestOutput != null;+ io.output = bestOutput;+ // System.out.println(" ret2=" + io);+ return io;+ } else {+ // System.out.println(" next arc");+ // Read next arc in this node:+ fr.index.readNextRealArc(arc, fstReader);+ }+ }+ }+ } else {+ result.length = bestUpto;+ InputOutput io = new InputOutput();+ io.input = result;+ io.output = bestOutput;+ // System.out.println(" ret3=" + io);+ return io;+ }+ }+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.javanew file mode 100644index 00000000000..83edf657abd--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java@@ -0,0 +1,851 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.TermsEnum.SeekStatus;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.fst.FST;++final class OrdsSegmentTermsEnumFrame {+ // Our index in stack[]:+ final int ord;+ // final boolean DEBUG = true;++ boolean hasTerms;+ boolean hasTermsOrig;+ boolean isFloor;++ // static boolean DEBUG = OrdsSegmentTermsEnum.DEBUG;++ FST.Arc<Output> arc;++ // File pointer where this block was loaded from+ long fp;+ long fpOrig;+ long fpEnd;++ byte[] suffixBytes = new byte[128];+ final ByteArrayDataInput suffixesReader = new ByteArrayDataInput();++ byte[] statBytes = new byte[64];+ final ByteArrayDataInput statsReader = new ByteArrayDataInput();++ byte[] floorData = new byte[32];+ final ByteArrayDataInput floorDataReader = new ByteArrayDataInput();++ // Length of prefix shared by all terms in this block+ int prefix;++ // Number of entries (term or sub-block) in this block+ int entCount;++ // Which term we will next read, or -1 if the block+ // isn't loaded yet+ int nextEnt;++ // Starting termOrd for this frame, used to reset termOrd in rewind()+ long termOrdOrig;++ // 1 + ordinal of the current term+ long termOrd;++ // True if this block is either not a floor block,+ // or, it's the last sub-block of a floor block+ boolean isLastInFloor;++ // True if all entries are terms+ boolean isLeafBlock;++ long lastSubFP;++ // Starting byte of next floor block:+ int nextFloorLabel;++ // Starting termOrd of next floor block:+ long nextFloorTermOrd;++ int numFollowFloorBlocks;++ // Next term to decode metaData; we decode metaData+ // lazily so that scanning to find the matching term is+ // fast and only if you find a match and app wants the+ // stats or docs/positions enums, will we decode the+ // metaData+ int metaDataUpto;++ final BlockTermState state;++ // metadata buffer, holding monotonic values+ public long[] longs;+ // metadata buffer, holding general values+ public byte[] bytes;+ ByteArrayDataInput bytesReader;++ private final OrdsSegmentTermsEnum ste;++ public OrdsSegmentTermsEnumFrame(OrdsSegmentTermsEnum ste, int ord) throws IOException {+ this.ste = ste;+ this.ord = ord;+ this.state = ste.fr.parent.postingsReader.newTermState();+ this.state.totalTermFreq = -1;+ this.longs = new long[ste.fr.longsSize];+ }++ public void setFloorData(ByteArrayDataInput in, BytesRef source) {+ final int numBytes = source.length - (in.getPosition() - source.offset);+ assert numBytes > 0;+ if (numBytes > floorData.length) {+ floorData = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ System.arraycopy(source.bytes, source.offset+in.getPosition(), floorData, 0, numBytes);+ floorDataReader.reset(floorData, 0, numBytes);+ numFollowFloorBlocks = floorDataReader.readVInt();+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ nextFloorTermOrd = termOrdOrig + floorDataReader.readVLong();+ // System.out.println(" setFloorData ord=" + ord + " nextFloorTermOrd=" + nextFloorTermOrd + " shift=" + (nextFloorTermOrd-termOrdOrig));++ //if (DEBUG) {+ //System.out.println(" setFloorData fpOrig=" + fpOrig + " bytes=" + new BytesRef(source.bytes, source.offset + in.getPosition(), numBytes) + " numFollowFloorBlocks=" + numFollowFloorBlocks + " nextFloorLabel=" + toHex(nextFloorLabel));+ //}+ }++ public int getTermBlockOrd() {+ return isLeafBlock ? nextEnt : state.termBlockOrd;+ }++ void loadNextFloorBlock() throws IOException {+ //if (DEBUG) {+ //System.out.println(" loadNextFloorBlock fp=" + fp + " fpEnd=" + fpEnd);+ //}+ assert arc == null || isFloor: "arc=" + arc + " isFloor=" + isFloor;+ // NOTE: we don't need to touch termOrd here, because we fully scanned this current frame+ fp = fpEnd;+ nextEnt = -1;+ loadBlock();+ }++ /* Does initial decode of next block of terms; this+ doesn't actually decode the docFreq, totalTermFreq,+ postings details (frq/prx offset, etc.) metadata;+ it just loads them as byte[] blobs which are then+ decoded on-demand if the metadata is ever requested+ for any term in this block. This enables terms-only+ intensive consumes (eg certain MTQs, respelling) to+ not pay the price of decoding metadata they won't+ use. */+ void loadBlock() throws IOException {++ // Clone the IndexInput lazily, so that consumers+ // that just pull a TermsEnum to+ // seekExact(TermState) don't pay this cost:+ ste.initIndexInput();++ if (nextEnt != -1) {+ // Already loaded+ return;+ }+ // System.out.println("loadBlock ord=" + ord + " termOrdOrig=" + termOrdOrig + " termOrd=" + termOrd + " fp=" + fp);++ ste.in.seek(fp);+ int code = ste.in.readVInt();+ entCount = code >>> 1;+ assert entCount > 0;+ isLastInFloor = (code & 1) != 0;+ assert arc == null || (isLastInFloor || isFloor);++ // TODO: if suffixes were stored in random-access+ // array structure, then we could do binary search+ // instead of linear scan to find target term; eg+ // we could have simple array of offsets++ // term suffixes:+ code = ste.in.readVInt();+ isLeafBlock = (code & 1) != 0;+ int numBytes = code >>> 1;+ if (suffixBytes.length < numBytes) {+ suffixBytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ ste.in.readBytes(suffixBytes, 0, numBytes);+ suffixesReader.reset(suffixBytes, 0, numBytes);++ /*if (DEBUG) {+ if (arc == null) {+ System.out.println(" loadBlock (next) fp=" + fp + " entCount=" + entCount + " prefixLen=" + prefix + " isLastInFloor=" + isLastInFloor + " leaf?=" + isLeafBlock);+ } else {+ System.out.println(" loadBlock (seek) fp=" + fp + " entCount=" + entCount + " prefixLen=" + prefix + " hasTerms?=" + hasTerms + " isFloor?=" + isFloor + " isLastInFloor=" + isLastInFloor + " leaf?=" + isLeafBlock);+ }+ }*/++ // stats+ numBytes = ste.in.readVInt();+ if (statBytes.length < numBytes) {+ statBytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ // System.out.println("READ stats numBytes=" + numBytes + " fp=" + ste.in.getFilePointer());+ ste.in.readBytes(statBytes, 0, numBytes);+ statsReader.reset(statBytes, 0, numBytes);+ metaDataUpto = 0;++ state.termBlockOrd = 0;+ nextEnt = 0;+ lastSubFP = -1;++ // TODO: we could skip this if !hasTerms; but+ // that's rare so won't help much+ // metadata+ numBytes = ste.in.readVInt();+ if (bytes == null) {+ bytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ bytesReader = new ByteArrayDataInput();+ } else if (bytes.length < numBytes) {+ bytes = new byte[ArrayUtil.oversize(numBytes, 1)];+ }+ ste.in.readBytes(bytes, 0, numBytes);+ bytesReader.reset(bytes, 0, numBytes);++ // Sub-blocks of a single floor block are always+ // written one after another -- tail recurse:+ fpEnd = ste.in.getFilePointer();+ // if (DEBUG) {+ // System.out.println(" fpEnd=" + fpEnd);+ // }+ }++ void rewind() {++ // Force reload:+ fp = fpOrig;+ termOrd = termOrdOrig;+ nextEnt = -1;+ hasTerms = hasTermsOrig;+ if (isFloor) {+ floorDataReader.rewind();+ numFollowFloorBlocks = floorDataReader.readVInt();+ assert numFollowFloorBlocks > 0;+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ nextFloorTermOrd = termOrdOrig + floorDataReader.readVLong();+ //System.out.println(" frame.rewind nextFloorTermOrd=" + nextFloorTermOrd);+ }++ /*+ //System.out.println("rewind");+ // Keeps the block loaded, but rewinds its state:+ if (nextEnt > 0 || fp != fpOrig) {+ if (DEBUG) {+ System.out.println(" rewind frame ord=" + ord + " fpOrig=" + fpOrig + " fp=" + fp + " hasTerms?=" + hasTerms + " isFloor?=" + isFloor + " nextEnt=" + nextEnt + " prefixLen=" + prefix);+ }+ if (fp != fpOrig) {+ fp = fpOrig;+ nextEnt = -1;+ } else {+ nextEnt = 0;+ }+ hasTerms = hasTermsOrig;+ if (isFloor) {+ floorDataReader.rewind();+ numFollowFloorBlocks = floorDataReader.readVInt();+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ }+ assert suffixBytes != null;+ suffixesReader.rewind();+ assert statBytes != null;+ statsReader.rewind();+ metaDataUpto = 0;+ state.termBlockOrd = 0;+ // TODO: skip this if !hasTerms? Then postings+ // impl wouldn't have to write useless 0 byte+ postingsReader.resetTermsBlock(fieldInfo, state);+ lastSubFP = -1;+ } else if (DEBUG) {+ System.out.println(" skip rewind fp=" + fp + " fpOrig=" + fpOrig + " nextEnt=" + nextEnt + " ord=" + ord);+ }+ */+ }++ public boolean next() {+ return isLeafBlock ? nextLeaf() : nextNonLeaf();+ }++ // Decodes next entry; returns true if it's a sub-block+ public boolean nextLeaf() {+ //if (DEBUG) System.out.println(" frame.next ord=" + ord + " nextEnt=" + nextEnt + " entCount=" + entCount);+ assert nextEnt != -1 && nextEnt < entCount: "nextEnt=" + nextEnt + " entCount=" + entCount + " fp=" + fp + " termOrd=" + termOrd;+ nextEnt++;+ termOrd++;+ suffix = suffixesReader.readVInt();+ startBytePos = suffixesReader.getPosition();+ ste.term.length = prefix + suffix;+ if (ste.term.bytes.length < ste.term.length) {+ ste.term.grow(ste.term.length);+ }+ suffixesReader.readBytes(ste.term.bytes, prefix, suffix);+ // A normal term+ ste.termExists = true;+ return false;+ }++ public boolean nextNonLeaf() {+ // if (DEBUG) System.out.println(" frame.next ord=" + ord + " nextEnt=" + nextEnt + " entCount=" + entCount);+ assert nextEnt != -1 && nextEnt < entCount: "nextEnt=" + nextEnt + " entCount=" + entCount + " fp=" + fp;+ nextEnt++;+ final int code = suffixesReader.readVInt();+ suffix = code >>> 1;+ startBytePos = suffixesReader.getPosition();+ ste.term.length = prefix + suffix;+ if (ste.term.bytes.length < ste.term.length) {+ ste.term.grow(ste.term.length);+ }+ suffixesReader.readBytes(ste.term.bytes, prefix, suffix);+ if ((code & 1) == 0) {+ // A normal term+ ste.termExists = true;+ subCode = 0;+ state.termBlockOrd++;+ termOrd++;+ return false;+ } else {+ // A sub-block; make sub-FP absolute:+ ste.termExists = false;+ subCode = suffixesReader.readVLong();+ termOrd += suffixesReader.readVLong();+ lastSubFP = fp - subCode;+ // if (DEBUG) {+ // System.out.println(" lastSubFP=" + lastSubFP);+ // }+ return true;+ }+ }++ // TODO: make this array'd so we can do bin search?+ // likely not worth it? need to measure how many+ // floor blocks we "typically" get+ public void scanToFloorFrame(BytesRef target) {++ if (!isFloor || target.length <= prefix) {+ // if (DEBUG) {+ // System.out.println(" scanToFloorFrame skip: isFloor=" + isFloor + " target.length=" + target.length + " vs prefix=" + prefix);+ // }+ return;+ }++ final int targetLabel = target.bytes[target.offset + prefix] & 0xFF;++ // if (DEBUG) {+ // System.out.println(" scanToFloorFrame fpOrig=" + fpOrig + " targetLabel=" + ((char) targetLabel) + " vs nextFloorLabel=" + ((char) nextFloorLabel) + " numFollowFloorBlocks=" + numFollowFloorBlocks);+ // }++ if (targetLabel < nextFloorLabel) {+ // if (DEBUG) {+ // System.out.println(" already on correct block");+ // }+ return;+ }++ assert numFollowFloorBlocks != 0;++ long newFP = fpOrig;+ long lastFloorTermOrd = nextFloorTermOrd;+ while (true) {+ final long code = floorDataReader.readVLong();+ newFP = fpOrig + (code >>> 1);+ hasTerms = (code & 1) != 0;+ // if (DEBUG) {+ // System.out.println(" label=" + ((char) nextFloorLabel) + " fp=" + newFP + " hasTerms?=" + hasTerms + " numFollowFloor=" + numFollowFloorBlocks);+ // }++ isLastInFloor = numFollowFloorBlocks == 1;+ numFollowFloorBlocks--;++ lastFloorTermOrd = nextFloorTermOrd;++ if (isLastInFloor) {+ nextFloorLabel = 256;+ nextFloorTermOrd = Long.MAX_VALUE;+ // if (DEBUG) {+ // System.out.println(" stop! last block nextFloorLabel=" + ((char) nextFloorLabel));+ // }+ break;+ } else {+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ nextFloorTermOrd += floorDataReader.readVLong();+ //System.out.println(" scanToFloorFrame: nextFloorTermOrd=" + nextFloorTermOrd);+ if (targetLabel < nextFloorLabel) {+ // if (DEBUG) {+ // System.out.println(" stop! nextFloorLabel=" + ((char) nextFloorLabel));+ // }+ break;+ }+ }+ }++ if (newFP != fp) {+ // Force re-load of the block:+ // if (DEBUG) {+ // System.out.println(" force switch to fp=" + newFP + " oldFP=" + fp);+ // }+ nextEnt = -1;+ termOrd = lastFloorTermOrd;+ fp = newFP;+ } else {+ // if (DEBUG) {+ // System.out.println(" stay on same fp=" + newFP);+ // }+ }+ }++ // TODO: make this array'd so we can do bin search?+ // likely not worth it? need to measure how many+ // floor blocks we "typically" get+ public void scanToFloorFrame(long targetOrd) {+ // System.out.println(" scanToFloorFrame targetOrd=" + targetOrd + " vs nextFloorTermOrd=" + nextFloorTermOrd + " numFollowFloorBlocks=" + numFollowFloorBlocks + " termOrdOrig=" + termOrdOrig);++ if (!isFloor || targetOrd < nextFloorTermOrd) {+ return;+ }++ assert numFollowFloorBlocks != 0;+ long lastFloorTermOrd = nextFloorTermOrd;++ long newFP = fpOrig;+ while (true) {+ final long code = floorDataReader.readVLong();+ newFP = fpOrig + (code >>> 1);+ hasTerms = (code & 1) != 0;+ // if (DEBUG) {+ // System.out.println(" label=" + ((char) nextFloorLabel) + " fp=" + newFP + " hasTerms?=" + hasTerms + " numFollowFloor=" + numFollowFloorBlocks);+ // }++ isLastInFloor = numFollowFloorBlocks == 1;+ numFollowFloorBlocks--;++ lastFloorTermOrd = nextFloorTermOrd;++ if (isLastInFloor) {+ nextFloorLabel = 256;+ nextFloorTermOrd = Long.MAX_VALUE;+ // if (DEBUG) {+ // System.out.println(" stop! last block nextFloorLabel=" + ((char) nextFloorLabel));+ // }+ break;+ } else {+ nextFloorLabel = floorDataReader.readByte() & 0xff;+ nextFloorTermOrd += floorDataReader.readVLong();+ if (targetOrd < nextFloorTermOrd) {+ // if (DEBUG) {+ // System.out.println(" stop! nextFloorLabel=" + ((char) nextFloorLabel));+ // }+ break;+ }+ }+ }+ // System.out.println(" after: lastFloorTermOrd=" + lastFloorTermOrd + " newFP=" + newFP + " vs fp=" + fp + " lastFloorTermOrd=" + lastFloorTermOrd);++ if (newFP != fp) {+ // Force re-load of the block:+ // if (DEBUG) {+ // System.out.println(" force switch to fp=" + newFP + " oldFP=" + fp);+ // }+ nextEnt = -1;+ termOrd = lastFloorTermOrd;+ fp = newFP;+ } else {+ // if (DEBUG) {+ // System.out.println(" stay on same fp=" + newFP);+ // }+ }+ }++ public void decodeMetaData() throws IOException {++ assert nextEnt >= 0;++ // lazily catch up on metadata decode:+ final int limit = getTermBlockOrd();+ boolean absolute = metaDataUpto == 0;+ assert limit > 0: "limit=" + limit + " isLeafBlock=" + isLeafBlock + " nextEnt=" + nextEnt;++ // if (DEBUG) System.out.println("\nBTTR.decodeMetadata seg=" + ste.fr.parent.segment + " mdUpto=" + metaDataUpto + " vs termBlockOrd=" + state.termBlockOrd + " limit=" + limit);++ // TODO: better API would be "jump straight to term=N"???+ while (metaDataUpto < limit) {++ // TODO: we could make "tiers" of metadata, ie,+ // decode docFreq/totalTF but don't decode postings+ // metadata; this way caller could get+ // docFreq/totalTF w/o paying decode cost for+ // postings++ // TODO: if docFreq were bulk decoded we could+ // just skipN here:++ // stats+ state.docFreq = statsReader.readVInt();+ //if (DEBUG) System.out.println(" dF=" + state.docFreq);+ if (ste.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {+ state.totalTermFreq = state.docFreq + statsReader.readVLong();+ //if (DEBUG) System.out.println(" totTF=" + state.totalTermFreq);+ }+ //if (DEBUG) System.out.println(" longsSize=" + ste.fr.longsSize);++ // metadata+ for (int i = 0; i < ste.fr.longsSize; i++) {+ longs[i] = bytesReader.readVLong();+ }+ ste.fr.parent.postingsReader.decodeTerm(longs, bytesReader, ste.fr.fieldInfo, state, absolute);++ metaDataUpto++;+ absolute = false;+ }+ state.termBlockOrd = metaDataUpto;+ }++ // Used only by assert+ private boolean prefixMatches(BytesRef target) {+ for(int bytePos=0;bytePos<prefix;bytePos++) {+ if (target.bytes[target.offset + bytePos] != ste.term.bytes[bytePos]) {+ return false;+ }+ }++ return true;+ }++ // Scans to sub-block that has this target fp; only+ // called by next(); NOTE: does not set+ // startBytePos/suffix as a side effect+ public void scanToSubBlock(long subFP) {+ assert !isLeafBlock;+ //if (DEBUG) System.out.println(" scanToSubBlock fp=" + fp + " subFP=" + subFP + " entCount=" + entCount + " lastSubFP=" + lastSubFP);+ //assert nextEnt == 0;+ if (lastSubFP == subFP) {+ //if (DEBUG) System.out.println(" already positioned");+ return;+ }+ assert subFP < fp : "fp=" + fp + " subFP=" + subFP;+ final long targetSubCode = fp - subFP;+ //if (DEBUG) System.out.println(" targetSubCode=" + targetSubCode);+ while(true) {+ assert nextEnt < entCount;+ nextEnt++;+ final int code = suffixesReader.readVInt();+ suffixesReader.skipBytes(isLeafBlock ? code : code >>> 1);+ //if (DEBUG) System.out.println(" " + nextEnt + " (of " + entCount + ") ent isSubBlock=" + ((code&1)==1));+ if ((code & 1) != 0) {+ final long subCode = suffixesReader.readVLong();+ termOrd += suffixesReader.readVLong();++ //if (DEBUG) System.out.println(" subCode=" + subCode);+ if (targetSubCode == subCode) {+ //if (DEBUG) System.out.println(" match!");+ lastSubFP = subFP;+ return;+ }+ } else {+ state.termBlockOrd++;+ termOrd++;+ }+ }+ }++ // NOTE: sets startBytePos/suffix as a side effect+ public SeekStatus scanToTerm(BytesRef target, boolean exactOnly) throws IOException {+ return isLeafBlock ? scanToTermLeaf(target, exactOnly) : scanToTermNonLeaf(target, exactOnly);+ }++ private int startBytePos;+ private int suffix;+ private long subCode;++ // Target's prefix matches this block's prefix; we+ // scan the entries check if the suffix matches.+ public SeekStatus scanToTermLeaf(BytesRef target, boolean exactOnly) throws IOException {++ // if (DEBUG) System.out.println(" scanToTermLeaf: block fp=" + fp + " prefix=" + prefix + " nextEnt=" + nextEnt + " (of " + entCount + ") target=" + OrdsSegmentTermsEnum.brToString(target) + " term=" + OrdsSegmentTermsEnum.brToString(ste.term));++ assert nextEnt != -1;++ ste.termExists = true;+ subCode = 0;++ if (nextEnt == entCount) {+ if (exactOnly) {+ fillTerm();+ }+ return SeekStatus.END;+ }++ assert prefixMatches(target);++ // Loop over each entry (term or sub-block) in this block:+ //nextTerm: while(nextEnt < entCount) {+ nextTerm: while (true) {+ nextEnt++;+ termOrd++;++ suffix = suffixesReader.readVInt();++ // if (DEBUG) {+ // BytesRef suffixBytesRef = new BytesRef();+ // suffixBytesRef.bytes = suffixBytes;+ // suffixBytesRef.offset = suffixesReader.getPosition();+ // suffixBytesRef.length = suffix;+ // System.out.println(" cycle: term " + (nextEnt-1) + " (of " + entCount + ") suffix=" + OrdsSegmentTermsEnum.brToString(suffixBytesRef));+ // }++ final int termLen = prefix + suffix;+ startBytePos = suffixesReader.getPosition();+ suffixesReader.skipBytes(suffix);++ final int targetLimit = target.offset + (target.length < termLen ? target.length : termLen);+ int targetPos = target.offset + prefix;++ // Loop over bytes in the suffix, comparing to+ // the target+ int bytePos = startBytePos;+ while(true) {+ final int cmp;+ final boolean stop;+ if (targetPos < targetLimit) {+ cmp = (suffixBytes[bytePos++]&0xFF) - (target.bytes[targetPos++]&0xFF);+ stop = false;+ } else {+ assert targetPos == targetLimit;+ cmp = termLen - target.length;+ stop = true;+ }++ if (cmp < 0) {+ // Current entry is still before the target;+ // keep scanning++ if (nextEnt == entCount) {+ if (exactOnly) {+ fillTerm();+ }+ // We are done scanning this block+ break nextTerm;+ } else {+ continue nextTerm;+ }+ } else if (cmp > 0) {++ // Done! Current entry is after target --+ // return NOT_FOUND:+ fillTerm();++ if (!exactOnly && !ste.termExists) {+ // We are on a sub-block, and caller wants+ // us to position to the next term after+ // the target, so we must recurse into the+ // sub-frame(s):+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen, ste.currentFrame.termOrd);+ ste.currentFrame.loadBlock();+ while (ste.currentFrame.next()) {+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length, ste.currentFrame.termOrd);+ ste.currentFrame.loadBlock();+ }+ }++ //if (DEBUG) System.out.println(" not found");+ return SeekStatus.NOT_FOUND;+ } else if (stop) {+ // Exact match!++ // This cannot be a sub-block because we+ // would have followed the index to this+ // sub-block from the start:++ assert ste.termExists;+ fillTerm();+ //if (DEBUG) System.out.println(" found!");+ return SeekStatus.FOUND;+ }+ }+ }++ // It is possible (and OK) that terms index pointed us+ // at this block, but, we scanned the entire block and+ // did not find the term to position to. This happens+ // when the target is after the last term in the block+ // (but, before the next term in the index). EG+ // target could be foozzz, and terms index pointed us+ // to the foo* block, but the last term in this block+ // was fooz (and, eg, first term in the next block will+ // bee fop).+ //if (DEBUG) System.out.println(" block end");+ if (exactOnly) {+ fillTerm();+ }++ // TODO: not consistent that in the+ // not-exact case we don't next() into the next+ // frame here+ return SeekStatus.END;+ }++ // Target's prefix matches this block's prefix; we+ // scan the entries check if the suffix matches.+ public SeekStatus scanToTermNonLeaf(BytesRef target, boolean exactOnly) throws IOException {++ // if (DEBUG) System.out.println(" scanToTermNonLeaf: block fp=" + fp + " prefix=" + prefix + " nextEnt=" + nextEnt + " (of " + entCount + ") target=" + OrdsSegmentTermsEnum.brToString(target) + " term=" + OrdsSegmentTermsEnum.brToString(ste.term));++ assert nextEnt != -1;++ if (nextEnt == entCount) {+ if (exactOnly) {+ fillTerm();+ ste.termExists = subCode == 0;+ }+ return SeekStatus.END;+ }++ assert prefixMatches(target);++ // Loop over each entry (term or sub-block) in this block:+ //nextTerm: while(nextEnt < entCount) {+ nextTerm: while (true) {+ nextEnt++;++ final int code = suffixesReader.readVInt();+ suffix = code >>> 1;+ // if (DEBUG) {+ // BytesRef suffixBytesRef = new BytesRef();+ // suffixBytesRef.bytes = suffixBytes;+ // suffixBytesRef.offset = suffixesReader.getPosition();+ // suffixBytesRef.length = suffix;+ // System.out.println(" cycle: " + ((code&1)==1 ? "sub-block" : "term") + " " + (nextEnt-1) + " (of " + entCount + ") suffix=" + brToString(suffixBytesRef));+ // }++ ste.termExists = (code & 1) == 0;+ final int termLen = prefix + suffix;+ startBytePos = suffixesReader.getPosition();+ suffixesReader.skipBytes(suffix);+ if (ste.termExists) {+ state.termBlockOrd++;+ termOrd++;+ subCode = 0;+ } else {+ subCode = suffixesReader.readVLong();+ termOrd += suffixesReader.readVLong();+ lastSubFP = fp - subCode;+ }++ final int targetLimit = target.offset + (target.length < termLen ? target.length : termLen);+ int targetPos = target.offset + prefix;++ // Loop over bytes in the suffix, comparing to+ // the target+ int bytePos = startBytePos;+ while(true) {+ final int cmp;+ final boolean stop;+ if (targetPos < targetLimit) {+ cmp = (suffixBytes[bytePos++]&0xFF) - (target.bytes[targetPos++]&0xFF);+ stop = false;+ } else {+ assert targetPos == targetLimit;+ cmp = termLen - target.length;+ stop = true;+ }++ if (cmp < 0) {+ // Current entry is still before the target;+ // keep scanning++ if (nextEnt == entCount) {+ if (exactOnly) {+ fillTerm();+ //termExists = true;+ }+ // We are done scanning this block+ break nextTerm;+ } else {+ continue nextTerm;+ }+ } else if (cmp > 0) {++ // Done! Current entry is after target --+ // return NOT_FOUND:+ fillTerm();++ if (!exactOnly && !ste.termExists) {+ // We are on a sub-block, and caller wants+ // us to position to the next term after+ // the target, so we must recurse into the+ // sub-frame(s):+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen, ste.currentFrame.termOrd);+ ste.currentFrame.loadBlock();+ while (ste.currentFrame.next()) {+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length, ste.currentFrame.termOrd);+ ste.currentFrame.loadBlock();+ }+ }++ //if (DEBUG) System.out.println(" not found");+ return SeekStatus.NOT_FOUND;+ } else if (stop) {+ // Exact match!++ // This cannot be a sub-block because we+ // would have followed the index to this+ // sub-block from the start:++ assert ste.termExists;+ fillTerm();+ //if (DEBUG) System.out.println(" found!");+ return SeekStatus.FOUND;+ }+ }+ }++ // It is possible (and OK) that terms index pointed us+ // at this block, but, we scanned the entire block and+ // did not find the term to position to. This happens+ // when the target is after the last term in the block+ // (but, before the next term in the index). EG+ // target could be foozzz, and terms index pointed us+ // to the foo* block, but the last term in this block+ // was fooz (and, eg, first term in the next block will+ // bee fop).+ //if (DEBUG) System.out.println(" block end");+ if (exactOnly) {+ fillTerm();+ }++ // TODO: not consistent that in the+ // not-exact case we don't next() into the next+ // frame here+ return SeekStatus.END;+ }++ private void fillTerm() {+ final int termLength = prefix + suffix;+ ste.term.length = prefix + suffix;+ if (ste.term.bytes.length < termLength) {+ ste.term.grow(termLength);+ }+ System.arraycopy(suffixBytes, startBytePos, ste.term.bytes, prefix, suffix);+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/package.html b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/package.htmlnew file mode 100644index 00000000000..4af09d5c6c2--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/package.html@@ -0,0 +1,27 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<!--+ 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.+-->+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+</head>+<body>+Same postings format as Lucene41, except the terms dictionary also+supports ords, i.e. returning which ord the enum is seeked to, and+seeking by ord.+</body>+</html>diff --git a/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormatindex 40a0c3550e8..500bb53bc49 100644--- a/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat+++ b/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat@@ -13,12 +13,13 @@# See the License for the specific language governing permissions and# limitations under the License.-org.apache.lucene.codecs.pulsing.Pulsing41PostingsFormat-org.apache.lucene.codecs.simpletext.SimpleTextPostingsFormat-org.apache.lucene.codecs.memory.MemoryPostingsFormat+org.apache.lucene.codecs.blocktreeords.Ords41PostingsFormatorg.apache.lucene.codecs.bloom.BloomFilteringPostingsFormatorg.apache.lucene.codecs.memory.DirectPostingsFormat-org.apache.lucene.codecs.memory.FSTPulsing41PostingsFormat+org.apache.lucene.codecs.memory.FSTOrdPostingsFormatorg.apache.lucene.codecs.memory.FSTOrdPulsing41PostingsFormatorg.apache.lucene.codecs.memory.FSTPostingsFormat-org.apache.lucene.codecs.memory.FSTOrdPostingsFormat+org.apache.lucene.codecs.memory.FSTPulsing41PostingsFormat+org.apache.lucene.codecs.memory.MemoryPostingsFormat+org.apache.lucene.codecs.pulsing.Pulsing41PostingsFormat+org.apache.lucene.codecs.simpletext.SimpleTextPostingsFormatdiff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/blocktreeords/TestOrdsBlockTree.java b/lucene/codecs/src/test/org/apache/lucene/codecs/blocktreeords/TestOrdsBlockTree.javanew file mode 100644index 00000000000..166fb0587e7--- /dev/null+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/blocktreeords/TestOrdsBlockTree.java@@ -0,0 +1,360 @@+package org.apache.lucene.codecs.blocktreeords;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.codecs.Codec;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.BasePostingsFormatTestCase;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.MultiFields;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.TestUtil;++public class TestOrdsBlockTree extends BasePostingsFormatTestCase {+ private final Codec codec = TestUtil.alwaysPostingsFormat(new Ords41PostingsFormat());++ @Override+ protected Codec getCodec() {+ return codec;+ }++ public void testBasic() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newTextField("field", "a b c", Field.Store.NO));+ w.addDocument(doc);+ IndexReader r = w.getReader();+ TermsEnum te = MultiFields.getTerms(r, "field").iterator(null);++ // Test next()+ assertEquals(new BytesRef("a"), te.next());+ assertEquals(0L, te.ord());+ assertEquals(new BytesRef("b"), te.next());+ assertEquals(1L, te.ord());+ assertEquals(new BytesRef("c"), te.next());+ assertEquals(2L, te.ord());+ assertNull(te.next());++ // Test seekExact by term+ assertTrue(te.seekExact(new BytesRef("b")));+ assertEquals(1, te.ord());+ assertTrue(te.seekExact(new BytesRef("a")));+ assertEquals(0, te.ord());+ assertTrue(te.seekExact(new BytesRef("c")));+ assertEquals(2, te.ord());++ // Test seekExact by ord+ te.seekExact(1);+ assertEquals(new BytesRef("b"), te.term());+ te.seekExact(0);+ assertEquals(new BytesRef("a"), te.term());+ te.seekExact(2);+ assertEquals(new BytesRef("c"), te.term());++ r.close();+ w.close();+ dir.close();+ }++ public void testTwoBlocks() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ List<String> terms = new ArrayList<>();+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "m" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ w.forceMerge(1);+ IndexReader r = w.getReader();+ TermsEnum te = MultiFields.getTerms(r, "field").iterator(null);++ assertTrue(te.seekExact(new BytesRef("mo")));+ assertEquals(27, te.ord());++ te.seekExact(54);+ assertEquals(new BytesRef("s"), te.term());++ Collections.sort(terms);++ for(int i=terms.size()-1;i>=0;i--) {+ te.seekExact(i);+ assertEquals(i, te.ord());+ assertEquals(terms.get(i), te.term().utf8ToString());+ }++ int iters = atLeast(1000);+ for(int iter=0;iter<iters;iter++) {+ int ord = random().nextInt(terms.size());+ BytesRef term = new BytesRef(terms.get(ord));+ if (random().nextBoolean()) {+ if (VERBOSE) {+ System.out.println("TEST: iter=" + iter + " seek to ord=" + ord + " of " + terms.size());+ }+ te.seekExact(ord);+ } else {+ if (VERBOSE) {+ System.out.println("TEST: iter=" + iter + " seek to term=" + terms.get(ord) + " ord=" + ord + " of " + terms.size());+ }+ te.seekExact(term);+ }+ assertEquals(ord, te.ord());+ assertEquals(term, te.term());+ }++ r.close();+ w.close();+ dir.close();+ }++ public void testThreeBlocks() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ List<String> terms = new ArrayList<>();+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "m" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "mo" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ w.forceMerge(1);+ IndexReader r = w.getReader();+ TermsEnum te = MultiFields.getTerms(r, "field").iterator(null);++ if (VERBOSE) {+ while (te.next() != null) {+ System.out.println("TERM: " + te.ord() + " " + te.term().utf8ToString());+ }+ }++ assertTrue(te.seekExact(new BytesRef("mo")));+ assertEquals(27, te.ord());++ te.seekExact(90);+ assertEquals(new BytesRef("s"), te.term());++ testEnum(te, terms);++ r.close();+ w.close();+ dir.close();+ }++ private void testEnum(TermsEnum te, List<String> terms) throws IOException {+ Collections.sort(terms);+ for(int i=terms.size()-1;i>=0;i--) {+ if (VERBOSE) {+ System.out.println("TEST: seek to ord=" + i);+ }+ te.seekExact(i);+ assertEquals(i, te.ord());+ assertEquals(terms.get(i), te.term().utf8ToString());+ }++ int iters = atLeast(1000);+ for(int iter=0;iter<iters;iter++) {+ int ord = random().nextInt(terms.size());+ if (random().nextBoolean()) {+ te.seekExact(ord);+ assertEquals(terms.get(ord), te.term().utf8ToString());+ } else {+ te.seekExact(new BytesRef(terms.get(ord)));+ assertEquals(ord, te.ord());+ }+ }+ }++ public void testFloorBlocks() throws Exception {+ Directory dir = newDirectory();+ IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));+ IndexWriter w = new IndexWriter(dir, iwc);+ for(int i=0;i<128;i++) {+ Document doc = new Document();+ String term = "" + (char) i;+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term + " bytes=" + new BytesRef(term));+ }+ doc.add(newStringField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ w.forceMerge(1);+ IndexReader r = DirectoryReader.open(w, true);+ TermsEnum te = MultiFields.getTerms(r, "field").iterator(null);++ if (VERBOSE) {+ BytesRef term;+ while ((term = te.next()) != null) {+ System.out.println(" " + te.ord() + ": " + term.utf8ToString());+ }+ }++ assertTrue(te.seekExact(new BytesRef("a")));+ assertEquals(97, te.ord());++ te.seekExact(98);+ assertEquals(new BytesRef("b"), te.term());++ assertTrue(te.seekExact(new BytesRef("z")));+ assertEquals(122, te.ord());++ r.close();+ w.close();+ dir.close();+ }++ public void testNonRootFloorBlocks() throws Exception {+ Directory dir = newDirectory();+ IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));+ IndexWriter w = new IndexWriter(dir, iwc);+ List<String> terms = new ArrayList<>();+ for(int i=0;i<36;i++) {+ Document doc = new Document();+ String term = "" + (char) (97+i);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term);+ }+ doc.add(newTextField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ for(int i=0;i<128;i++) {+ Document doc = new Document();+ String term = "m" + (char) i;+ terms.add(term);+ if (VERBOSE) {+ System.out.println("i=" + i + " term=" + term + " bytes=" + new BytesRef(term));+ }+ doc.add(newStringField("field", term, Field.Store.NO));+ w.addDocument(doc);+ }+ w.forceMerge(1);+ IndexReader r = DirectoryReader.open(w, true);+ TermsEnum te = MultiFields.getTerms(r, "field").iterator(null);++ BytesRef term;+ int ord = 0;+ while ((term = te.next()) != null) {+ if (VERBOSE) {+ System.out.println("TEST: " + te.ord() + ": " + term.utf8ToString());+ }+ assertEquals(ord, te.ord());+ ord++;+ }++ testEnum(te, terms);++ r.close();+ w.close();+ dir.close();+ }++ public void testSeveralNonRootBlocks() throws Exception {+ Directory dir = newDirectory();+ IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));+ IndexWriter w = new IndexWriter(dir, iwc);+ List<String> terms = new ArrayList<>();+ for(int i=0;i<30;i++) {+ for(int j=0;j<30;j++) {+ Document doc = new Document();+ String term = "" + (char) (97+i) + (char) (97+j);+ terms.add(term);+ if (VERBOSE) {+ System.out.println("term=" + term);+ }+ doc.add(newTextField("body", term, Field.Store.NO));+ w.addDocument(doc);+ }+ }+ w.forceMerge(1);+ IndexReader r = DirectoryReader.open(w, true);+ TermsEnum te = MultiFields.getTerms(r, "body").iterator(null);++ for(int i=0;i<30;i++) {+ for(int j=0;j<30;j++) {+ String term = "" + (char) (97+i) + (char) (97+j);+ if (VERBOSE) {+ System.out.println("TEST: check term=" + term);+ }+ assertEquals(term, te.next().utf8ToString());+ assertEquals(30*i+j, te.ord());+ }+ }++ testEnum(te, terms);++ te.seekExact(0);+ assertEquals("aa", te.term().utf8ToString());++ r.close();+ w.close();+ dir.close();+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.javaindex 2f19c32b739..ec681d92473 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java@@ -222,6 +222,7 @@ final class SegmentTermsEnumFrame {if (isFloor) {floorDataReader.rewind();numFollowFloorBlocks = floorDataReader.readVInt();+ assert numFollowFloorBlocks > 0;nextFloorLabel = floorDataReader.readByte() & 0xff;}diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.javaindex 4c22e58900b..cf4a64c0e9e 100644--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java@@ -43,6 +43,7 @@ import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CommandLineUtil;import org.apache.lucene.util.FixedBitSet;+import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.LongBitSet;import org.apache.lucene.util.StringHelper;@@ -329,6 +330,20 @@ public class CheckIndex {return crossCheckTermVectors;}+ private boolean failFast;++ /** If true, just throw the original exception immediately when+ * corruption is detected, rather than continuing to iterate to other+ * segments looking for more corruption. */+ public void setFailFast(boolean v) {+ failFast = v;+ }++ /** See {@link #setFailFast}. */+ public boolean getFailFast() {+ return failFast;+ }+private boolean verbose;/** Set infoStream where messages should go. If null, no@@ -382,6 +397,9 @@ public class CheckIndex {try {sis.read(dir);} catch (Throwable t) {+ if (failFast) {+ IOUtils.reThrow(t);+ }msg(infoStream, "ERROR: could not read any segments file in directory");result.missingSegments = true;if (infoStream != null)@@ -417,6 +435,9 @@ public class CheckIndex {try {input = dir.openInput(segmentsFileName, IOContext.READONCE);} catch (Throwable t) {+ if (failFast) {+ IOUtils.reThrow(t);+ }msg(infoStream, "ERROR: could not open segments file in directory");if (infoStream != null)t.printStackTrace(infoStream);@@ -427,6 +448,9 @@ public class CheckIndex {try {format = input.readInt();} catch (Throwable t) {+ if (failFast) {+ IOUtils.reThrow(t);+ }msg(infoStream, "ERROR: could not read segment file version in directory");if (infoStream != null)t.printStackTrace(infoStream);@@ -607,18 +631,18 @@ public class CheckIndex {segInfoStat.numFields = fieldInfos.size();// Test Field Norms- segInfoStat.fieldNormStatus = testFieldNorms(reader, infoStream);+ segInfoStat.fieldNormStatus = testFieldNorms(reader, infoStream, failFast);// Test the Term Index- segInfoStat.termIndexStatus = testPostings(reader, infoStream, verbose);+ segInfoStat.termIndexStatus = testPostings(reader, infoStream, verbose, failFast);// Test Stored Fields- segInfoStat.storedFieldStatus = testStoredFields(reader, infoStream);+ segInfoStat.storedFieldStatus = testStoredFields(reader, infoStream, failFast);// Test Term Vectors- segInfoStat.termVectorStatus = testTermVectors(reader, infoStream, verbose, crossCheckTermVectors);+ segInfoStat.termVectorStatus = testTermVectors(reader, infoStream, verbose, crossCheckTermVectors, failFast);- segInfoStat.docValuesStatus = testDocValues(reader, infoStream);+ segInfoStat.docValuesStatus = testDocValues(reader, infoStream, failFast);// Rethrow the first exception we encountered// This will cause stats for failed segments to be incremented properly@@ -637,6 +661,9 @@ public class CheckIndex {msg(infoStream, "");} catch (Throwable t) {+ if (failFast) {+ IOUtils.reThrow(t);+ }msg(infoStream, "FAILED");String comment;comment = "fixIndex() would remove reference to this segment";@@ -678,7 +705,7 @@ public class CheckIndex {* Test field norms.* @lucene.experimental*/- public static Status.FieldNormStatus testFieldNorms(AtomicReader reader, PrintStream infoStream) {+ public static Status.FieldNormStatus testFieldNorms(AtomicReader reader, PrintStream infoStream, boolean failFast) throws IOException {final Status.FieldNormStatus status = new Status.FieldNormStatus();try {@@ -699,6 +726,9 @@ public class CheckIndex {msg(infoStream, "OK [" + status.totFields + " fields]");} catch (Throwable e) {+ if (failFast) {+ IOUtils.reThrow(e);+ }msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");status.error = e;if (infoStream != null) {@@ -825,6 +855,7 @@ public class CheckIndex {long sumTotalTermFreq = 0;long sumDocFreq = 0;+ long upto = 0;FixedBitSet visitedDocs = new FixedBitSet(maxDoc);while(true) {@@ -832,7 +863,7 @@ public class CheckIndex {if (term == null) {break;}-+assert term.isValid();// make sure terms arrive in order according to@@ -1267,15 +1298,15 @@ public class CheckIndex {* Test the term index.* @lucene.experimental*/- public static Status.TermIndexStatus testPostings(AtomicReader reader, PrintStream infoStream) {- return testPostings(reader, infoStream, false);+ public static Status.TermIndexStatus testPostings(AtomicReader reader, PrintStream infoStream) throws IOException {+ return testPostings(reader, infoStream, false, false);}/*** Test the term index.* @lucene.experimental*/- public static Status.TermIndexStatus testPostings(AtomicReader reader, PrintStream infoStream, boolean verbose) {+ public static Status.TermIndexStatus testPostings(AtomicReader reader, PrintStream infoStream, boolean verbose, boolean failFast) throws IOException {// TODO: we should go and verify term vectors match, if// crossCheckTermVectors is on...@@ -1299,6 +1330,9 @@ public class CheckIndex {checkFields(fields, null, maxDoc, fieldInfos, true, false, infoStream, verbose);}} catch (Throwable e) {+ if (failFast) {+ IOUtils.reThrow(e);+ }msg(infoStream, "ERROR: " + e);status = new Status.TermIndexStatus();status.error = e;@@ -1314,7 +1348,7 @@ public class CheckIndex {* Test stored fields.* @lucene.experimental*/- public static Status.StoredFieldStatus testStoredFields(AtomicReader reader, PrintStream infoStream) {+ public static Status.StoredFieldStatus testStoredFields(AtomicReader reader, PrintStream infoStream, boolean failFast) throws IOException {final Status.StoredFieldStatus status = new Status.StoredFieldStatus();try {@@ -1342,6 +1376,9 @@ public class CheckIndex {msg(infoStream, "OK [" + status.totFields + " total field count; avg " +NumberFormat.getInstance(Locale.ROOT).format((((float) status.totFields)/status.docCount)) + " fields per doc]");} catch (Throwable e) {+ if (failFast) {+ IOUtils.reThrow(e);+ }msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");status.error = e;if (infoStream != null) {@@ -1357,7 +1394,8 @@ public class CheckIndex {* @lucene.experimental*/public static Status.DocValuesStatus testDocValues(AtomicReader reader,- PrintStream infoStream) {+ PrintStream infoStream,+ boolean failFast) throws IOException {final Status.DocValuesStatus status = new Status.DocValuesStatus();try {if (infoStream != null) {@@ -1385,6 +1423,9 @@ public class CheckIndex {+ status.totalSortedNumericFields + " SORTED_NUMERIC; "+ status.totalSortedSetFields + " SORTED_SET]");} catch (Throwable e) {+ if (failFast) {+ IOUtils.reThrow(e);+ }msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");status.error = e;if (infoStream != null) {@@ -1624,15 +1665,15 @@ public class CheckIndex {* Test term vectors.* @lucene.experimental*/- public static Status.TermVectorStatus testTermVectors(AtomicReader reader, PrintStream infoStream) {- return testTermVectors(reader, infoStream, false, false);+ public static Status.TermVectorStatus testTermVectors(AtomicReader reader, PrintStream infoStream) throws IOException {+ return testTermVectors(reader, infoStream, false, false, false);}/*** Test term vectors.* @lucene.experimental*/- public static Status.TermVectorStatus testTermVectors(AtomicReader reader, PrintStream infoStream, boolean verbose, boolean crossCheckTermVectors) {+ public static Status.TermVectorStatus testTermVectors(AtomicReader reader, PrintStream infoStream, boolean verbose, boolean crossCheckTermVectors, boolean failFast) throws IOException {final Status.TermVectorStatus status = new Status.TermVectorStatus();final FieldInfos fieldInfos = reader.getFieldInfos();final Bits onlyDocIsDeleted = new FixedBitSet(1);@@ -1844,6 +1885,9 @@ public class CheckIndex {msg(infoStream, "OK [" + status.totVectors + " total vector count; avg " +NumberFormat.getInstance(Locale.ROOT).format(vectorAvg) + " term/freq vector fields per doc]");} catch (Throwable e) {+ if (failFast) {+ IOUtils.reThrow(e);+ }msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");status.error = e;if (infoStream != null) {diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/ByteSequenceOutputs.java b/lucene/core/src/java/org/apache/lucene/util/fst/ByteSequenceOutputs.javaindex 4bacf3e236a..38860b7c2b2 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/ByteSequenceOutputs.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/ByteSequenceOutputs.java@@ -23,6 +23,7 @@ import org.apache.lucene.store.DataInput;import org.apache.lucene.store.DataOutput;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.RamUsageEstimator;+import org.apache.lucene.util.StringHelper;/*** An FST {@link Outputs} implementation where each output@@ -80,13 +81,16 @@ public final class ByteSequenceOutputs extends Outputs<BytesRef> {if (inc == NO_OUTPUT) {// no prefix removedreturn output;- } else if (inc.length == output.length) {- // entire output removed- return NO_OUTPUT;} else {- assert inc.length < output.length: "inc.length=" + inc.length + " vs output.length=" + output.length;- assert inc.length > 0;- return new BytesRef(output.bytes, output.offset + inc.length, output.length-inc.length);+ assert StringHelper.startsWith(output, inc);+ if (inc.length == output.length) {+ // entire output removed+ return NO_OUTPUT;+ } else {+ assert inc.length < output.length: "inc.length=" + inc.length + " vs output.length=" + output.length;+ assert inc.length > 0;+ return new BytesRef(output.bytes, output.offset + inc.length, output.length-inc.length);+ }}}diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java b/lucene/core/src/java/org/apache/lucene/util/fst/FST.javaindex a87c969c98e..ba610639eb8 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/FST.java@@ -85,7 +85,10 @@ public final class FST<T> implements Accountable {// TODO: we can free up a bit if we can nuke this:final static int BIT_STOP_NODE = 1 << 3;- final static int BIT_ARC_HAS_OUTPUT = 1 << 4;++ /** This flag is set if the arc has an output. */+ public final static int BIT_ARC_HAS_OUTPUT = 1 << 4;+final static int BIT_ARC_HAS_FINAL_OUTPUT = 1 << 5;// Arcs are stored as fixed-size (per entry) array, so@@ -196,11 +199,22 @@ public final class FST<T> implements Accountable {// address (into the byte[]), or ord/address if label == END_LABELlong nextArc;- // This is non-zero if current arcs are fixed array:- long posArcsStart;- int bytesPerArc;- int arcIdx;- int numArcs;+ /** Where the first arc in the array starts; only valid if+ * bytesPerArc != 0 */+ public long posArcsStart;++ /** Non-zero if this arc is part of an array, which means all+ * arcs for the node are encoded with a fixed number of bytes so+ * that we can random access by index. We do when there are enough+ * arcs leaving one node. It wastes some bytes but gives faster+ * lookups. */+ public int bytesPerArc;++ /** Where we are in the array; only valid if bytesPerArc != 0. */+ public int arcIdx;++ /** How many arcs in the array; only valid if bytesPerArc != 0. */+ public int numArcs;/** Returns this */public Arc<T> copyFrom(Arc<T> other) {@@ -644,7 +658,8 @@ public final class FST<T> implements Accountable {}}- int readLabel(DataInput in) throws IOException {+ /** Reads one BYTE1/2/4 label from the provided {@link DataInput}. */+ public int readLabel(DataInput in) throws IOException {final int v;if (inputType == INPUT_TYPE.BYTE1) {// Unsigned byte:diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.javaindex 7038ae912af..103baeb5dbe 100644--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java@@ -36,6 +36,8 @@ import org.apache.lucene.codecs.blockterms.VariableGapTermsIndexReader;import org.apache.lucene.codecs.blockterms.VariableGapTermsIndexWriter;import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;+import org.apache.lucene.codecs.blocktreeords.OrdsBlockTreeTermsReader;+import org.apache.lucene.codecs.blocktreeords.OrdsBlockTreeTermsWriter;import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;import org.apache.lucene.codecs.memory.FSTOrdTermsReader;@@ -128,7 +130,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {}final FieldsConsumer fields;- final int t1 = random.nextInt(4);+ final int t1 = random.nextInt(5);if (t1 == 0) {boolean success = false;@@ -171,7 +173,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {postingsWriter.close();}}- } else {+ } else if (t1 == 3) {if (LuceneTestCase.VERBOSE) {System.out.println("MockRandomCodec: writing Block terms dict");@@ -241,6 +243,30 @@ public final class MockRandomPostingsFormat extends PostingsFormat {}}}+ } else if (t1 == 4) {+ // Use OrdsBlockTree terms dict+ if (LuceneTestCase.VERBOSE) {+ System.out.println("MockRandomCodec: writing OrdsBlockTree");+ }++ // TODO: would be nice to allow 1 but this is very+ // slow to write+ final int minTermsInBlock = TestUtil.nextInt(random, 2, 100);+ final int maxTermsInBlock = Math.max(2, (minTermsInBlock-1)*2 + random.nextInt(100));++ boolean success = false;+ try {+ fields = new OrdsBlockTreeTermsWriter(state, postingsWriter, minTermsInBlock, maxTermsInBlock);+ success = true;+ } finally {+ if (!success) {+ postingsWriter.close();+ }+ }++ } else {+ // BUG!+ throw new AssertionError();}return fields;@@ -275,7 +301,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {}final FieldsProducer fields;- final int t1 = random.nextInt(4);+ final int t1 = random.nextInt(5);if (t1 == 0) {boolean success = false;try {@@ -316,7 +342,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {postingsReader.close();}}- } else {+ } else if (t1 == 3) {if (LuceneTestCase.VERBOSE) {System.out.println("MockRandomCodec: reading Block terms dict");@@ -380,6 +406,29 @@ public final class MockRandomPostingsFormat extends PostingsFormat {}}}+ } else if (t1 == 4) {+ // Use OrdsBlockTree terms dict+ if (LuceneTestCase.VERBOSE) {+ System.out.println("MockRandomCodec: reading OrdsBlockTree terms dict");+ }++ boolean success = false;+ try {+ fields = new OrdsBlockTreeTermsReader(state.directory,+ state.fieldInfos,+ state.segmentInfo,+ postingsReader,+ state.context,+ state.segmentSuffix);+ success = true;+ } finally {+ if (!success) {+ postingsReader.close();+ }+ }+ } else {+ // BUG!+ throw new AssertionError();}return fields;diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.javaindex 71a216ac57e..71b2b0b3898 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java@@ -59,6 +59,11 @@ import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.LineFileDocs;import org.apache.lucene.util.RamUsageTester;import org.apache.lucene.util.TestUtil;+import org.apache.lucene.util.UnicodeUtil;+import org.apache.lucene.util.automaton.Automaton;+import org.apache.lucene.util.automaton.AutomatonTestUtil.RandomAcceptedStrings;+import org.apache.lucene.util.automaton.AutomatonTestUtil;+import org.apache.lucene.util.automaton.CompiledAutomaton;import org.junit.AfterClass;import org.junit.BeforeClass;@@ -293,17 +298,28 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}private static class FieldAndTerm {- String field;- BytesRef term;+ final String field;+ final BytesRef term;+ final long ord;- public FieldAndTerm(String field, BytesRef term) {+ public FieldAndTerm(String field, BytesRef term, long ord) {this.field = field;this.term = BytesRef.deepCopyOf(term);+ this.ord = ord;+ }+ }++ private static class SeedAndOrd {+ final long seed;+ long ord;++ public SeedAndOrd(long seed) {+ this.seed = seed;}}// Holds all postings:- private static Map<String,SortedMap<BytesRef,Long>> fields;+ private static Map<String,SortedMap<BytesRef,SeedAndOrd>> fields;private static FieldInfos fieldInfos;@@ -359,7 +375,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestnull, DocValuesType.NUMERIC, -1, null);fieldUpto++;- SortedMap<BytesRef,Long> postings = new TreeMap<>();+ SortedMap<BytesRef,SeedAndOrd> postings = new TreeMap<>();fields.put(field, postings);Set<String> seenTerms = new HashSet<>();@@ -370,7 +386,9 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestnumTerms = TestUtil.nextInt(random(), 2, 20);}- for(int termUpto=0;termUpto<numTerms;termUpto++) {+ while (postings.size() < numTerms) {+ int termUpto = postings.size();+ // Cannot contain surrogates else default Java string sort order (by UTF16 code unit) is different from Lucene:String term = TestUtil.randomSimpleString(random());if (seenTerms.contains(term)) {continue;@@ -392,7 +410,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}long termSeed = random().nextLong();- postings.put(new BytesRef(term), termSeed);+ postings.put(new BytesRef(term), new SeedAndOrd(termSeed));// NOTE: sort of silly: we enum all the docs just to// get the maxDoc@@ -404,6 +422,12 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}maxDoc = Math.max(lastDoc, maxDoc);}++ // assign ords+ long ord = 0;+ for(SeedAndOrd ent : postings.values()) {+ ent.ord = ord++;+ }}fieldInfos = new FieldInfos(fieldInfoArray);@@ -420,10 +444,11 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}allTerms = new ArrayList<>();- for(Map.Entry<String,SortedMap<BytesRef,Long>> fieldEnt : fields.entrySet()) {+ for(Map.Entry<String,SortedMap<BytesRef,SeedAndOrd>> fieldEnt : fields.entrySet()) {String field = fieldEnt.getKey();- for(Map.Entry<BytesRef,Long> termEnt : fieldEnt.getValue().entrySet()) {- allTerms.add(new FieldAndTerm(field, termEnt.getKey()));+ long ord = 0;+ for(Map.Entry<BytesRef,SeedAndOrd> termEnt : fieldEnt.getValue().entrySet()) {+ allTerms.add(new FieldAndTerm(field, termEnt.getKey(), ord++));}}@@ -441,12 +466,12 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}private static class SeedFields extends Fields {- final Map<String,SortedMap<BytesRef,Long>> fields;+ final Map<String,SortedMap<BytesRef,SeedAndOrd>> fields;final FieldInfos fieldInfos;final IndexOptions maxAllowed;final boolean allowPayloads;- public SeedFields(Map<String,SortedMap<BytesRef,Long>> fields, FieldInfos fieldInfos, IndexOptions maxAllowed, boolean allowPayloads) {+ public SeedFields(Map<String,SortedMap<BytesRef,SeedAndOrd>> fields, FieldInfos fieldInfos, IndexOptions maxAllowed, boolean allowPayloads) {this.fields = fields;this.fieldInfos = fieldInfos;this.maxAllowed = maxAllowed;@@ -460,7 +485,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest@Overridepublic Terms terms(String field) {- SortedMap<BytesRef,Long> terms = fields.get(field);+ SortedMap<BytesRef,SeedAndOrd> terms = fields.get(field);if (terms == null) {return null;} else {@@ -475,12 +500,12 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}private static class SeedTerms extends Terms {- final SortedMap<BytesRef,Long> terms;+ final SortedMap<BytesRef,SeedAndOrd> terms;final FieldInfo fieldInfo;final IndexOptions maxAllowed;final boolean allowPayloads;- public SeedTerms(SortedMap<BytesRef,Long> terms, FieldInfo fieldInfo, IndexOptions maxAllowed, boolean allowPayloads) {+ public SeedTerms(SortedMap<BytesRef,SeedAndOrd> terms, FieldInfo fieldInfo, IndexOptions maxAllowed, boolean allowPayloads) {this.terms = terms;this.fieldInfo = fieldInfo;this.maxAllowed = maxAllowed;@@ -545,15 +570,15 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}private static class SeedTermsEnum extends TermsEnum {- final SortedMap<BytesRef,Long> terms;+ final SortedMap<BytesRef,SeedAndOrd> terms;final IndexOptions maxAllowed;final boolean allowPayloads;- private Iterator<Map.Entry<BytesRef,Long>> iterator;+ private Iterator<Map.Entry<BytesRef,SeedAndOrd>> iterator;- private Map.Entry<BytesRef,Long> current;+ private Map.Entry<BytesRef,SeedAndOrd> current;- public SeedTermsEnum(SortedMap<BytesRef,Long> terms, IndexOptions maxAllowed, boolean allowPayloads) {+ public SeedTermsEnum(SortedMap<BytesRef,SeedAndOrd> terms, IndexOptions maxAllowed, boolean allowPayloads) {this.terms = terms;this.maxAllowed = maxAllowed;this.allowPayloads = allowPayloads;@@ -565,7 +590,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest@Overridepublic SeekStatus seekCeil(BytesRef text) {- SortedMap<BytesRef,Long> tailMap = terms.tailMap(text);+ SortedMap<BytesRef,SeedAndOrd> tailMap = terms.tailMap(text);if (tailMap.isEmpty()) {return SeekStatus.END;} else {@@ -600,7 +625,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest@Overridepublic long ord() {- throw new UnsupportedOperationException();+ return current.getValue().ord;}@Override@@ -621,7 +646,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestif ((flags & DocsEnum.FLAG_FREQS) != 0 && maxAllowed.compareTo(IndexOptions.DOCS_AND_FREQS) < 0) {return null;}- return getSeedPostings(current.getKey().utf8ToString(), current.getValue(), false, maxAllowed, allowPayloads);+ return getSeedPostings(current.getKey().utf8ToString(), current.getValue().seed, false, maxAllowed, allowPayloads);}@Override@@ -638,7 +663,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestif ((flags & DocsAndPositionsEnum.FLAG_PAYLOADS) != 0 && allowPayloads == false) {return null;}- return getSeedPostings(current.getKey().utf8ToString(), current.getValue(), false, maxAllowed, allowPayloads);+ return getSeedPostings(current.getKey().utf8ToString(), current.getValue().seed, false, maxAllowed, allowPayloads);}}@@ -766,7 +791,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest// NOTE: can be empty list if we are using liveDocs:SeedPostings expected = getSeedPostings(term.utf8ToString(),- fields.get(field).get(term),+ fields.get(field).get(term).seed,useLiveDocs,maxIndexOptions,true);@@ -1104,12 +1129,16 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest// Test random terms/fields:List<TermState> termStates = new ArrayList<>();List<FieldAndTerm> termStateTerms = new ArrayList<>();++ boolean supportsOrds = true;Collections.shuffle(allTerms, random());int upto = 0;while (upto < allTerms.size()) {boolean useTermState = termStates.size() != 0 && random().nextInt(5) == 1;+ boolean useTermOrd = supportsOrds && useTermState == false && random().nextInt(5) == 1;+FieldAndTerm fieldAndTerm;TermsEnum termsEnum;@@ -1119,7 +1148,11 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest// Seek by random field+term:fieldAndTerm = allTerms.get(upto++);if (VERBOSE) {- System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() );+ if (useTermOrd) {+ System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() + " using ord=" + fieldAndTerm.ord);+ } else {+ System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() );+ }}} else {// Seek by previous saved TermState@@ -1136,11 +1169,38 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTesttermsEnum = terms.iterator(null);if (!useTermState) {- assertTrue(termsEnum.seekExact(fieldAndTerm.term));+ if (useTermOrd) {+ // Try seek by ord sometimes:+ try {+ termsEnum.seekExact(fieldAndTerm.ord);+ } catch (UnsupportedOperationException uoe) {+ supportsOrds = false;+ assertTrue(termsEnum.seekExact(fieldAndTerm.term));+ }+ } else {+ assertTrue(termsEnum.seekExact(fieldAndTerm.term));+ }} else {termsEnum.seekExact(fieldAndTerm.term, termState);}+ long termOrd;+ if (supportsOrds) {+ try {+ termOrd = termsEnum.ord();+ } catch (UnsupportedOperationException uoe) {+ supportsOrds = false;+ termOrd = -1;+ }+ } else {+ termOrd = -1;+ }++ if (termOrd != -1) {+ // PostingsFormat supports ords+ assertEquals(fieldAndTerm.ord, termsEnum.ord());+ }+boolean savedTermState = false;if (options.contains(Option.TERM_STATE) && !useTermState && random().nextInt(5) == 1) {@@ -1185,6 +1245,71 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestalwaysTestMax);}}++ // Test Terms.intersect:+ for(String field : fields.keySet()) {+ while (true) {+ Automaton a = AutomatonTestUtil.randomAutomaton(random());+ CompiledAutomaton ca = new CompiledAutomaton(a);+ if (ca.type != CompiledAutomaton.AUTOMATON_TYPE.NORMAL) {+ // Keep retrying until we get an A that will really "use" the PF's intersect code:+ continue;+ }+ // System.out.println("A:\n" + a.toDot());++ BytesRef startTerm = null;+ if (random().nextBoolean()) {+ RandomAcceptedStrings ras = new RandomAcceptedStrings(a);+ for (int iter=0;iter<100;iter++) {+ int[] codePoints = ras.getRandomAcceptedString(random());+ if (codePoints.length == 0) {+ continue;+ }+ startTerm = new BytesRef(UnicodeUtil.newString(codePoints, 0, codePoints.length));+ break;+ }+ // Don't allow empty string startTerm:+ if (startTerm == null) {+ continue;+ }+ }+ TermsEnum intersected = fieldsSource.terms(field).intersect(ca, startTerm);++ Set<BytesRef> intersectedTerms = new HashSet<BytesRef>();+ BytesRef term;+ while ((term = intersected.next()) != null) {+ if (startTerm != null) {+ // NOTE: not <=+ assertTrue(startTerm.compareTo(term) < 0);+ }+ intersectedTerms.add(BytesRef.deepCopyOf(term));+ verifyEnum(threadState,+ field,+ term,+ intersected,+ maxTestOptions,+ maxIndexOptions,+ options,+ alwaysTestMax);+ }++ if (ca.runAutomaton == null) {+ assertTrue(intersectedTerms.isEmpty());+ } else {+ for(BytesRef term2 : fields.get(field).keySet()) {+ boolean expected;+ if (startTerm != null && startTerm.compareTo(term2) >= 0) {+ expected = false;+ } else {+ expected = ca.runAutomaton.run(term2.bytes, term2.offset, term2.length);+ }+ assertEquals("term=" + term2, expected, intersectedTerms.contains(term2));+ }+ }++ break;+ }+ }}private void testFields(Fields fields) throws Exception {@@ -1284,7 +1409,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTest}}- public void testEmptyField() throws Exception {+ public void testJustEmptyField() throws Exception {Directory dir = newDirectory();IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, null);iwc.setCodec(getCodec());@@ -1449,6 +1574,7 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestDocsEnum docs = null;while(termsEnum.next() != null) {BytesRef term = termsEnum.term();+if (random().nextBoolean()) {docs = termsEnum.docs(null, docs, DocsEnum.FLAG_FREQS);} else if (docs instanceof DocsAndPositionsEnum) {@@ -1584,11 +1710,24 @@ public abstract class BasePostingsFormatTestCase extends BaseIndexFileFormatTestTermsEnum termsEnum = terms.iterator(null);long termCount = 0;+ boolean supportsOrds = true;while(termsEnum.next() != null) {BytesRef term = termsEnum.term();- termCount++;assertEquals(termFreqs.get(term.utf8ToString()).docFreq, termsEnum.docFreq());assertEquals(termFreqs.get(term.utf8ToString()).totalTermFreq, termsEnum.totalTermFreq());+ if (supportsOrds) {+ long ord;+ try {+ ord = termsEnum.ord();+ } catch (UnsupportedOperationException uoe) {+ supportsOrds = false;+ ord = -1;+ }+ if (ord != -1) {+ assertEquals(termCount, ord);+ }+ }+ termCount++;}assertEquals(termFreqs.size(), termCount);diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java b/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.javaindex 941767b2ac3..f49c3fc0e5c 100644--- a/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java+++ b/lucene/test-framework/src/java/org/apache/lucene/store/MockDirectoryWrapper.java@@ -692,7 +692,7 @@ public class MockDirectoryWrapper extends BaseDirectoryWrapper {if (LuceneTestCase.VERBOSE) {System.out.println("\nNOTE: MockDirectoryWrapper: now run CheckIndex");}- TestUtil.checkIndex(this, getCrossCheckTermVectorsOnClose());+ TestUtil.checkIndex(this, getCrossCheckTermVectorsOnClose(), true);// TODO: factor this out / share w/ TestIW.assertNoUnreferencedFilesif (assertNoUnreferencedFilesOnClose) {diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.javaindex 16e9497bfd9..1bd04515e8b 100644--- a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java+++ b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java@@ -28,7 +28,6 @@ import java.io.PrintStream;import java.math.BigDecimal;import java.math.BigInteger;import java.nio.CharBuffer;-import java.util.ArrayList;import java.util.Arrays;import java.util.Enumeration;import java.util.HashMap;@@ -194,9 +193,16 @@ public final class TestUtil {}public static CheckIndex.Status checkIndex(Directory dir, boolean crossCheckTermVectors) throws IOException {+ return checkIndex(dir, crossCheckTermVectors, false);+ }++ /** If failFast is true, then throw the first exception when index corruption is hit, instead of moving on to other fields/segments to+ * look for any other corruption. */+ public static CheckIndex.Status checkIndex(Directory dir, boolean crossCheckTermVectors, boolean failFast) throws IOException {ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);CheckIndex checker = new CheckIndex(dir);checker.setCrossCheckTermVectors(crossCheckTermVectors);+ checker.setFailFast(failFast);checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8), false);CheckIndex.Status indexStatus = checker.checkIndex(null);if (indexStatus == null || indexStatus.clean == false) {@@ -224,24 +230,14 @@ public final class TestUtil {PrintStream infoStream = new PrintStream(bos, false, IOUtils.UTF_8);reader.checkIntegrity();- FieldNormStatus fieldNormStatus = CheckIndex.testFieldNorms(reader, infoStream);- TermIndexStatus termIndexStatus = CheckIndex.testPostings(reader, infoStream);- StoredFieldStatus storedFieldStatus = CheckIndex.testStoredFields(reader, infoStream);- TermVectorStatus termVectorStatus = CheckIndex.testTermVectors(reader, infoStream, false, crossCheckTermVectors);- DocValuesStatus docValuesStatus = CheckIndex.testDocValues(reader, infoStream);+ FieldNormStatus fieldNormStatus = CheckIndex.testFieldNorms(reader, infoStream, true);+ TermIndexStatus termIndexStatus = CheckIndex.testPostings(reader, infoStream, false, true);+ StoredFieldStatus storedFieldStatus = CheckIndex.testStoredFields(reader, infoStream, true);+ TermVectorStatus termVectorStatus = CheckIndex.testTermVectors(reader, infoStream, false, crossCheckTermVectors, true);+ DocValuesStatus docValuesStatus = CheckIndex.testDocValues(reader, infoStream, true);- if (fieldNormStatus.error != null ||- termIndexStatus.error != null ||- storedFieldStatus.error != null ||- termVectorStatus.error != null ||- docValuesStatus.error != null) {- System.out.println("CheckReader failed");+ if (LuceneTestCase.INFOSTREAM) {System.out.println(bos.toString(IOUtils.UTF_8));- throw new RuntimeException("CheckReader failed");- } else {- if (LuceneTestCase.INFOSTREAM) {- System.out.println(bos.toString(IOUtils.UTF_8));- }}}