Skip to content

Apache Lucene open-source search software

remove 'temp' impersonators

Han Jiang1b4c3f688cf4
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsReader.java
deleted file mode 100644
index 3118142c7b8..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsReader.java
+++ /dev/null
@@ -1,704 +0,0 @@
-package org.apache.lucene.codecs.sep;
-
-/*
- * 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.CodecUtil;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-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.TermState;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.DataInput;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-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.IOUtils;
-
-/** Concrete class that reads the current doc/freq/skip
- * postings format.
- *
- * @lucene.experimental
- */
-
-// TODO: -- should we switch "hasProx" higher up? and
-// create two separate docs readers, one that also reads
-// prox and one that doesn't?
-
-public class TempSepPostingsReader extends TempPostingsReaderBase {
-
- final IntIndexInput freqIn;
- final IntIndexInput docIn;
- final IntIndexInput posIn;
- final IndexInput payloadIn;
- final IndexInput skipIn;
-
- int skipInterval;
- int maxSkipLevels;
- int skipMinimum;
-
- public TempSepPostingsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo segmentInfo, IOContext context, IntStreamFactory intFactory, String segmentSuffix) throws IOException {
- boolean success = false;
- try {
-
- final String docFileName = IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempSepPostingsWriter.DOC_EXTENSION);
- docIn = intFactory.openInput(dir, docFileName, context);
-
- skipIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempSepPostingsWriter.SKIP_EXTENSION), context);
-
- if (fieldInfos.hasFreq()) {
- freqIn = intFactory.openInput(dir, IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempSepPostingsWriter.FREQ_EXTENSION), context);
- } else {
- freqIn = null;
- }
- if (fieldInfos.hasProx()) {
- posIn = intFactory.openInput(dir, IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempSepPostingsWriter.POS_EXTENSION), context);
- payloadIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempSepPostingsWriter.PAYLOAD_EXTENSION), context);
- } else {
- posIn = null;
- payloadIn = null;
- }
- success = true;
- } finally {
- if (!success) {
- close();
- }
- }
- }
-
- @Override
- public void init(IndexInput termsIn) throws IOException {
- // Make sure we are talking to the matching past writer
- CodecUtil.checkHeader(termsIn, TempSepPostingsWriter.CODEC,
- TempSepPostingsWriter.VERSION_START, TempSepPostingsWriter.VERSION_START);
- skipInterval = termsIn.readInt();
- maxSkipLevels = termsIn.readInt();
- skipMinimum = termsIn.readInt();
- }
-
- @Override
- public void close() throws IOException {
- IOUtils.close(freqIn, docIn, skipIn, posIn, payloadIn);
- }
-
- private static final class SepTermState extends BlockTermState {
- // We store only the seek point to the docs file because
- // the rest of the info (freqIndex, posIndex, etc.) is
- // stored in the docs file:
- IntIndexInput.Index docIndex;
- IntIndexInput.Index posIndex;
- IntIndexInput.Index freqIndex;
- long payloadFP;
- long skipFP;
-
- @Override
- public SepTermState clone() {
- SepTermState other = new SepTermState();
- other.copyFrom(this);
- return other;
- }
-
- @Override
- public void copyFrom(TermState _other) {
- super.copyFrom(_other);
- SepTermState other = (SepTermState) _other;
- if (docIndex == null) {
- docIndex = other.docIndex.clone();
- } else {
- docIndex.copyFrom(other.docIndex);
- }
- if (other.freqIndex != null) {
- if (freqIndex == null) {
- freqIndex = other.freqIndex.clone();
- } else {
- freqIndex.copyFrom(other.freqIndex);
- }
- } else {
- freqIndex = null;
- }
- if (other.posIndex != null) {
- if (posIndex == null) {
- posIndex = other.posIndex.clone();
- } else {
- posIndex.copyFrom(other.posIndex);
- }
- } else {
- posIndex = null;
- }
- payloadFP = other.payloadFP;
- skipFP = other.skipFP;
- }
-
- @Override
- public String toString() {
- return super.toString() + " docIndex=" + docIndex + " freqIndex=" + freqIndex + " posIndex=" + posIndex + " payloadFP=" + payloadFP + " skipFP=" + skipFP;
- }
- }
-
- @Override
- public BlockTermState newTermState() throws IOException {
- final SepTermState state = new SepTermState();
- state.docIndex = docIn.index();
- if (freqIn != null) {
- state.freqIndex = freqIn.index();
- }
- if (posIn != null) {
- state.posIndex = posIn.index();
- }
- return state;
- }
-
- @Override
- public void decodeTerm(long[] empty, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute)
- throws IOException {
- final SepTermState termState = (SepTermState) _termState;
- termState.docIndex.read(in, absolute);
- if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- termState.freqIndex.read(in, absolute);
- if (fieldInfo.getIndexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
- //System.out.println(" freqIndex=" + termState.freqIndex);
- termState.posIndex.read(in, absolute);
- //System.out.println(" posIndex=" + termState.posIndex);
- if (fieldInfo.hasPayloads()) {
- if (absolute) {
- termState.payloadFP = in.readVLong();
- } else {
- termState.payloadFP += in.readVLong();
- }
- //System.out.println(" payloadFP=" + termState.payloadFP);
- }
- }
- }
-
- if (termState.docFreq >= skipMinimum) {
- //System.out.println(" readSkip @ " + in.getPosition());
- if (absolute) {
- termState.skipFP = in.readVLong();
- } else {
- termState.skipFP += in.readVLong();
- }
- //System.out.println(" skipFP=" + termState.skipFP);
- } else if (absolute) {
- termState.skipFP = 0;
- }
- }
-
- @Override
- public DocsEnum docs(FieldInfo fieldInfo, BlockTermState _termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
- final SepTermState termState = (SepTermState) _termState;
- SepDocsEnum docsEnum;
- if (reuse == null || !(reuse instanceof SepDocsEnum)) {
- docsEnum = new SepDocsEnum();
- } else {
- docsEnum = (SepDocsEnum) reuse;
- if (docsEnum.startDocIn != docIn) {
- // If you are using ParellelReader, and pass in a
- // reused DocsAndPositionsEnum, it could have come
- // from another reader also using sep codec
- docsEnum = new SepDocsEnum();
- }
- }
-
- return docsEnum.init(fieldInfo, termState, liveDocs);
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState _termState, Bits liveDocs,
- DocsAndPositionsEnum reuse, int flags)
- throws IOException {
-
- assert fieldInfo.getIndexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
- final SepTermState termState = (SepTermState) _termState;
- SepDocsAndPositionsEnum postingsEnum;
- if (reuse == null || !(reuse instanceof SepDocsAndPositionsEnum)) {
- postingsEnum = new SepDocsAndPositionsEnum();
- } else {
- postingsEnum = (SepDocsAndPositionsEnum) reuse;
- if (postingsEnum.startDocIn != docIn) {
- // If you are using ParellelReader, and pass in a
- // reused DocsAndPositionsEnum, it could have come
- // from another reader also using sep codec
- postingsEnum = new SepDocsAndPositionsEnum();
- }
- }
-
- return postingsEnum.init(fieldInfo, termState, liveDocs);
- }
-
- class SepDocsEnum extends DocsEnum {
- int docFreq;
- int doc = -1;
- int accum;
- int count;
- int freq;
- long freqStart;
-
- // TODO: -- should we do omitTF with 2 different enum classes?
- private boolean omitTF;
- private IndexOptions indexOptions;
- private boolean storePayloads;
- private Bits liveDocs;
- private final IntIndexInput.Reader docReader;
- private final IntIndexInput.Reader freqReader;
- private long skipFP;
-
- private final IntIndexInput.Index docIndex;
- private final IntIndexInput.Index freqIndex;
- private final IntIndexInput.Index posIndex;
- private final IntIndexInput startDocIn;
-
- // TODO: -- should we do hasProx with 2 different enum classes?
-
- boolean skipped;
- SepSkipListReader skipper;
-
- SepDocsEnum() throws IOException {
- startDocIn = docIn;
- docReader = docIn.reader();
- docIndex = docIn.index();
- if (freqIn != null) {
- freqReader = freqIn.reader();
- freqIndex = freqIn.index();
- } else {
- freqReader = null;
- freqIndex = null;
- }
- if (posIn != null) {
- posIndex = posIn.index(); // only init this so skipper can read it
- } else {
- posIndex = null;
- }
- }
-
- SepDocsEnum init(FieldInfo fieldInfo, SepTermState termState, Bits liveDocs) throws IOException {
- this.liveDocs = liveDocs;
- this.indexOptions = fieldInfo.getIndexOptions();
- omitTF = indexOptions == IndexOptions.DOCS_ONLY;
- storePayloads = fieldInfo.hasPayloads();
-
- // TODO: can't we only do this if consumer
- // skipped consuming the previous docs?
- docIndex.copyFrom(termState.docIndex);
- docIndex.seek(docReader);
-
- if (!omitTF) {
- freqIndex.copyFrom(termState.freqIndex);
- freqIndex.seek(freqReader);
- }
-
- docFreq = termState.docFreq;
- // NOTE: unused if docFreq < skipMinimum:
- skipFP = termState.skipFP;
- count = 0;
- doc = -1;
- accum = 0;
- freq = 1;
- skipped = false;
-
- return this;
- }
-
- @Override
- public int nextDoc() throws IOException {
-
- while(true) {
- if (count == docFreq) {
- return doc = NO_MORE_DOCS;
- }
-
- count++;
-
- // Decode next doc
- //System.out.println("decode docDelta:");
- accum += docReader.next();
-
- if (!omitTF) {
- //System.out.println("decode freq:");
- freq = freqReader.next();
- }
-
- if (liveDocs == null || liveDocs.get(accum)) {
- break;
- }
- }
- return (doc = accum);
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- @Override
- public int advance(int target) throws IOException {
-
- if ((target - skipInterval) >= doc && docFreq >= skipMinimum) {
-
- // There are enough docs in the posting to have
- // skip data, and its not too close
-
- if (skipper == null) {
- // This DocsEnum has never done any skipping
- skipper = new SepSkipListReader(skipIn.clone(),
- freqIn,
- docIn,
- posIn,
- maxSkipLevels, skipInterval);
-
- }
-
- if (!skipped) {
- // We haven't yet skipped for this posting
- skipper.init(skipFP,
- docIndex,
- freqIndex,
- posIndex,
- 0,
- docFreq,
- storePayloads);
- skipper.setIndexOptions(indexOptions);
-
- skipped = true;
- }
-
- final int newCount = skipper.skipTo(target);
-
- if (newCount > count) {
-
- // Skipper did move
- if (!omitTF) {
- skipper.getFreqIndex().seek(freqReader);
- }
- skipper.getDocIndex().seek(docReader);
- count = newCount;
- doc = accum = skipper.getDoc();
- }
- }
-
- // Now, linear scan for the rest:
- do {
- if (nextDoc() == NO_MORE_DOCS) {
- return NO_MORE_DOCS;
- }
- } while (target > doc);
-
- return doc;
- }
-
- @Override
- public long cost() {
- return docFreq;
- }
- }
-
- class SepDocsAndPositionsEnum extends DocsAndPositionsEnum {
- int docFreq;
- int doc = -1;
- int accum;
- int count;
- int freq;
- long freqStart;
-
- private boolean storePayloads;
- private Bits liveDocs;
- private final IntIndexInput.Reader docReader;
- private final IntIndexInput.Reader freqReader;
- private final IntIndexInput.Reader posReader;
- private final IndexInput payloadIn;
- private long skipFP;
-
- private final IntIndexInput.Index docIndex;
- private final IntIndexInput.Index freqIndex;
- private final IntIndexInput.Index posIndex;
- private final IntIndexInput startDocIn;
-
- private long payloadFP;
-
- private int pendingPosCount;
- private int position;
- private int payloadLength;
- private long pendingPayloadBytes;
-
- private boolean skipped;
- private SepSkipListReader skipper;
- private boolean payloadPending;
- private boolean posSeekPending;
-
- SepDocsAndPositionsEnum() throws IOException {
- startDocIn = docIn;
- docReader = docIn.reader();
- docIndex = docIn.index();
- freqReader = freqIn.reader();
- freqIndex = freqIn.index();
- posReader = posIn.reader();
- posIndex = posIn.index();
- payloadIn = TempSepPostingsReader.this.payloadIn.clone();
- }
-
- SepDocsAndPositionsEnum init(FieldInfo fieldInfo, SepTermState termState, Bits liveDocs) throws IOException {
- this.liveDocs = liveDocs;
- storePayloads = fieldInfo.hasPayloads();
- //System.out.println("Sep D&P init");
-
- // TODO: can't we only do this if consumer
- // skipped consuming the previous docs?
- docIndex.copyFrom(termState.docIndex);
- docIndex.seek(docReader);
- //System.out.println(" docIndex=" + docIndex);
-
- freqIndex.copyFrom(termState.freqIndex);
- freqIndex.seek(freqReader);
- //System.out.println(" freqIndex=" + freqIndex);
-
- posIndex.copyFrom(termState.posIndex);
- //System.out.println(" posIndex=" + posIndex);
- posSeekPending = true;
- payloadPending = false;
-
- payloadFP = termState.payloadFP;
- skipFP = termState.skipFP;
- //System.out.println(" skipFP=" + skipFP);
-
- docFreq = termState.docFreq;
- count = 0;
- doc = -1;
- accum = 0;
- pendingPosCount = 0;
- pendingPayloadBytes = 0;
- skipped = false;
-
- return this;
- }
-
- @Override
- public int nextDoc() throws IOException {
-
- while(true) {
- if (count == docFreq) {
- return doc = NO_MORE_DOCS;
- }
-
- count++;
-
- // TODO: maybe we should do the 1-bit trick for encoding
- // freq=1 case?
-
- // Decode next doc
- //System.out.println(" sep d&p read doc");
- accum += docReader.next();
-
- //System.out.println(" sep d&p read freq");
- freq = freqReader.next();
-
- pendingPosCount += freq;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- break;
- }
- }
-
- position = 0;
- return (doc = accum);
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- @Override
- public int advance(int target) throws IOException {
- //System.out.println("SepD&P advance target=" + target + " vs current=" + doc + " this=" + this);
-
- if ((target - skipInterval) >= doc && docFreq >= skipMinimum) {
-
- // There are enough docs in the posting to have
- // skip data, and its not too close
-
- if (skipper == null) {
- //System.out.println(" create skipper");
- // This DocsEnum has never done any skipping
- skipper = new SepSkipListReader(skipIn.clone(),
- freqIn,
- docIn,
- posIn,
- maxSkipLevels, skipInterval);
- }
-
- if (!skipped) {
- //System.out.println(" init skip data skipFP=" + skipFP);
- // We haven't yet skipped for this posting
- skipper.init(skipFP,
- docIndex,
- freqIndex,
- posIndex,
- payloadFP,
- docFreq,
- storePayloads);
- skipper.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
- skipped = true;
- }
- final int newCount = skipper.skipTo(target);
- //System.out.println(" skip newCount=" + newCount + " vs " + count);
-
- if (newCount > count) {
-
- // Skipper did move
- skipper.getFreqIndex().seek(freqReader);
- skipper.getDocIndex().seek(docReader);
- //System.out.println(" doc seek'd to " + skipper.getDocIndex());
- // NOTE: don't seek pos here; do it lazily
- // instead. Eg a PhraseQuery may skip to many
- // docs before finally asking for positions...
- posIndex.copyFrom(skipper.getPosIndex());
- posSeekPending = true;
- count = newCount;
- doc = accum = skipper.getDoc();
- //System.out.println(" moved to doc=" + doc);
- //payloadIn.seek(skipper.getPayloadPointer());
- payloadFP = skipper.getPayloadPointer();
- pendingPosCount = 0;
- pendingPayloadBytes = 0;
- payloadPending = false;
- payloadLength = skipper.getPayloadLength();
- //System.out.println(" move payloadLen=" + payloadLength);
- }
- }
-
- // Now, linear scan for the rest:
- do {
- if (nextDoc() == NO_MORE_DOCS) {
- //System.out.println(" advance nextDoc=END");
- return NO_MORE_DOCS;
- }
- //System.out.println(" advance nextDoc=" + doc);
- } while (target > doc);
-
- //System.out.println(" return doc=" + doc);
- return doc;
- }
-
- @Override
- public int nextPosition() throws IOException {
- if (posSeekPending) {
- posIndex.seek(posReader);
- payloadIn.seek(payloadFP);
- posSeekPending = false;
- }
-
- // scan over any docs that were iterated without their
- // positions
- while (pendingPosCount > freq) {
- final int code = posReader.next();
- if (storePayloads && (code & 1) != 0) {
- // Payload length has changed
- payloadLength = posReader.next();
- assert payloadLength >= 0;
- }
- pendingPosCount--;
- position = 0;
- pendingPayloadBytes += payloadLength;
- }
-
- final int code = posReader.next();
-
- if (storePayloads) {
- if ((code & 1) != 0) {
- // Payload length has changed
- payloadLength = posReader.next();
- assert payloadLength >= 0;
- }
- position += code >>> 1;
- pendingPayloadBytes += payloadLength;
- payloadPending = payloadLength > 0;
- } else {
- position += code;
- }
-
- pendingPosCount--;
- assert pendingPosCount >= 0;
- return position;
- }
-
- @Override
- public int startOffset() {
- return -1;
- }
-
- @Override
- public int endOffset() {
- return -1;
- }
-
- private BytesRef payload;
-
- @Override
- public BytesRef getPayload() throws IOException {
- if (!payloadPending) {
- return null;
- }
-
- if (pendingPayloadBytes == 0) {
- return payload;
- }
-
- assert pendingPayloadBytes >= payloadLength;
-
- if (pendingPayloadBytes > payloadLength) {
- payloadIn.seek(payloadIn.getFilePointer() + (pendingPayloadBytes - payloadLength));
- }
-
- if (payload == null) {
- payload = new BytesRef();
- payload.bytes = new byte[payloadLength];
- } else if (payload.bytes.length < payloadLength) {
- payload.grow(payloadLength);
- }
-
- payloadIn.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
- pendingPayloadBytes = 0;
- return payload;
- }
-
- @Override
- public long cost() {
- return docFreq;
- }
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsWriter.java
deleted file mode 100644
index f7888331df7..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/sep/TempSepPostingsWriter.java
+++ /dev/null
@@ -1,375 +0,0 @@
-package org.apache.lucene.codecs.sep;
-
-/*
- * 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.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.codecs.sep.*;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.store.RAMOutputStream;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-/** Writes frq to .frq, docs to .doc, pos to .pos, payloads
- * to .pyl, skip data to .skp
- *
- * @lucene.experimental */
-public final class TempSepPostingsWriter extends TempPostingsWriterBase {
- final static String CODEC = "TempSepPostingsWriter";
-
- final static String DOC_EXTENSION = "doc";
- final static String SKIP_EXTENSION = "skp";
- final static String FREQ_EXTENSION = "frq";
- final static String POS_EXTENSION = "pos";
- final static String PAYLOAD_EXTENSION = "pyl";
-
- // Increment version to change it:
- final static int VERSION_START = 0;
- final static int VERSION_CURRENT = VERSION_START;
-
- IntIndexOutput freqOut;
- IntIndexOutput.Index freqIndex;
-
- IntIndexOutput posOut;
- IntIndexOutput.Index posIndex;
-
- IntIndexOutput docOut;
- IntIndexOutput.Index docIndex;
-
- IndexOutput payloadOut;
-
- IndexOutput skipOut;
-
- final SepSkipListWriter skipListWriter;
- /** Expert: The fraction of TermDocs entries stored in skip tables,
- * used to accelerate {@link DocsEnum#advance(int)}. Larger values result in
- * smaller indexes, greater acceleration, but fewer accelerable cases, while
- * smaller values result in bigger indexes, less acceleration and more
- * accelerable cases. More detailed experiments would be useful here. */
- final int skipInterval;
- static final int DEFAULT_SKIP_INTERVAL = 16;
-
- /**
- * Expert: minimum docFreq to write any skip data at all
- */
- final int skipMinimum;
-
- /** Expert: The maximum number of skip levels. Smaller values result in
- * slightly smaller indexes, but slower skipping in big posting lists.
- */
- final int maxSkipLevels = 10;
-
- final int totalNumDocs;
-
- boolean storePayloads;
- IndexOptions indexOptions;
-
- FieldInfo fieldInfo;
-
- int lastPayloadLength;
- int lastPosition;
- long payloadStart;
- int lastDocID;
- int df;
-
- SepTermState lastState;
- long lastPayloadFP;
- long lastSkipFP;
-
- public TempSepPostingsWriter(SegmentWriteState state, IntStreamFactory factory) throws IOException {
- this(state, factory, DEFAULT_SKIP_INTERVAL);
- }
-
- public TempSepPostingsWriter(SegmentWriteState state, IntStreamFactory factory, int skipInterval) throws IOException {
- freqOut = null;
- freqIndex = null;
- posOut = null;
- posIndex = null;
- payloadOut = null;
- boolean success = false;
- try {
- this.skipInterval = skipInterval;
- this.skipMinimum = skipInterval; /* set to the same for now */
- final String docFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, DOC_EXTENSION);
-
- docOut = factory.createOutput(state.directory, docFileName, state.context);
- docIndex = docOut.index();
-
- if (state.fieldInfos.hasFreq()) {
- final String frqFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, FREQ_EXTENSION);
- freqOut = factory.createOutput(state.directory, frqFileName, state.context);
- freqIndex = freqOut.index();
- }
-
- if (state.fieldInfos.hasProx()) {
- final String posFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, POS_EXTENSION);
- posOut = factory.createOutput(state.directory, posFileName, state.context);
- posIndex = posOut.index();
-
- // TODO: -- only if at least one field stores payloads?
- final String payloadFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, PAYLOAD_EXTENSION);
- payloadOut = state.directory.createOutput(payloadFileName, state.context);
- }
-
- final String skipFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, SKIP_EXTENSION);
- skipOut = state.directory.createOutput(skipFileName, state.context);
-
- totalNumDocs = state.segmentInfo.getDocCount();
-
- skipListWriter = new SepSkipListWriter(skipInterval,
- maxSkipLevels,
- totalNumDocs,
- freqOut, docOut,
- posOut, payloadOut);
-
- success = true;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docOut, skipOut, freqOut, posOut, payloadOut);
- }
- }
- }
-
- @Override
- public void init(IndexOutput termsOut) throws IOException {
- CodecUtil.writeHeader(termsOut, CODEC, VERSION_CURRENT);
- // TODO: -- just ask skipper to "start" here
- termsOut.writeInt(skipInterval); // write skipInterval
- termsOut.writeInt(maxSkipLevels); // write maxSkipLevels
- termsOut.writeInt(skipMinimum); // write skipMinimum
- }
-
- @Override
- public SepTermState newTermState() {
- return new SepTermState();
- }
-
- @Override
- public void startTerm() throws IOException {
- docIndex.mark();
- //System.out.println("SEPW: startTerm docIndex=" + docIndex);
-
- if (indexOptions != IndexOptions.DOCS_ONLY) {
- freqIndex.mark();
- }
-
- if (indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
- posIndex.mark();
- payloadStart = payloadOut.getFilePointer();
- lastPayloadLength = -1;
- }
-
- skipListWriter.resetSkip(docIndex, freqIndex, posIndex);
- }
-
- // Currently, this instance is re-used across fields, so
- // our parent calls setField whenever the field changes
- @Override
- public int setField(FieldInfo fieldInfo) {
- this.fieldInfo = fieldInfo;
- this.indexOptions = fieldInfo.getIndexOptions();
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) {
- throw new UnsupportedOperationException("this codec cannot index offsets");
- }
- skipListWriter.setIndexOptions(indexOptions);
- storePayloads = indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS && fieldInfo.hasPayloads();
- lastPayloadFP = 0;
- lastSkipFP = 0;
- lastState = setEmptyState();
- return 0;
- }
-
- private SepTermState setEmptyState() {
- SepTermState emptyState = new SepTermState();
- emptyState.docIndex = docOut.index();
- if (indexOptions != IndexOptions.DOCS_ONLY) {
- emptyState.freqIndex = freqOut.index();
- if (indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
- emptyState.posIndex = posOut.index();
- }
- }
- emptyState.payloadFP = 0;
- emptyState.skipFP = 0;
- return emptyState;
- }
-
- /** Adds a new doc in this term. If this returns null
- * then we just skip consuming positions/payloads. */
- @Override
- public void startDoc(int docID, int termDocFreq) throws IOException {
-
- final int delta = docID - lastDocID;
- //System.out.println("SEPW: startDoc: write doc=" + docID + " delta=" + delta + " out.fp=" + docOut);
-
- if (docID < 0 || (df > 0 && delta <= 0)) {
- throw new CorruptIndexException("docs out of order (" + docID + " <= " + lastDocID + " ) (docOut: " + docOut + ")");
- }
-
- if ((++df % skipInterval) == 0) {
- // TODO: -- awkward we have to make these two
- // separate calls to skipper
- //System.out.println(" buffer skip lastDocID=" + lastDocID);
- skipListWriter.setSkipData(lastDocID, storePayloads, lastPayloadLength);
- skipListWriter.bufferSkip(df);
- }
-
- lastDocID = docID;
- docOut.write(delta);
- if (indexOptions != IndexOptions.DOCS_ONLY) {
- //System.out.println(" sepw startDoc: write freq=" + termDocFreq);
- freqOut.write(termDocFreq);
- }
- }
-
- /** Add a new position & payload */
- @Override
- public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {
- assert indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
-
- final int delta = position - lastPosition;
- assert delta >= 0: "position=" + position + " lastPosition=" + lastPosition; // not quite right (if pos=0 is repeated twice we don't catch it)
- lastPosition = position;
-
- if (storePayloads) {
- final int payloadLength = payload == null ? 0 : payload.length;
- if (payloadLength != lastPayloadLength) {
- lastPayloadLength = payloadLength;
- // TODO: explore whether we get better compression
- // by not storing payloadLength into prox stream?
- posOut.write((delta<<1)|1);
- posOut.write(payloadLength);
- } else {
- posOut.write(delta << 1);
- }
-
- if (payloadLength > 0) {
- payloadOut.writeBytes(payload.bytes, payload.offset, payloadLength);
- }
- } else {
- posOut.write(delta);
- }
-
- lastPosition = position;
- }
-
- /** Called when we are done adding positions & payloads */
- @Override
- public void finishDoc() {
- lastPosition = 0;
- }
-
- private static class SepTermState extends BlockTermState {
- public IntIndexOutput.Index docIndex;
- public IntIndexOutput.Index freqIndex;
- public IntIndexOutput.Index posIndex;
- public long payloadFP;
- public long skipFP;
- }
-
- /** Called when we are done adding docs to this term */
- @Override
- public void finishTerm(BlockTermState _state) throws IOException {
- SepTermState state = (SepTermState)_state;
- // TODO: -- wasteful we are counting this in two places?
- assert state.docFreq > 0;
- assert state.docFreq == df;
-
- state.docIndex = docOut.index();
- state.docIndex.copyFrom(docIndex, false);
- if (indexOptions != IndexOptions.DOCS_ONLY) {
- state.freqIndex = freqOut.index();
- state.freqIndex.copyFrom(freqIndex, false);
- if (indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
- state.posIndex = posOut.index();
- state.posIndex.copyFrom(posIndex, false);
- } else {
- state.posIndex = null;
- }
- } else {
- state.freqIndex = null;
- state.posIndex = null;
- }
-
- if (df >= skipMinimum) {
- state.skipFP = skipOut.getFilePointer();
- //System.out.println(" skipFP=" + skipFP);
- skipListWriter.writeSkip(skipOut);
- //System.out.println(" numBytes=" + (skipOut.getFilePointer()-skipFP));
- } else {
- state.skipFP = -1;
- }
- state.payloadFP = payloadStart;
-
- lastDocID = 0;
- df = 0;
- }
-
- @Override
- public void encodeTerm(long[] longs, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
- SepTermState state = (SepTermState)_state;
- if (absolute) {
- lastSkipFP = 0;
- lastPayloadFP = 0;
- lastState = state;
- }
- lastState.docIndex.copyFrom(state.docIndex, false);
- lastState.docIndex.write(out, absolute);
- if (indexOptions != IndexOptions.DOCS_ONLY) {
- lastState.freqIndex.copyFrom(state.freqIndex, false);
- lastState.freqIndex.write(out, absolute);
- if (indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
- lastState.posIndex.copyFrom(state.posIndex, false);
- lastState.posIndex.write(out, absolute);
- if (storePayloads) {
- if (absolute) {
- out.writeVLong(state.payloadFP);
- } else {
- out.writeVLong(state.payloadFP - lastPayloadFP);
- }
- lastPayloadFP = state.payloadFP;
- }
- }
- }
- if (state.skipFP != -1) {
- if (absolute) {
- out.writeVLong(state.skipFP);
- } else {
- out.writeVLong(state.skipFP - lastSkipFP);
- }
- lastSkipFP = state.skipFP;
- }
- }
-
- @Override
- public void close() throws IOException {
- IOUtils.close(docOut, skipOut, freqOut, posOut, payloadOut);
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockPostingsFormat.java
deleted file mode 100644
index 4ffb090ff58..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockPostingsFormat.java
+++ /dev/null
@@ -1,142 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.blockterms.BlockTermsReader;
-import org.apache.lucene.codecs.blockterms.BlockTermsWriter;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
-import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
-import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
-import org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat; // javadocs
-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.BytesRef;
-
-// TODO: we could make separate base class that can wrapp
-// any PostingsBaseFormat and make it ord-able...
-
-/**
- * Customized version of {@link Lucene41PostingsFormat} that uses
- * {@link FixedGapTermsIndexWriter}.
- */
-public final class TempBlockPostingsFormat extends PostingsFormat {
- final int termIndexInterval;
-
- public TempBlockPostingsFormat() {
- this(FixedGapTermsIndexWriter.DEFAULT_TERM_INDEX_INTERVAL);
- }
-
- public TempBlockPostingsFormat(int termIndexInterval) {
- super("TempBlock");
- this.termIndexInterval = termIndexInterval;
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docs = new TempPostingsWriter(state);
-
- // TODO: should we make the terms index more easily
- // pluggable? Ie so that this codec would record which
- // index impl was used, and switch on loading?
- // Or... you must make a new Codec for this?
- TermsIndexWriterBase indexWriter;
- boolean success = false;
- try {
- indexWriter = new FixedGapTermsIndexWriter(state, termIndexInterval);
- success = true;
- } finally {
- if (!success) {
- docs.close();
- }
- }
-
- success = false;
- try {
- // Must use BlockTermsWriter (not BlockTree) because
- // BlockTree doens't support ords (yet)...
- FieldsConsumer ret = new TempBlockTermsWriter(indexWriter, state, docs);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- docs.close();
- } finally {
- indexWriter.close();
- }
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postings = new TempPostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
- TermsIndexReaderBase indexReader;
-
- boolean success = false;
- try {
- indexReader = new FixedGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- BytesRef.getUTF8SortedAsUnicodeComparator(),
- state.segmentSuffix, state.context);
- success = true;
- } finally {
- if (!success) {
- postings.close();
- }
- }
-
- success = false;
- try {
- FieldsProducer ret = new TempBlockTermsReader(indexReader,
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postings,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postings.close();
- } finally {
- indexReader.close();
- }
- }
- }
- }
-
- /** Extension of freq postings file */
- static final String FREQ_EXTENSION = "frq";
-
- /** Extension of prox postings file */
- static final String PROX_EXTENSION = "prx";
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsReader.java
deleted file mode 100644
index a006531289e..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsReader.java
+++ /dev/null
@@ -1,873 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.Comparator;
-import java.util.Iterator;
-import java.util.TreeMap;
-import java.util.Arrays;
-
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-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.TermState;
-import org.apache.lucene.index.Terms;
-import org.apache.lucene.index.TermsEnum;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-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.DoubleBarrelLRUCache;
-import org.apache.lucene.codecs.blockterms.*;
-
-/** Handles a terms dict, but decouples all details of
- * doc/freqs/positions reading to an instance of {@link
- * TempPostingsReaderBase}. This class is reusable for
- * codecs that use a different format for
- * docs/freqs/positions (though codecs are also free to
- * make their own terms dict impl).
- *
- * <p>This class also interacts with an instance of {@link
- * TermsIndexReaderBase}, to abstract away the specific
- * implementation of the terms dict index.
- * @lucene.experimental */
-
-public class TempBlockTermsReader extends FieldsProducer {
- // Open input to the main terms dict file (_X.tis)
- private final IndexInput in;
-
- // Reads the terms dict entries, to gather state to
- // produce DocsEnum on demand
- private final TempPostingsReaderBase postingsReader;
-
- private final TreeMap<String,FieldReader> fields = new TreeMap<String,FieldReader>();
-
- // Reads the terms index
- private TermsIndexReaderBase indexReader;
-
- // keeps the dirStart offset
- private long dirOffset;
-
- private final int version;
-
- // Used as key for the terms cache
- private static class FieldAndTerm extends DoubleBarrelLRUCache.CloneableKey {
- String field;
- BytesRef term;
-
- public FieldAndTerm() {
- }
-
- public FieldAndTerm(FieldAndTerm other) {
- field = other.field;
- term = BytesRef.deepCopyOf(other.term);
- }
-
- @Override
- public boolean equals(Object _other) {
- FieldAndTerm other = (FieldAndTerm) _other;
- return other.field.equals(field) && term.bytesEquals(other.term);
- }
-
- @Override
- public FieldAndTerm clone() {
- return new FieldAndTerm(this);
- }
-
- @Override
- public int hashCode() {
- return field.hashCode() * 31 + term.hashCode();
- }
- }
-
- // private String segment;
-
- public TempBlockTermsReader(TermsIndexReaderBase indexReader, Directory dir, FieldInfos fieldInfos, SegmentInfo info, TempPostingsReaderBase postingsReader, IOContext context,
- String segmentSuffix)
- throws IOException {
-
- this.postingsReader = postingsReader;
-
- // this.segment = segment;
- in = dir.openInput(IndexFileNames.segmentFileName(info.name, segmentSuffix, TempBlockTermsWriter.TERMS_EXTENSION),
- context);
-
- boolean success = false;
- try {
- version = readHeader(in);
-
- // Have PostingsReader init itself
- postingsReader.init(in);
-
- // Read per-field details
- seekDir(in, dirOffset);
-
- final int numFields = in.readVInt();
- if (numFields < 0) {
- throw new CorruptIndexException("invalid number of fields: " + numFields + " (resource=" + in + ")");
- }
- for(int i=0;i<numFields;i++) {
- final int field = in.readVInt();
- final long numTerms = in.readVLong();
- assert numTerms >= 0;
- final long termsStartPointer = in.readVLong();
- final FieldInfo fieldInfo = fieldInfos.fieldInfo(field);
- 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();
- 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 + ")");
- }
- FieldReader previous = fields.put(fieldInfo.name, new FieldReader(fieldInfo, numTerms, termsStartPointer, sumTotalTermFreq, sumDocFreq, docCount, longsSize));
- if (previous != null) {
- throw new CorruptIndexException("duplicate fields: " + fieldInfo.name + " (resource=" + in + ")");
- }
- }
- success = true;
- } finally {
- if (!success) {
- in.close();
- }
- }
-
- this.indexReader = indexReader;
- }
-
- private int readHeader(IndexInput input) throws IOException {
- int version = CodecUtil.checkHeader(input, TempBlockTermsWriter.CODEC_NAME,
- TempBlockTermsWriter.VERSION_START,
- TempBlockTermsWriter.VERSION_CURRENT);
- if (version < TempBlockTermsWriter.VERSION_APPEND_ONLY) {
- dirOffset = input.readLong();
- }
- return version;
- }
-
- private void seekDir(IndexInput input, long dirOffset) throws IOException {
- if (version >= TempBlockTermsWriter.VERSION_APPEND_ONLY) {
- input.seek(input.length() - 8);
- dirOffset = input.readLong();
- }
- input.seek(dirOffset);
- }
-
- @Override
- public void close() throws IOException {
- try {
- try {
- if (indexReader != null) {
- indexReader.close();
- }
- } finally {
- // null so if an app hangs on to us (ie, we are not
- // GCable, despite being closed) we still free most
- // ram
- indexReader = null;
- if (in != null) {
- in.close();
- }
- }
- } finally {
- if (postingsReader != null) {
- postingsReader.close();
- }
- }
- }
-
- @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();
- }
-
- private class FieldReader extends Terms {
- final long numTerms;
- final FieldInfo fieldInfo;
- final long termsStartPointer;
- final long sumTotalTermFreq;
- final long sumDocFreq;
- final int docCount;
- final int longsSize;
-
- FieldReader(FieldInfo fieldInfo, long numTerms, long termsStartPointer, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize) {
- assert numTerms > 0;
- this.fieldInfo = fieldInfo;
- this.numTerms = numTerms;
- this.termsStartPointer = termsStartPointer;
- this.sumTotalTermFreq = sumTotalTermFreq;
- this.sumDocFreq = sumDocFreq;
- this.docCount = docCount;
- this.longsSize = longsSize;
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- @Override
- public TermsEnum iterator(TermsEnum reuse) throws IOException {
- return new SegmentTermsEnum();
- }
-
- @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 long size() {
- return numTerms;
- }
-
- @Override
- public long getSumTotalTermFreq() {
- return sumTotalTermFreq;
- }
-
- @Override
- public long getSumDocFreq() throws IOException {
- return sumDocFreq;
- }
-
- @Override
- public int getDocCount() throws IOException {
- return docCount;
- }
-
- // Iterates through terms in this field
- private final class SegmentTermsEnum extends TermsEnum {
- private final IndexInput in;
- private final BlockTermState state;
- private final boolean doOrd;
- private final FieldAndTerm fieldTerm = new FieldAndTerm();
- private final TermsIndexReaderBase.FieldIndexEnum indexEnum;
- private final BytesRef term = new BytesRef();
-
- /* This is true if indexEnum is "still" seek'd to the index term
- for the current term. We set it to true on seeking, and then it
- remains valid until next() is called enough times to load another
- terms block: */
- private boolean indexIsCurrent;
-
- /* True if we've already called .next() on the indexEnum, to "bracket"
- the current block of terms: */
- private boolean didIndexNext;
-
- /* Next index term, bracketing the current block of terms; this is
- only valid if didIndexNext is true: */
- private BytesRef nextIndexTerm;
-
- /* True after seekExact(TermState), do defer seeking. If the app then
- calls next() (which is not "typical"), then we'll do the real seek */
- private boolean seekPending;
-
- private byte[] termSuffixes;
- private ByteArrayDataInput termSuffixesReader = new ByteArrayDataInput();
-
- /* Common prefix used for all terms in this block. */
- private int termBlockPrefix;
-
- /* How many terms in current block */
- private int blockTermCount;
-
- private byte[] docFreqBytes;
- private final ByteArrayDataInput freqReader = new ByteArrayDataInput();
- private int metaDataUpto;
-
- private long[] longs;
- private byte[] bytes;
- private ByteArrayDataInput bytesReader;
-
-
- public SegmentTermsEnum() throws IOException {
- in = TempBlockTermsReader.this.in.clone();
- in.seek(termsStartPointer);
- indexEnum = indexReader.getFieldEnum(fieldInfo);
- doOrd = indexReader.supportsOrd();
- fieldTerm.field = fieldInfo.name;
- state = postingsReader.newTermState();
- state.totalTermFreq = -1;
- state.ord = -1;
-
- termSuffixes = new byte[128];
- docFreqBytes = new byte[64];
- //System.out.println("BTR.enum init this=" + this + " postingsReader=" + postingsReader);
- longs = new long[longsSize];
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- // TODO: we may want an alternate mode here which is
- // "if you are about to return NOT_FOUND I won't use
- // the terms data from that"; eg FuzzyTermsEnum will
- // (usually) just immediately call seek again if we
- // return NOT_FOUND so it's a waste for us to fill in
- // the term that was actually NOT_FOUND
- @Override
- public SeekStatus seekCeil(final BytesRef target) throws IOException {
-
- if (indexEnum == null) {
- throw new IllegalStateException("terms index was not loaded");
- }
-
- //System.out.println("BTR.seek seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + term().utf8ToString() + " " + term() + " useCache=" + useCache + " indexIsCurrent=" + indexIsCurrent + " didIndexNext=" + didIndexNext + " seekPending=" + seekPending + " divisor=" + indexReader.getDivisor() + " this=" + this);
- if (didIndexNext) {
- if (nextIndexTerm == null) {
- //System.out.println(" nextIndexTerm=null");
- } else {
- //System.out.println(" nextIndexTerm=" + nextIndexTerm.utf8ToString());
- }
- }
-
- boolean doSeek = true;
-
- // See if we can avoid seeking, because target term
- // is after current term but before next index term:
- if (indexIsCurrent) {
-
- final int cmp = BytesRef.getUTF8SortedAsUnicodeComparator().compare(term, target);
-
- if (cmp == 0) {
- // Already at the requested term
- return SeekStatus.FOUND;
- } else if (cmp < 0) {
-
- // Target term is after current term
- if (!didIndexNext) {
- if (indexEnum.next() == -1) {
- nextIndexTerm = null;
- } else {
- nextIndexTerm = indexEnum.term();
- }
- //System.out.println(" now do index next() nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString()));
- didIndexNext = true;
- }
-
- if (nextIndexTerm == null || BytesRef.getUTF8SortedAsUnicodeComparator().compare(target, nextIndexTerm) < 0) {
- // Optimization: requested term is within the
- // same term block we are now in; skip seeking
- // (but do scanning):
- doSeek = false;
- //System.out.println(" skip seek: nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString()));
- }
- }
- }
-
- if (doSeek) {
- //System.out.println(" seek");
-
- // Ask terms index to find biggest indexed term (=
- // first term in a block) that's <= our text:
- in.seek(indexEnum.seek(target));
- boolean result = nextBlock();
-
- // Block must exist since, at least, the indexed term
- // is in the block:
- assert result;
-
- indexIsCurrent = true;
- didIndexNext = false;
-
- if (doOrd) {
- state.ord = indexEnum.ord()-1;
- }
-
- term.copyBytes(indexEnum.term());
- //System.out.println(" seek: term=" + term.utf8ToString());
- } else {
- //System.out.println(" skip seek");
- if (state.termBlockOrd == blockTermCount && !nextBlock()) {
- indexIsCurrent = false;
- return SeekStatus.END;
- }
- }
-
- seekPending = false;
-
- int common = 0;
-
- // Scan within block. We could do this by calling
- // _next() and testing the resulting term, but this
- // is wasteful. Instead, we first confirm the
- // target matches the common prefix of this block,
- // and then we scan the term bytes directly from the
- // termSuffixesreader's byte[], saving a copy into
- // the BytesRef term per term. Only when we return
- // do we then copy the bytes into the term.
-
- while(true) {
-
- // First, see if target term matches common prefix
- // in this block:
- if (common < termBlockPrefix) {
- final int cmp = (term.bytes[common]&0xFF) - (target.bytes[target.offset + common]&0xFF);
- if (cmp < 0) {
-
- // TODO: maybe we should store common prefix
- // in block header? (instead of relying on
- // last term of previous block)
-
- // Target's prefix is after the common block
- // prefix, so term cannot be in this block
- // but it could be in next block. We
- // must scan to end-of-block to set common
- // prefix for next block:
- if (state.termBlockOrd < blockTermCount) {
- while(state.termBlockOrd < blockTermCount-1) {
- state.termBlockOrd++;
- state.ord++;
- termSuffixesReader.skipBytes(termSuffixesReader.readVInt());
- }
- final int suffix = termSuffixesReader.readVInt();
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
- }
- state.ord++;
-
- if (!nextBlock()) {
- indexIsCurrent = false;
- return SeekStatus.END;
- }
- common = 0;
-
- } else if (cmp > 0) {
- // Target's prefix is before the common prefix
- // of this block, so we position to start of
- // block and return NOT_FOUND:
- assert state.termBlockOrd == 0;
-
- final int suffix = termSuffixesReader.readVInt();
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
- return SeekStatus.NOT_FOUND;
- } else {
- common++;
- }
-
- continue;
- }
-
- // Test every term in this block
- while (true) {
- state.termBlockOrd++;
- state.ord++;
-
- final int suffix = termSuffixesReader.readVInt();
-
- // We know the prefix matches, so just compare the new suffix:
- final int termLen = termBlockPrefix + suffix;
- int bytePos = termSuffixesReader.getPosition();
-
- boolean next = false;
- final int limit = target.offset + (termLen < target.length ? termLen : target.length);
- int targetPos = target.offset + termBlockPrefix;
- while(targetPos < limit) {
- final int cmp = (termSuffixes[bytePos++]&0xFF) - (target.bytes[targetPos++]&0xFF);
- if (cmp < 0) {
- // Current term is still before the target;
- // keep scanning
- next = true;
- break;
- } else if (cmp > 0) {
- // Done! Current term is after target. Stop
- // here, fill in real term, return NOT_FOUND.
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
- //System.out.println(" NOT_FOUND");
- return SeekStatus.NOT_FOUND;
- }
- }
-
- if (!next && target.length <= termLen) {
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
-
- if (target.length == termLen) {
- // Done! Exact match. Stop here, fill in
- // real term, return FOUND.
- //System.out.println(" FOUND");
- return SeekStatus.FOUND;
- } else {
- //System.out.println(" NOT_FOUND");
- return SeekStatus.NOT_FOUND;
- }
- }
-
- if (state.termBlockOrd == blockTermCount) {
- // Must pre-fill term for next block's common prefix
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
- break;
- } else {
- termSuffixesReader.skipBytes(suffix);
- }
- }
-
- // The purpose of the terms dict index is to seek
- // the enum to the closest index term before the
- // term we are looking for. So, we should never
- // cross another index term (besides the first
- // one) while we are scanning:
-
- assert indexIsCurrent;
-
- if (!nextBlock()) {
- //System.out.println(" END");
- indexIsCurrent = false;
- return SeekStatus.END;
- }
- common = 0;
- }
- }
-
- @Override
- public BytesRef next() throws IOException {
- //System.out.println("BTR.next() seekPending=" + seekPending + " pendingSeekCount=" + state.termBlockOrd);
-
- // If seek was previously called and the term was cached,
- // 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 (seekPending) {
- assert !indexIsCurrent;
- in.seek(state.blockFilePointer);
- final int pendingSeekCount = state.termBlockOrd;
- boolean result = nextBlock();
-
- final long savOrd = state.ord;
-
- // Block must exist since seek(TermState) was called w/ a
- // TermState previously returned by this enum when positioned
- // on a real term:
- assert result;
-
- while(state.termBlockOrd < pendingSeekCount) {
- BytesRef nextResult = _next();
- assert nextResult != null;
- }
- seekPending = false;
- state.ord = savOrd;
- }
- return _next();
- }
-
- /* 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. */
- private BytesRef _next() throws IOException {
- //System.out.println("BTR._next seg=" + segment + " this=" + this + " termCount=" + state.termBlockOrd + " (vs " + blockTermCount + ")");
- if (state.termBlockOrd == blockTermCount && !nextBlock()) {
- //System.out.println(" eof");
- indexIsCurrent = false;
- return null;
- }
-
- // TODO: cutover to something better for these ints! simple64?
- final int suffix = termSuffixesReader.readVInt();
- //System.out.println(" suffix=" + suffix);
-
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
- state.termBlockOrd++;
-
- // NOTE: meaningless in the non-ord case
- state.ord++;
-
- //System.out.println(" return term=" + fieldInfo.name + ":" + term.utf8ToString() + " " + term + " tbOrd=" + state.termBlockOrd);
- return term;
- }
-
- @Override
- public BytesRef term() {
- return term;
- }
-
- @Override
- public int docFreq() throws IOException {
- //System.out.println("BTR.docFreq");
- decodeMetaData();
- //System.out.println(" return " + state.docFreq);
- return state.docFreq;
- }
-
- @Override
- public long totalTermFreq() throws IOException {
- decodeMetaData();
- return state.totalTermFreq;
- }
-
- @Override
- public DocsEnum docs(Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
- //System.out.println("BTR.docs this=" + this);
- decodeMetaData();
- //System.out.println("BTR.docs: state.docFreq=" + state.docFreq);
- return postingsReader.docs(fieldInfo, state, liveDocs, reuse, flags);
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {
- if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
- // Positions were not indexed:
- return null;
- }
-
- decodeMetaData();
- return postingsReader.docsAndPositions(fieldInfo, state, liveDocs, reuse, flags);
- }
-
- @Override
- public void seekExact(BytesRef target, TermState otherState) {
- //System.out.println("BTR.seekExact termState target=" + target.utf8ToString() + " " + target + " this=" + this);
- assert otherState != null && otherState instanceof BlockTermState;
- assert !doOrd || ((BlockTermState) otherState).ord < numTerms;
- state.copyFrom(otherState);
- seekPending = true;
- indexIsCurrent = false;
- term.copyBytes(target);
- }
-
- @Override
- public TermState termState() throws IOException {
- //System.out.println("BTR.termState this=" + this);
- decodeMetaData();
- TermState ts = state.clone();
- //System.out.println(" return ts=" + ts);
- return ts;
- }
-
- @Override
- public void seekExact(long ord) throws IOException {
- //System.out.println("BTR.seek by ord ord=" + ord);
- if (indexEnum == null) {
- throw new IllegalStateException("terms index was not loaded");
- }
-
- assert ord < numTerms;
-
- // TODO: if ord is in same terms block and
- // after current ord, we should avoid this seek just
- // like we do in the seek(BytesRef) case
- in.seek(indexEnum.seek(ord));
- boolean result = nextBlock();
-
- // Block must exist since ord < numTerms:
- assert result;
-
- indexIsCurrent = true;
- didIndexNext = false;
- seekPending = false;
-
- state.ord = indexEnum.ord()-1;
- assert state.ord >= -1: "ord=" + state.ord;
- term.copyBytes(indexEnum.term());
-
- // Now, scan:
- int left = (int) (ord - state.ord);
- while(left > 0) {
- final BytesRef term = _next();
- assert term != null;
- left--;
- assert indexIsCurrent;
- }
- }
-
- @Override
- public long ord() {
- if (!doOrd) {
- throw new UnsupportedOperationException();
- }
- return state.ord;
- }
-
- /* 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. */
- private boolean nextBlock() throws IOException {
-
- // TODO: we still lazy-decode the byte[] for each
- // term (the suffix), but, if we decoded
- // all N terms up front then seeking could do a fast
- // bsearch w/in the block...
-
- //System.out.println("BTR.nextBlock() fp=" + in.getFilePointer() + " this=" + this);
- state.blockFilePointer = in.getFilePointer();
- blockTermCount = in.readVInt();
- //System.out.println(" blockTermCount=" + blockTermCount);
- if (blockTermCount == 0) {
- return false;
- }
- termBlockPrefix = in.readVInt();
-
- // term suffixes:
- int len = in.readVInt();
- if (termSuffixes.length < len) {
- termSuffixes = new byte[ArrayUtil.oversize(len, 1)];
- }
- //System.out.println(" termSuffixes len=" + len);
- in.readBytes(termSuffixes, 0, len);
- termSuffixesReader.reset(termSuffixes, 0, len);
-
- // docFreq, totalTermFreq
- len = in.readVInt();
- if (docFreqBytes.length < len) {
- docFreqBytes = new byte[ArrayUtil.oversize(len, 1)];
- }
- //System.out.println(" freq bytes len=" + len);
- in.readBytes(docFreqBytes, 0, len);
- freqReader.reset(docFreqBytes, 0, len);
-
- // metadata
- len = in.readVInt();
- if (bytes == null) {
- bytes = new byte[ArrayUtil.oversize(len, 1)];
- bytesReader = new ByteArrayDataInput();
- } else if (bytes.length < len) {
- bytes = new byte[ArrayUtil.oversize(len, 1)];
- }
- in.readBytes(bytes, 0, len);
- bytesReader.reset(bytes, 0, len);
-
- metaDataUpto = 0;
- state.termBlockOrd = 0;
-
- indexIsCurrent = false;
- //System.out.println(" indexIsCurrent=" + indexIsCurrent);
-
- return true;
- }
-
- private void decodeMetaData() throws IOException {
- //System.out.println("BTR.decodeMetadata mdUpto=" + metaDataUpto + " vs termCount=" + state.termBlockOrd + " state=" + state);
- if (!seekPending) {
- // TODO: cutover to random-access API
- // here.... really stupid that we have to decode N
- // wasted term metadata just to get to the N+1th
- // that we really need...
-
- // lazily catch up on metadata decode:
- final int limit = state.termBlockOrd;
- boolean absolute = metaDataUpto == 0;
- // We must set/incr state.termCount because
- // postings impl can look at this
- state.termBlockOrd = metaDataUpto;
-
- // TODO: better API would be "jump straight to term=N"???
- while (metaDataUpto < limit) {
- //System.out.println(" decode mdUpto=" + metaDataUpto);
- // 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:
-
- // docFreq, totalTermFreq
- state.docFreq = freqReader.readVInt();
- //System.out.println(" dF=" + state.docFreq);
- if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- state.totalTermFreq = state.docFreq + freqReader.readVLong();
- //System.out.println(" totTF=" + state.totalTermFreq);
- }
- // metadata
- for (int i = 0; i < longs.length; i++) {
- longs[i] = bytesReader.readVLong();
- }
- postingsReader.decodeTerm(longs, bytesReader, fieldInfo, state, absolute);
- metaDataUpto++;
- state.termBlockOrd++;
- absolute = false;
- }
- } else {
- //System.out.println(" skip! seekPending");
- }
- }
- }
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsWriter.java
deleted file mode 100644
index 2f276093e7f..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempBlockTermsWriter.java
+++ /dev/null
@@ -1,363 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.Arrays;
-import java.util.Comparator;
-import java.util.List;
-
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.PostingsConsumer;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.TermsConsumer;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.FieldInfos;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-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.IOUtils;
-import org.apache.lucene.util.RamUsageEstimator;
-import org.apache.lucene.codecs.blockterms.*;
-
-// TODO: currently we encode all terms between two indexed
-// terms as a block; but, we could decouple the two, ie
-// allow several blocks in between two indexed terms
-
-/**
- * Writes terms dict, block-encoding (column stride) each
- * term's metadata for each set of terms between two
- * index terms.
- *
- * @lucene.experimental
- */
-
-public class TempBlockTermsWriter extends FieldsConsumer {
-
- final static String CODEC_NAME = "BLOCK_TERMS_DICT";
-
- // Initial format
- public static final int VERSION_START = 0;
- public static final int VERSION_APPEND_ONLY = 1;
- public static final int VERSION_CURRENT = VERSION_APPEND_ONLY;
-
- /** Extension of terms file */
- static final String TERMS_EXTENSION = "tib";
-
- protected final IndexOutput out;
- final TempPostingsWriterBase postingsWriter;
- final FieldInfos fieldInfos;
- FieldInfo currentField;
- private final TermsIndexWriterBase termsIndexWriter;
-
- private static class FieldMetaData {
- public final FieldInfo fieldInfo;
- public final long numTerms;
- public final long termsStartPointer;
- public final long sumTotalTermFreq;
- public final long sumDocFreq;
- public final int docCount;
- public final int longsSize;
-
- public FieldMetaData(FieldInfo fieldInfo, long numTerms, long termsStartPointer, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize) {
- assert numTerms > 0;
- this.fieldInfo = fieldInfo;
- this.termsStartPointer = termsStartPointer;
- this.numTerms = numTerms;
- this.sumTotalTermFreq = sumTotalTermFreq;
- this.sumDocFreq = sumDocFreq;
- this.docCount = docCount;
- this.longsSize = longsSize;
- }
- }
-
- private final List<FieldMetaData> fields = new ArrayList<FieldMetaData>();
-
- // private final String segment;
-
- public TempBlockTermsWriter(TermsIndexWriterBase termsIndexWriter,
- SegmentWriteState state, TempPostingsWriterBase postingsWriter)
- throws IOException {
- final String termsFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_EXTENSION);
- this.termsIndexWriter = termsIndexWriter;
- out = state.directory.createOutput(termsFileName, state.context);
- boolean success = false;
- try {
- fieldInfos = state.fieldInfos;
- writeHeader(out);
- currentField = null;
- this.postingsWriter = postingsWriter;
- // segment = state.segmentName;
-
- //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);
- }
- }
- }
-
- private void writeHeader(IndexOutput out) throws IOException {
- CodecUtil.writeHeader(out, CODEC_NAME, VERSION_CURRENT);
- }
-
- @Override
- public TermsConsumer addField(FieldInfo field) throws IOException {
- //System.out.println("\nBTW.addField seg=" + segment + " field=" + field.name);
- assert currentField == null || currentField.name.compareTo(field.name) < 0;
- currentField = field;
- TermsIndexWriterBase.FieldWriter fieldIndexWriter = termsIndexWriter.addField(field, out.getFilePointer());
- return new TermsWriter(fieldIndexWriter, field, postingsWriter);
- }
-
- @Override
- public void close() throws IOException {
-
- try {
-
- final long dirStart = out.getFilePointer();
-
- out.writeVInt(fields.size());
- for(FieldMetaData field : fields) {
- out.writeVInt(field.fieldInfo.number);
- out.writeVLong(field.numTerms);
- out.writeVLong(field.termsStartPointer);
- if (field.fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- out.writeVLong(field.sumTotalTermFreq);
- }
- out.writeVLong(field.sumDocFreq);
- out.writeVInt(field.docCount);
- out.writeVInt(field.longsSize);
- }
- writeTrailer(dirStart);
- } finally {
- IOUtils.close(out, postingsWriter, termsIndexWriter);
- }
- }
-
- private void writeTrailer(long dirStart) throws IOException {
- out.writeLong(dirStart);
- }
-
- private static class TermEntry {
- public final BytesRef term = new BytesRef();
- public BlockTermState state;
- }
-
- class TermsWriter extends TermsConsumer {
- private final FieldInfo fieldInfo;
- private final TempPostingsWriterBase postingsWriter;
- private final long termsStartPointer;
- private long numTerms;
- private final TermsIndexWriterBase.FieldWriter fieldIndexWriter;
- long sumTotalTermFreq;
- long sumDocFreq;
- int docCount;
- int longsSize;
-
- private TermEntry[] pendingTerms;
-
- private int pendingCount;
-
- TermsWriter(
- TermsIndexWriterBase.FieldWriter fieldIndexWriter,
- FieldInfo fieldInfo,
- TempPostingsWriterBase postingsWriter)
- {
- this.fieldInfo = fieldInfo;
- this.fieldIndexWriter = fieldIndexWriter;
- pendingTerms = new TermEntry[32];
- for(int i=0;i<pendingTerms.length;i++) {
- pendingTerms[i] = new TermEntry();
- }
- termsStartPointer = out.getFilePointer();
- this.postingsWriter = postingsWriter;
- this.longsSize = postingsWriter.setField(fieldInfo);
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- @Override
- public PostingsConsumer startTerm(BytesRef text) throws IOException {
- //System.out.println("BTW: startTerm term=" + fieldInfo.name + ":" + text.utf8ToString() + " " + text + " seg=" + segment);
- postingsWriter.startTerm();
- return postingsWriter;
- }
-
- private final BytesRef lastPrevTerm = new BytesRef();
-
- @Override
- public void finishTerm(BytesRef text, TermStats stats) throws IOException {
-
- assert stats.docFreq > 0;
- //System.out.println("BTW: finishTerm term=" + fieldInfo.name + ":" + text.utf8ToString() + " " + text + " seg=" + segment + " df=" + stats.docFreq);
-
- final boolean isIndexTerm = fieldIndexWriter.checkIndexTerm(text, stats);
-
- if (isIndexTerm) {
- if (pendingCount > 0) {
- // Instead of writing each term, live, we gather terms
- // in RAM in a pending buffer, and then write the
- // entire block in between index terms:
- flushBlock();
- }
- fieldIndexWriter.add(text, stats, out.getFilePointer());
- //System.out.println(" index term!");
- }
-
- if (pendingTerms.length == pendingCount) {
- final TermEntry[] newArray = new TermEntry[ArrayUtil.oversize(pendingCount+1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- System.arraycopy(pendingTerms, 0, newArray, 0, pendingCount);
- for(int i=pendingCount;i<newArray.length;i++) {
- newArray[i] = new TermEntry();
- }
- pendingTerms = newArray;
- }
- final TermEntry te = pendingTerms[pendingCount];
- te.term.copyBytes(text);
- te.state = postingsWriter.newTermState();
- te.state.docFreq = stats.docFreq;
- te.state.totalTermFreq = stats.totalTermFreq;
- postingsWriter.finishTerm(te.state);
-
- pendingCount++;
- numTerms++;
- }
-
- // Finishes all terms in this field
- @Override
- public void finish(long sumTotalTermFreq, long sumDocFreq, int docCount) throws IOException {
- if (pendingCount > 0) {
- flushBlock();
- }
- // EOF marker:
- out.writeVInt(0);
-
- this.sumTotalTermFreq = sumTotalTermFreq;
- this.sumDocFreq = sumDocFreq;
- this.docCount = docCount;
- fieldIndexWriter.finish(out.getFilePointer());
- if (numTerms > 0) {
- fields.add(new FieldMetaData(fieldInfo,
- numTerms,
- termsStartPointer,
- sumTotalTermFreq,
- sumDocFreq,
- docCount,
- longsSize));
- }
- }
-
- private int sharedPrefix(BytesRef term1, BytesRef term2) {
- assert term1.offset == 0;
- assert term2.offset == 0;
- int pos1 = 0;
- int pos1End = pos1 + Math.min(term1.length, term2.length);
- int pos2 = 0;
- while(pos1 < pos1End) {
- if (term1.bytes[pos1] != term2.bytes[pos2]) {
- return pos1;
- }
- pos1++;
- pos2++;
- }
- return pos1;
- }
-
- private final RAMOutputStream bytesWriter = new RAMOutputStream();
- private final RAMOutputStream bufferWriter = new RAMOutputStream();
-
- private void flushBlock() throws IOException {
- //System.out.println("BTW.flushBlock seg=" + segment + " pendingCount=" + pendingCount + " fp=" + out.getFilePointer());
-
- // First pass: compute common prefix for all terms
- // in the block, against term before first term in
- // this block:
- int commonPrefix = sharedPrefix(lastPrevTerm, pendingTerms[0].term);
- for(int termCount=1;termCount<pendingCount;termCount++) {
- commonPrefix = Math.min(commonPrefix,
- sharedPrefix(lastPrevTerm,
- pendingTerms[termCount].term));
- }
-
- out.writeVInt(pendingCount);
- out.writeVInt(commonPrefix);
-
- // 2nd pass: write suffixes, as separate byte[] blob
- for(int termCount=0;termCount<pendingCount;termCount++) {
- final int suffix = pendingTerms[termCount].term.length - commonPrefix;
- // TODO: cutover to better intblock codec, instead
- // of interleaving here:
- bytesWriter.writeVInt(suffix);
- bytesWriter.writeBytes(pendingTerms[termCount].term.bytes, commonPrefix, suffix);
- }
- out.writeVInt((int) bytesWriter.getFilePointer());
- bytesWriter.writeTo(out);
- bytesWriter.reset();
-
- // 3rd pass: write the freqs as byte[] blob
- // TODO: cutover to better intblock codec. simple64?
- // write prefix, suffix first:
- for(int termCount=0;termCount<pendingCount;termCount++) {
- final BlockTermState state = pendingTerms[termCount].state;
- assert state != null;
- bytesWriter.writeVInt(state.docFreq);
- if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- bytesWriter.writeVLong(state.totalTermFreq-state.docFreq);
- }
- }
- out.writeVInt((int) bytesWriter.getFilePointer());
- bytesWriter.writeTo(out);
- bytesWriter.reset();
-
- // 4th pass: write the metadata
- long[] longs = new long[longsSize];
- boolean absolute = true;
- for(int termCount=0;termCount<pendingCount;termCount++) {
- final BlockTermState state = pendingTerms[termCount].state;
- postingsWriter.encodeTerm(longs, bufferWriter, fieldInfo, state, absolute);
- for (int i = 0; i < longsSize; i++) {
- bytesWriter.writeVLong(longs[i]);
- }
- bufferWriter.writeTo(bytesWriter);
- bufferWriter.reset();
- absolute = false;
- }
- out.writeVInt((int) bytesWriter.getFilePointer());
- bytesWriter.writeTo(out);
- bytesWriter.reset();
-
- lastPrevTerm.copyBytes(pendingTerms[pendingCount-1].term);
- pendingCount = 0;
- }
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java
similarity index 87%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java
index 2c786f7696f..8b687a8617d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPostingsFormat.java
@@ -23,8 +23,10 @@ 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
@@ -42,7 +44,7 @@ public final class TempFSTOrdPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase postingsWriter = new TempPostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state);
boolean success = false;
try {
@@ -58,7 +60,7 @@ public final class TempFSTOrdPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postingsReader = new TempPostingsReader(state.directory,
+ PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.directory,
state.fieldInfos,
state.segmentInfo,
state.context,
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java
index c3f7d4ec795..8d6b9f99b6a 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java
@@ -21,9 +21,16 @@ import java.io.IOException;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
+import org.apache.lucene.codecs.PostingsBaseFormat;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsBaseFormat;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat;
+import org.apache.lucene.codecs.pulsing.PulsingPostingsWriter;
+import org.apache.lucene.codecs.pulsing.PulsingPostingsReader;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
@@ -32,22 +39,28 @@ import org.apache.lucene.util.IOUtils;
* @lucene.experimental */
public class TempFSTOrdPulsing41PostingsFormat extends PostingsFormat {
- private final TempPostingsBaseFormat wrappedPostingsBaseFormat;
-
+ private final PostingsBaseFormat wrappedPostingsBaseFormat;
+ private final int freqCutoff;
+
public TempFSTOrdPulsing41PostingsFormat() {
+ this(1);
+ }
+
+ public TempFSTOrdPulsing41PostingsFormat(int freqCutoff) {
super("TempFSTOrdPulsing41");
- this.wrappedPostingsBaseFormat = new TempPostingsBaseFormat();
+ this.wrappedPostingsBaseFormat = new Lucene41PostingsBaseFormat();
+ this.freqCutoff = freqCutoff;
}
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docsWriter = null;
- TempPostingsWriterBase pulsingWriter = null;
+ PostingsWriterBase docsWriter = null;
+ PostingsWriterBase pulsingWriter = null;
boolean success = false;
try {
docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);
- pulsingWriter = new TempPulsingPostingsWriter(state, 1, docsWriter);
+ pulsingWriter = new PulsingPostingsWriter(state, freqCutoff, docsWriter);
FieldsConsumer ret = new TempFSTOrdTermsWriter(state, pulsingWriter);
success = true;
return ret;
@@ -60,12 +73,12 @@ public class TempFSTOrdPulsing41PostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase docsReader = null;
- TempPostingsReaderBase pulsingReader = null;
+ PostingsReaderBase docsReader = null;
+ PostingsReaderBase pulsingReader = null;
boolean success = false;
try {
docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);
- pulsingReader = new TempPulsingPostingsReader(state, docsReader);
+ pulsingReader = new PulsingPostingsReader(state, docsReader);
FieldsProducer ret = new TempFSTOrdTermsReader(state, pulsingReader);
success = true;
return ret;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java
similarity index 99%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java
index 0fa434143fa..4d664b80577 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java
@@ -58,18 +58,18 @@ import org.apache.lucene.util.fst.PositiveIntOutputs;
import org.apache.lucene.util.fst.Util;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.CodecUtil;
public class TempFSTOrdTermsReader extends FieldsProducer {
static final int INTERVAL = TempFSTOrdTermsWriter.SKIP_INTERVAL;
final TreeMap<String, TermsReader> fields = new TreeMap<String, TermsReader>();
- final TempPostingsReaderBase postingsReader;
+ final PostingsReaderBase postingsReader;
IndexInput indexIn = null;
IndexInput blockIn = null;
//static final boolean TEST = false;
- public TempFSTOrdTermsReader(SegmentReadState state, TempPostingsReaderBase postingsReader) throws IOException {
+ public TempFSTOrdTermsReader(SegmentReadState state, PostingsReaderBase postingsReader) throws IOException {
final String termsIndexFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempFSTOrdTermsWriter.TERMS_INDEX_EXTENSION);
final String termsBlockFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempFSTOrdTermsWriter.TERMS_BLOCK_EXTENSION);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java
similarity index 97%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java
index ed9ccb7d0e9..1c51b87e945 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java
@@ -38,7 +38,7 @@ import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
import org.apache.lucene.util.fst.Util;
import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.codecs.PostingsConsumer;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.TermsConsumer;
@@ -57,13 +57,13 @@ public class TempFSTOrdTermsWriter extends FieldsConsumer {
public static final int SKIP_INTERVAL = 8;
//static final boolean TEST = false;
- final TempPostingsWriterBase postingsWriter;
+ final PostingsWriterBase postingsWriter;
final FieldInfos fieldInfos;
final List<FieldMetaData> fields = new ArrayList<FieldMetaData>();
IndexOutput blockOut = null;
IndexOutput indexOut = null; // nocommit: hmm, do we really need two streams?
- public TempFSTOrdTermsWriter(SegmentWriteState state, TempPostingsWriterBase postingsWriter) throws IOException {
+ public TempFSTOrdTermsWriter(SegmentWriteState state, PostingsWriterBase postingsWriter) throws IOException {
final String termsIndexFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_INDEX_EXTENSION);
final String termsBlockFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_BLOCK_EXTENSION);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java
similarity index 87%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java
index 9c0806dc321..4fe7ae7a7ec 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPostingsFormat.java
@@ -23,8 +23,10 @@ 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
@@ -42,7 +44,7 @@ public final class TempFSTPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase postingsWriter = new TempPostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state);
boolean success = false;
try {
@@ -58,7 +60,7 @@ public final class TempFSTPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postingsReader = new TempPostingsReader(state.directory,
+ PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.directory,
state.fieldInfos,
state.segmentInfo,
state.context,
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java
index e5131646a21..063ebc24860 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java
@@ -21,9 +21,16 @@ import java.io.IOException;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
+import org.apache.lucene.codecs.PostingsBaseFormat;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsBaseFormat;
+import org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat;
+import org.apache.lucene.codecs.pulsing.PulsingPostingsWriter;
+import org.apache.lucene.codecs.pulsing.PulsingPostingsReader;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
@@ -33,22 +40,28 @@ import org.apache.lucene.util.IOUtils;
* @lucene.experimental */
public class TempFSTPulsing41PostingsFormat extends PostingsFormat {
- private final TempPostingsBaseFormat wrappedPostingsBaseFormat;
-
+ private final PostingsBaseFormat wrappedPostingsBaseFormat;
+ private final int freqCutoff;
+
public TempFSTPulsing41PostingsFormat() {
+ this(1);
+ }
+
+ public TempFSTPulsing41PostingsFormat(int freqCutoff) {
super("TempFSTPulsing41");
- this.wrappedPostingsBaseFormat = new TempPostingsBaseFormat();
+ this.wrappedPostingsBaseFormat = new Lucene41PostingsBaseFormat();
+ this.freqCutoff = freqCutoff;
}
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docsWriter = null;
- TempPostingsWriterBase pulsingWriter = null;
+ PostingsWriterBase docsWriter = null;
+ PostingsWriterBase pulsingWriter = null;
boolean success = false;
try {
docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);
- pulsingWriter = new TempPulsingPostingsWriter(state, 1, docsWriter);
+ pulsingWriter = new PulsingPostingsWriter(state, freqCutoff, docsWriter);
FieldsConsumer ret = new TempFSTTermsWriter(state, pulsingWriter);
success = true;
return ret;
@@ -61,12 +74,12 @@ public class TempFSTPulsing41PostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase docsReader = null;
- TempPostingsReaderBase pulsingReader = null;
+ PostingsReaderBase docsReader = null;
+ PostingsReaderBase pulsingReader = null;
boolean success = false;
try {
docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);
- pulsingReader = new TempPulsingPostingsReader(state, docsReader);
+ pulsingReader = new PulsingPostingsReader(state, docsReader);
FieldsProducer ret = new TempFSTTermsReader(state, pulsingReader);
success = true;
return ret;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java
similarity index 99%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java
index 83032b76ed6..e8658560e43 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java
@@ -56,16 +56,16 @@ import org.apache.lucene.util.fst.Outputs;
import org.apache.lucene.util.fst.Util;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
+import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.CodecUtil;
public class TempFSTTermsReader extends FieldsProducer {
final TreeMap<String, TermsReader> fields = new TreeMap<String, TermsReader>();
- final TempPostingsReaderBase postingsReader;
+ final PostingsReaderBase postingsReader;
final IndexInput in;
//static boolean DEBUG = false;
- public TempFSTTermsReader(SegmentReadState state, TempPostingsReaderBase postingsReader) throws IOException {
+ public TempFSTTermsReader(SegmentReadState state, PostingsReaderBase postingsReader) throws IOException {
final String termsFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempFSTTermsWriter.TERMS_EXTENSION);
this.postingsReader = postingsReader;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java
similarity index 97%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java
index 50fb221a4b4..7a8905c16ee 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTTermsWriter.java
@@ -37,7 +37,7 @@ import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.Util;
import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.codecs.PostingsConsumer;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.TermsConsumer;
@@ -53,12 +53,12 @@ public class TempFSTTermsWriter extends FieldsConsumer {
public static final int TERMS_VERSION_START = 0;
public static final int TERMS_VERSION_CURRENT = TERMS_VERSION_START;
- final TempPostingsWriterBase postingsWriter;
+ final PostingsWriterBase postingsWriter;
final FieldInfos fieldInfos;
final IndexOutput out;
final List<FieldMetaData> fields = new ArrayList<FieldMetaData>();
- public TempFSTTermsWriter(SegmentWriteState state, TempPostingsWriterBase postingsWriter) throws IOException {
+ public TempFSTTermsWriter(SegmentWriteState state, PostingsWriterBase postingsWriter) throws IOException {
final String termsFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_EXTENSION);
this.postingsWriter = postingsWriter;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempNestedPulsingPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempNestedPulsingPostingsFormat.java
deleted file mode 100644
index 92ef4ac4e97..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempNestedPulsingPostingsFormat.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.util.IOUtils;
-
-/**
- * Pulsing(1, Pulsing(2, Lucene41))
- * @lucene.experimental
- */
-// TODO: if we create PulsingPostingsBaseFormat then we
-// can simplify this? note: I don't like the *BaseFormat
-// hierarchy, maybe we can clean that up...
-public final class TempNestedPulsingPostingsFormat extends PostingsFormat {
- public TempNestedPulsingPostingsFormat() {
- super("TempNestedPulsing");
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docsWriter = null;
- TempPostingsWriterBase pulsingWriterInner = null;
- TempPostingsWriterBase pulsingWriter = null;
-
- // Terms dict
- boolean success = false;
- try {
- docsWriter = new TempPostingsWriter(state);
-
- pulsingWriterInner = new TempPulsingPostingsWriter(state, 2, docsWriter);
- pulsingWriter = new TempPulsingPostingsWriter(state, 1, pulsingWriterInner);
- FieldsConsumer ret = new TempBlockTreeTermsWriter(state, pulsingWriter,
- TempBlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, TempBlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docsWriter, pulsingWriterInner, pulsingWriter);
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase docsReader = null;
- TempPostingsReaderBase pulsingReaderInner = null;
- TempPostingsReaderBase pulsingReader = null;
- boolean success = false;
- try {
- docsReader = new TempPostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
- pulsingReaderInner = new TempPulsingPostingsReader(state, docsReader);
- pulsingReader = new TempPulsingPostingsReader(state, pulsingReaderInner);
- FieldsProducer ret = new TempBlockTreeTermsReader(
- state.directory, state.fieldInfos, state.segmentInfo,
- pulsingReader,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docsReader, pulsingReaderInner, pulsingReader);
- }
- }
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.java
deleted file mode 100644
index 5d90face596..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.lucene.codecs.BlockTreeTermsWriter;
-import org.apache.lucene.codecs.lucene41.Lucene41PostingsBaseFormat;
-import org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat; // javadocs
-import org.apache.lucene.codecs.temp.TempPostingsBaseFormat;
-
-/**
- * Concrete pulsing implementation over {@link Lucene41PostingsFormat}.
- *
- * @lucene.experimental
- */
-public class TempPulsing41PostingsFormat extends TempPulsingPostingsFormat {
-
- /** Inlines docFreq=1 terms, otherwise uses the normal "Lucene41" format. */
- public TempPulsing41PostingsFormat() {
- this(1);
- }
-
- /** Inlines docFreq=<code>freqCutoff</code> terms, otherwise uses the normal "Lucene41" format. */
- public TempPulsing41PostingsFormat(int freqCutoff) {
- this(freqCutoff, BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
- }
-
- /** Inlines docFreq=<code>freqCutoff</code> terms, otherwise uses the normal "Lucene41" format. */
- public TempPulsing41PostingsFormat(int freqCutoff, int minBlockSize, int maxBlockSize) {
- super("TempPulsing41", new TempPostingsBaseFormat(), freqCutoff, minBlockSize, maxBlockSize);
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.java
deleted file mode 100644
index a112a11aa24..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.temp.TempBlockTreeTermsReader;
-import org.apache.lucene.codecs.temp.TempBlockTreeTermsWriter;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.TempPostingsBaseFormat;
-import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.util.IOUtils;
-
-/** This postings format "inlines" the postings for terms that have
- * low docFreq. It wraps another postings format, which is used for
- * writing the non-inlined terms.
- *
- * @lucene.experimental */
-
-public abstract class TempPulsingPostingsFormat extends PostingsFormat {
-
- private final int freqCutoff;
- private final int minBlockSize;
- private final int maxBlockSize;
- private final TempPostingsBaseFormat wrappedPostingsBaseFormat;
-
- public TempPulsingPostingsFormat(String name, TempPostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff) {
- this(name, wrappedPostingsBaseFormat, freqCutoff, TempBlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, TempBlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
- }
-
- /** Terms with freq <= freqCutoff are inlined into terms
- * dict. */
- public TempPulsingPostingsFormat(String name, TempPostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff, int minBlockSize, int maxBlockSize) {
- super(name);
- this.freqCutoff = freqCutoff;
- this.minBlockSize = minBlockSize;
- assert minBlockSize > 1;
- this.maxBlockSize = maxBlockSize;
- this.wrappedPostingsBaseFormat = wrappedPostingsBaseFormat;
- }
-
- @Override
- public String toString() {
- return getName() + "(freqCutoff=" + freqCutoff + " minBlockSize=" + minBlockSize + " maxBlockSize=" + maxBlockSize + ")";
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docsWriter = null;
-
- // Terms that have <= freqCutoff number of docs are
- // "pulsed" (inlined):
- TempPostingsWriterBase pulsingWriter = null;
-
- // Terms dict
- boolean success = false;
- try {
- docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);
-
- // Terms that have <= freqCutoff number of docs are
- // "pulsed" (inlined):
- pulsingWriter = new TempPulsingPostingsWriter(state, freqCutoff, docsWriter);
- FieldsConsumer ret = new TempBlockTreeTermsWriter(state, pulsingWriter, minBlockSize, maxBlockSize);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docsWriter, pulsingWriter);
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase docsReader = null;
- TempPostingsReaderBase pulsingReader = null;
-
- boolean success = false;
- try {
- docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);
- pulsingReader = new TempPulsingPostingsReader(state, docsReader);
- FieldsProducer ret = new TempBlockTreeTermsReader(
- state.directory, state.fieldInfos, state.segmentInfo,
- pulsingReader,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docsReader, pulsingReader);
- }
- }
- }
-
- public int getFreqCutoff() {
- return freqCutoff;
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.java
deleted file mode 100644
index f52e7aa7e78..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.java
+++ /dev/null
@@ -1,651 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.IdentityHashMap;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.TermState;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.DataInput;
-import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.Attribute;
-import org.apache.lucene.util.AttributeImpl;
-import org.apache.lucene.util.AttributeSource;
-import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-/** Concrete class that reads the current doc/freq/skip
- * postings format
- * @lucene.experimental */
-
-// TODO: -- should we switch "hasProx" higher up? and
-// create two separate docs readers, one that also reads
-// prox and one that doesn't?
-
-public class TempPulsingPostingsReader extends TempPostingsReaderBase {
-
- // Fallback reader for non-pulsed terms:
- final TempPostingsReaderBase wrappedPostingsReader;
- final SegmentReadState segmentState;
- int maxPositions;
- int version;
- TreeMap<Integer, Integer> fields;
-
- public TempPulsingPostingsReader(SegmentReadState state, TempPostingsReaderBase wrappedPostingsReader) {
- this.wrappedPostingsReader = wrappedPostingsReader;
- this.segmentState = state;
- }
-
- @Override
- public void init(IndexInput termsIn) throws IOException {
- version = CodecUtil.checkHeader(termsIn, TempPulsingPostingsWriter.CODEC,
- TempPulsingPostingsWriter.VERSION_START,
- TempPulsingPostingsWriter.VERSION_CURRENT);
- maxPositions = termsIn.readVInt();
- wrappedPostingsReader.init(termsIn);
- if (wrappedPostingsReader instanceof TempPulsingPostingsReader ||
- version < TempPulsingPostingsWriter.VERSION_META_ARRAY) {
- fields = null;
- } else {
- fields = new TreeMap<Integer, Integer>();
- String summaryFileName = IndexFileNames.segmentFileName(segmentState.segmentInfo.name, segmentState.segmentSuffix, TempPulsingPostingsWriter.SUMMARY_EXTENSION);
- IndexInput in = null;
- try {
- in = segmentState.directory.openInput(summaryFileName, segmentState.context);
- CodecUtil.checkHeader(in, TempPulsingPostingsWriter.CODEC, version,
- TempPulsingPostingsWriter.VERSION_CURRENT);
- int numField = in.readVInt();
- for (int i = 0; i < numField; i++) {
- int fieldNum = in.readVInt();
- int longsSize = in.readVInt();
- fields.put(fieldNum, longsSize);
- }
- } finally {
- IOUtils.closeWhileHandlingException(in);
- }
- }
- }
-
- private static class PulsingTermState extends BlockTermState {
- private boolean absolute = false;
- private long[] longs;
- private byte[] postings;
- private int postingsSize; // -1 if this term was not inlined
- private BlockTermState wrappedTermState;
-
- @Override
- public PulsingTermState clone() {
- PulsingTermState clone;
- clone = (PulsingTermState) super.clone();
- if (postingsSize != -1) {
- clone.postings = new byte[postingsSize];
- System.arraycopy(postings, 0, clone.postings, 0, postingsSize);
- } else {
- assert wrappedTermState != null;
- clone.wrappedTermState = (BlockTermState) wrappedTermState.clone();
- clone.absolute = absolute;
- if (longs != null) {
- clone.longs = new long[longs.length];
- System.arraycopy(longs, 0, clone.longs, 0, longs.length);
- }
- }
- return clone;
- }
-
- @Override
- public void copyFrom(TermState _other) {
- super.copyFrom(_other);
- PulsingTermState other = (PulsingTermState) _other;
- postingsSize = other.postingsSize;
- if (other.postingsSize != -1) {
- if (postings == null || postings.length < other.postingsSize) {
- postings = new byte[ArrayUtil.oversize(other.postingsSize, 1)];
- }
- System.arraycopy(other.postings, 0, postings, 0, other.postingsSize);
- } else {
- wrappedTermState.copyFrom(other.wrappedTermState);
- }
- }
-
- @Override
- public String toString() {
- if (postingsSize == -1) {
- return "PulsingTermState: not inlined: wrapped=" + wrappedTermState;
- } else {
- return "PulsingTermState: inlined size=" + postingsSize + " " + super.toString();
- }
- }
- }
-
- @Override
- public BlockTermState newTermState() throws IOException {
- PulsingTermState state = new PulsingTermState();
- state.wrappedTermState = wrappedPostingsReader.newTermState();
- return state;
- }
-
- @Override
- public void decodeTerm(long[] empty, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute) throws IOException {
- //System.out.println("PR nextTerm");
- PulsingTermState termState = (PulsingTermState) _termState;
- assert empty.length == 0;
- termState.absolute = termState.absolute || absolute;
- // if we have positions, its total TF, otherwise its computed based on docFreq.
- long count = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 ? termState.totalTermFreq : termState.docFreq;
- //System.out.println(" count=" + count + " threshold=" + maxPositions);
-
- if (count <= maxPositions) {
- // Inlined into terms dict -- just read the byte[] blob in,
- // but don't decode it now (we only decode when a DocsEnum
- // or D&PEnum is pulled):
- termState.postingsSize = in.readVInt();
- if (termState.postings == null || termState.postings.length < termState.postingsSize) {
- termState.postings = new byte[ArrayUtil.oversize(termState.postingsSize, 1)];
- }
- // TODO: sort of silly to copy from one big byte[]
- // (the blob holding all inlined terms' blobs for
- // current term block) into another byte[] (just the
- // blob for this term)...
- in.readBytes(termState.postings, 0, termState.postingsSize);
- //System.out.println(" inlined bytes=" + termState.postingsSize);
- termState.absolute = termState.absolute || absolute;
- } else {
- //System.out.println(" not inlined");
- final int longsSize = fields == null ? 0 : fields.get(fieldInfo.number);
- if (termState.longs == null) {
- termState.longs = new long[longsSize];
- }
- for (int i = 0; i < longsSize; i++) {
- termState.longs[i] = in.readVLong();
- }
- termState.postingsSize = -1;
- termState.wrappedTermState.docFreq = termState.docFreq;
- termState.wrappedTermState.totalTermFreq = termState.totalTermFreq;
- wrappedPostingsReader.decodeTerm(termState.longs, in, fieldInfo, termState.wrappedTermState, termState.absolute);
- termState.absolute = false;
- }
- }
-
- @Override
- public DocsEnum docs(FieldInfo field, BlockTermState _termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
- PulsingTermState termState = (PulsingTermState) _termState;
- if (termState.postingsSize != -1) {
- PulsingDocsEnum postings;
- if (reuse instanceof PulsingDocsEnum) {
- postings = (PulsingDocsEnum) reuse;
- if (!postings.canReuse(field)) {
- postings = new PulsingDocsEnum(field);
- }
- } else {
- // the 'reuse' is actually the wrapped enum
- PulsingDocsEnum previous = (PulsingDocsEnum) getOther(reuse);
- if (previous != null && previous.canReuse(field)) {
- postings = previous;
- } else {
- postings = new PulsingDocsEnum(field);
- }
- }
- if (reuse != postings) {
- setOther(postings, reuse); // postings.other = reuse
- }
- return postings.reset(liveDocs, termState);
- } else {
- if (reuse instanceof PulsingDocsEnum) {
- DocsEnum wrapped = wrappedPostingsReader.docs(field, termState.wrappedTermState, liveDocs, getOther(reuse), flags);
- setOther(wrapped, reuse); // wrapped.other = reuse
- return wrapped;
- } else {
- return wrappedPostingsReader.docs(field, termState.wrappedTermState, liveDocs, reuse, flags);
- }
- }
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(FieldInfo field, BlockTermState _termState, Bits liveDocs, DocsAndPositionsEnum reuse,
- int flags) throws IOException {
-
- final PulsingTermState termState = (PulsingTermState) _termState;
-
- if (termState.postingsSize != -1) {
- PulsingDocsAndPositionsEnum postings;
- if (reuse instanceof PulsingDocsAndPositionsEnum) {
- postings = (PulsingDocsAndPositionsEnum) reuse;
- if (!postings.canReuse(field)) {
- postings = new PulsingDocsAndPositionsEnum(field);
- }
- } else {
- // the 'reuse' is actually the wrapped enum
- PulsingDocsAndPositionsEnum previous = (PulsingDocsAndPositionsEnum) getOther(reuse);
- if (previous != null && previous.canReuse(field)) {
- postings = previous;
- } else {
- postings = new PulsingDocsAndPositionsEnum(field);
- }
- }
- if (reuse != postings) {
- setOther(postings, reuse); // postings.other = reuse
- }
- return postings.reset(liveDocs, termState);
- } else {
- if (reuse instanceof PulsingDocsAndPositionsEnum) {
- DocsAndPositionsEnum wrapped = wrappedPostingsReader.docsAndPositions(field, termState.wrappedTermState, liveDocs, (DocsAndPositionsEnum) getOther(reuse),
- flags);
- setOther(wrapped, reuse); // wrapped.other = reuse
- return wrapped;
- } else {
- return wrappedPostingsReader.docsAndPositions(field, termState.wrappedTermState, liveDocs, reuse, flags);
- }
- }
- }
-
- private static class PulsingDocsEnum extends DocsEnum {
- private byte[] postingsBytes;
- private final ByteArrayDataInput postings = new ByteArrayDataInput();
- private final IndexOptions indexOptions;
- private final boolean storePayloads;
- private final boolean storeOffsets;
- private Bits liveDocs;
- private int docID = -1;
- private int accum;
- private int freq;
- private int payloadLength;
- private int cost;
-
- public PulsingDocsEnum(FieldInfo fieldInfo) {
- indexOptions = fieldInfo.getIndexOptions();
- storePayloads = fieldInfo.hasPayloads();
- storeOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- }
-
- public PulsingDocsEnum reset(Bits liveDocs, PulsingTermState termState) {
- //System.out.println("PR docsEnum termState=" + termState + " docFreq=" + termState.docFreq);
- assert termState.postingsSize != -1;
-
- // Must make a copy of termState's byte[] so that if
- // app does TermsEnum.next(), this DocsEnum is not affected
- if (postingsBytes == null) {
- postingsBytes = new byte[termState.postingsSize];
- } else if (postingsBytes.length < termState.postingsSize) {
- postingsBytes = ArrayUtil.grow(postingsBytes, termState.postingsSize);
- }
- System.arraycopy(termState.postings, 0, postingsBytes, 0, termState.postingsSize);
- postings.reset(postingsBytes, 0, termState.postingsSize);
- docID = -1;
- accum = 0;
- freq = 1;
- cost = termState.docFreq;
- payloadLength = 0;
- this.liveDocs = liveDocs;
- return this;
- }
-
- boolean canReuse(FieldInfo fieldInfo) {
- return indexOptions == fieldInfo.getIndexOptions() && storePayloads == fieldInfo.hasPayloads();
- }
-
- @Override
- public int nextDoc() throws IOException {
- //System.out.println("PR nextDoc this= "+ this);
- while(true) {
- if (postings.eof()) {
- //System.out.println("PR END");
- return docID = NO_MORE_DOCS;
- }
-
- final int code = postings.readVInt();
- //System.out.println(" read code=" + code);
- if (indexOptions == IndexOptions.DOCS_ONLY) {
- accum += code;
- } else {
- accum += code >>> 1; // shift off low bit
- if ((code & 1) != 0) { // if low bit is set
- freq = 1; // freq is one
- } else {
- freq = postings.readVInt(); // else read freq
- }
-
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
- // Skip positions
- if (storePayloads) {
- for(int pos=0;pos<freq;pos++) {
- final int posCode = postings.readVInt();
- if ((posCode & 1) != 0) {
- payloadLength = postings.readVInt();
- }
- if (storeOffsets && (postings.readVInt() & 1) != 0) {
- // new offset length
- postings.readVInt();
- }
- if (payloadLength != 0) {
- postings.skipBytes(payloadLength);
- }
- }
- } else {
- for(int pos=0;pos<freq;pos++) {
- // TODO: skipVInt
- postings.readVInt();
- if (storeOffsets && (postings.readVInt() & 1) != 0) {
- // new offset length
- postings.readVInt();
- }
- }
- }
- }
- }
-
- if (liveDocs == null || liveDocs.get(accum)) {
- return (docID = accum);
- }
- }
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return docID;
- }
-
- @Override
- public int advance(int target) throws IOException {
- return docID = slowAdvance(target);
- }
-
- @Override
- public long cost() {
- return cost;
- }
- }
-
- private static class PulsingDocsAndPositionsEnum extends DocsAndPositionsEnum {
- private byte[] postingsBytes;
- private final ByteArrayDataInput postings = new ByteArrayDataInput();
- private final boolean storePayloads;
- private final boolean storeOffsets;
- // note: we could actually reuse across different options, if we passed this to reset()
- // and re-init'ed storeOffsets accordingly (made it non-final)
- private final IndexOptions indexOptions;
-
- private Bits liveDocs;
- private int docID = -1;
- private int accum;
- private int freq;
- private int posPending;
- private int position;
- private int payloadLength;
- private BytesRef payload;
- private int startOffset;
- private int offsetLength;
-
- private boolean payloadRetrieved;
- private int cost;
-
- public PulsingDocsAndPositionsEnum(FieldInfo fieldInfo) {
- indexOptions = fieldInfo.getIndexOptions();
- storePayloads = fieldInfo.hasPayloads();
- storeOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- }
-
- boolean canReuse(FieldInfo fieldInfo) {
- return indexOptions == fieldInfo.getIndexOptions() && storePayloads == fieldInfo.hasPayloads();
- }
-
- public PulsingDocsAndPositionsEnum reset(Bits liveDocs, PulsingTermState termState) {
- assert termState.postingsSize != -1;
- if (postingsBytes == null) {
- postingsBytes = new byte[termState.postingsSize];
- } else if (postingsBytes.length < termState.postingsSize) {
- postingsBytes = ArrayUtil.grow(postingsBytes, termState.postingsSize);
- }
- System.arraycopy(termState.postings, 0, postingsBytes, 0, termState.postingsSize);
- postings.reset(postingsBytes, 0, termState.postingsSize);
- this.liveDocs = liveDocs;
- payloadLength = 0;
- posPending = 0;
- docID = -1;
- accum = 0;
- cost = termState.docFreq;
- startOffset = storeOffsets ? 0 : -1; // always return -1 if no offsets are stored
- offsetLength = 0;
- //System.out.println("PR d&p reset storesPayloads=" + storePayloads + " bytes=" + bytes.length + " this=" + this);
- return this;
- }
-
- @Override
- public int nextDoc() throws IOException {
- //System.out.println("PR d&p nextDoc this=" + this);
-
- while(true) {
- //System.out.println(" cycle skip posPending=" + posPending);
-
- skipPositions();
-
- if (postings.eof()) {
- //System.out.println("PR END");
- return docID = NO_MORE_DOCS;
- }
-
- final int code = postings.readVInt();
- accum += code >>> 1; // shift off low bit
- if ((code & 1) != 0) { // if low bit is set
- freq = 1; // freq is one
- } else {
- freq = postings.readVInt(); // else read freq
- }
- posPending = freq;
- startOffset = storeOffsets ? 0 : -1; // always return -1 if no offsets are stored
-
- if (liveDocs == null || liveDocs.get(accum)) {
- //System.out.println(" return docID=" + docID + " freq=" + freq);
- position = 0;
- return (docID = accum);
- }
- }
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return docID;
- }
-
- @Override
- public int advance(int target) throws IOException {
- return docID = slowAdvance(target);
- }
-
- @Override
- public int nextPosition() throws IOException {
- //System.out.println("PR d&p nextPosition posPending=" + posPending + " vs freq=" + freq);
-
- assert posPending > 0;
- posPending--;
-
- if (storePayloads) {
- if (!payloadRetrieved) {
- //System.out.println("PR skip payload=" + payloadLength);
- postings.skipBytes(payloadLength);
- }
- final int code = postings.readVInt();
- //System.out.println("PR code=" + code);
- if ((code & 1) != 0) {
- payloadLength = postings.readVInt();
- //System.out.println("PR new payload len=" + payloadLength);
- }
- position += code >>> 1;
- payloadRetrieved = false;
- } else {
- position += postings.readVInt();
- }
-
- if (storeOffsets) {
- int offsetCode = postings.readVInt();
- if ((offsetCode & 1) != 0) {
- // new offset length
- offsetLength = postings.readVInt();
- }
- startOffset += offsetCode >>> 1;
- }
-
- //System.out.println("PR d&p nextPos return pos=" + position + " this=" + this);
- return position;
- }
-
- @Override
- public int startOffset() {
- return startOffset;
- }
-
- @Override
- public int endOffset() {
- return startOffset + offsetLength;
- }
-
- private void skipPositions() throws IOException {
- while(posPending != 0) {
- nextPosition();
- }
- if (storePayloads && !payloadRetrieved) {
- //System.out.println(" skip payload len=" + payloadLength);
- postings.skipBytes(payloadLength);
- payloadRetrieved = true;
- }
- }
-
- @Override
- public BytesRef getPayload() throws IOException {
- //System.out.println("PR getPayload payloadLength=" + payloadLength + " this=" + this);
- if (payloadRetrieved) {
- return payload;
- } else if (storePayloads && payloadLength > 0) {
- payloadRetrieved = true;
- if (payload == null) {
- payload = new BytesRef(payloadLength);
- } else {
- payload.grow(payloadLength);
- }
- postings.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
- return payload;
- } else {
- return null;
- }
- }
-
- @Override
- public long cost() {
- return cost;
- }
- }
-
- @Override
- public void close() throws IOException {
- wrappedPostingsReader.close();
- }
-
- /** for a docsenum, gets the 'other' reused enum.
- * Example: Pulsing(Standard).
- * when doing a term range query you are switching back and forth
- * between Pulsing and Standard
- *
- * The way the reuse works is that Pulsing.other = Standard and
- * Standard.other = Pulsing.
- */
- private DocsEnum getOther(DocsEnum de) {
- if (de == null) {
- return null;
- } else {
- final AttributeSource atts = de.attributes();
- return atts.addAttribute(PulsingEnumAttribute.class).enums().get(this);
- }
- }
-
- /**
- * for a docsenum, sets the 'other' reused enum.
- * see getOther for an example.
- */
- private DocsEnum setOther(DocsEnum de, DocsEnum other) {
- final AttributeSource atts = de.attributes();
- return atts.addAttribute(PulsingEnumAttribute.class).enums().put(this, other);
- }
-
- /**
- * A per-docsenum attribute that stores additional reuse information
- * so that pulsing enums can keep a reference to their wrapped enums,
- * and vice versa. this way we can always reuse.
- *
- * @lucene.internal */
- public static interface PulsingEnumAttribute extends Attribute {
- public Map<TempPulsingPostingsReader,DocsEnum> enums();
- }
-
- /**
- * Implementation of {@link PulsingEnumAttribute} for reuse of
- * wrapped postings readers underneath pulsing.
- *
- * @lucene.internal */
- public static final class PulsingEnumAttributeImpl extends AttributeImpl implements PulsingEnumAttribute {
- // we could store 'other', but what if someone 'chained' multiple postings readers,
- // this could cause problems?
- // TODO: we should consider nuking this map and just making it so if you do this,
- // you don't reuse? and maybe pulsingPostingsReader should throw an exc if it wraps
- // another pulsing, because this is just stupid and wasteful.
- // we still have to be careful in case someone does Pulsing(Stomping(Pulsing(...
- private final Map<TempPulsingPostingsReader,DocsEnum> enums =
- new IdentityHashMap<TempPulsingPostingsReader,DocsEnum>();
-
- @Override
- public Map<TempPulsingPostingsReader,DocsEnum> enums() {
- return enums;
- }
-
- @Override
- public void clear() {
- // our state is per-docsenum, so this makes no sense.
- // its best not to clear, in case a wrapped enum has a per-doc attribute or something
- // and is calling clearAttributes(), so they don't nuke the reuse information!
- }
-
- @Override
- public void copyTo(AttributeImpl target) {
- // this makes no sense for us, because our state is per-docsenum.
- // we don't want to copy any stuff over to another docsenum ever!
- }
- }
-}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.java
deleted file mode 100644
index 16974fbaf74..00000000000
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.java
+++ /dev/null
@@ -1,458 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.List;
-import java.util.ArrayList;
-
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.store.RAMOutputStream;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-// TODO: we now inline based on total TF of the term,
-// but it might be better to inline by "net bytes used"
-// so that a term that has only 1 posting but a huge
-// payload would not be inlined. Though this is
-// presumably rare in practice...
-
-/**
- * Writer for the pulsing format.
- * <p>
- * Wraps another postings implementation and decides
- * (based on total number of occurrences), whether a terms
- * postings should be inlined into the term dictionary,
- * or passed through to the wrapped writer.
- *
- * @lucene.experimental */
-public final class TempPulsingPostingsWriter extends TempPostingsWriterBase {
-
- final static String CODEC = "TempPulsedPostingsWriter";
-
- // recording field summary
- final static String SUMMARY_EXTENSION = "smy";
-
- // To add a new version, increment from the last one, and
- // change VERSION_CURRENT to point to your new version:
- final static int VERSION_START = 0;
-
- final static int VERSION_META_ARRAY = 1;
-
- final static int VERSION_CURRENT = VERSION_META_ARRAY;
-
- private SegmentWriteState segmentState;
- private IndexOutput termsOut;
-
- private List<FieldMetaData> fields;
-
- private IndexOptions indexOptions;
- private boolean storePayloads;
-
- // information for wrapped PF, in current field
- private int longsSize;
- private long[] longs;
- boolean absolute;
-
- private static class PulsingTermState extends BlockTermState {
- private byte[] bytes;
- private BlockTermState wrappedState;
- @Override
- public String toString() {
- if (bytes != null) {
- return "inlined";
- } else {
- return "not inlined wrapped=" + wrappedState;
- }
- }
- }
-
- // one entry per position
- private final Position[] pending;
- private int pendingCount = 0; // -1 once we've hit too many positions
- private Position currentDoc; // first Position entry of current doc
-
- private static final class Position {
- BytesRef payload;
- int termFreq; // only incremented on first position for a given doc
- int pos;
- int docID;
- int startOffset;
- int endOffset;
- }
-
- private static final class FieldMetaData {
- int fieldNumber;
- int longsSize;
- FieldMetaData(int number, int size) {
- fieldNumber = number;
- longsSize = size;
- }
- }
-
- // TODO: -- lazy init this? ie, if every single term
- // was inlined (eg for a "primary key" field) then we
- // never need to use this fallback? Fallback writer for
- // non-inlined terms:
- final TempPostingsWriterBase wrappedPostingsWriter;
-
- /** If the total number of positions (summed across all docs
- * for this term) is <= maxPositions, then the postings are
- * inlined into terms dict */
- public TempPulsingPostingsWriter(SegmentWriteState state, int maxPositions, TempPostingsWriterBase wrappedPostingsWriter) {
-
- pending = new Position[maxPositions];
- for(int i=0;i<maxPositions;i++) {
- pending[i] = new Position();
- }
- fields = new ArrayList<FieldMetaData>();
-
- // We simply wrap another postings writer, but only call
- // on it when tot positions is >= the cutoff:
- this.wrappedPostingsWriter = wrappedPostingsWriter;
- this.segmentState = state;
- }
-
- @Override
- public void init(IndexOutput termsOut) throws IOException {
- this.termsOut = termsOut;
- CodecUtil.writeHeader(termsOut, CODEC, VERSION_CURRENT);
- termsOut.writeVInt(pending.length); // encode maxPositions in header
- wrappedPostingsWriter.init(termsOut);
- }
-
- @Override
- public BlockTermState newTermState() throws IOException {
- PulsingTermState state = new PulsingTermState();
- state.wrappedState = wrappedPostingsWriter.newTermState();
- return state;
- }
-
- @Override
- public void startTerm() {
- //if (DEBUG) System.out.println("PW startTerm");
- assert pendingCount == 0;
- }
-
- // TODO: -- should we NOT reuse across fields? would
- // be cleaner
-
- // Currently, this instance is re-used across fields, so
- // our parent calls setField whenever the field changes
- @Override
- public int setField(FieldInfo fieldInfo) {
- this.indexOptions = fieldInfo.getIndexOptions();
- //if (DEBUG) System.out.println("PW field=" + fieldInfo.name + " indexOptions=" + indexOptions);
- storePayloads = fieldInfo.hasPayloads();
- absolute = false;
- longsSize = wrappedPostingsWriter.setField(fieldInfo);
- longs = new long[longsSize];
- fields.add(new FieldMetaData(fieldInfo.number, longsSize));
- return 0;
- //DEBUG = BlockTreeTermsWriter.DEBUG;
- }
-
- private boolean DEBUG;
-
- @Override
- public void startDoc(int docID, int termDocFreq) throws IOException {
- assert docID >= 0: "got docID=" + docID;
-
- /*
- if (termID != -1) {
- if (docID == 0) {
- baseDocID = termID;
- } else if (baseDocID + docID != termID) {
- throw new RuntimeException("WRITE: baseDocID=" + baseDocID + " docID=" + docID + " termID=" + termID);
- }
- }
- */
-
- //if (DEBUG) System.out.println("PW doc=" + docID);
-
- if (pendingCount == pending.length) {
- push();
- //if (DEBUG) System.out.println("PW: wrapped.finishDoc");
- wrappedPostingsWriter.finishDoc();
- }
-
- if (pendingCount != -1) {
- assert pendingCount < pending.length;
- currentDoc = pending[pendingCount];
- currentDoc.docID = docID;
- if (indexOptions == IndexOptions.DOCS_ONLY) {
- pendingCount++;
- } else if (indexOptions == IndexOptions.DOCS_AND_FREQS) {
- pendingCount++;
- currentDoc.termFreq = termDocFreq;
- } else {
- currentDoc.termFreq = termDocFreq;
- }
- } else {
- // We've already seen too many docs for this term --
- // just forward to our fallback writer
- wrappedPostingsWriter.startDoc(docID, termDocFreq);
- }
- }
-
- @Override
- public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {
-
- //if (DEBUG) System.out.println("PW pos=" + position + " payload=" + (payload == null ? "null" : payload.length + " bytes"));
- if (pendingCount == pending.length) {
- push();
- }
-
- if (pendingCount == -1) {
- // We've already seen too many docs for this term --
- // just forward to our fallback writer
- wrappedPostingsWriter.addPosition(position, payload, startOffset, endOffset);
- } else {
- // buffer up
- final Position pos = pending[pendingCount++];
- pos.pos = position;
- pos.startOffset = startOffset;
- pos.endOffset = endOffset;
- pos.docID = currentDoc.docID;
- if (payload != null && payload.length > 0) {
- if (pos.payload == null) {
- pos.payload = BytesRef.deepCopyOf(payload);
- } else {
- pos.payload.copyBytes(payload);
- }
- } else if (pos.payload != null) {
- pos.payload.length = 0;
- }
- }
- }
-
- @Override
- public void finishDoc() throws IOException {
- // if (DEBUG) System.out.println("PW finishDoc");
- if (pendingCount == -1) {
- wrappedPostingsWriter.finishDoc();
- }
- }
-
- private final RAMOutputStream buffer = new RAMOutputStream();
-
- // private int baseDocID;
-
- /** Called when we are done adding docs to this term */
- @Override
- public void finishTerm(BlockTermState _state) throws IOException {
- PulsingTermState state = (PulsingTermState) _state;
-
- // if (DEBUG) System.out.println("PW finishTerm docCount=" + stats.docFreq + " pendingCount=" + pendingCount + " pendingTerms.size()=" + pendingTerms.size());
-
- assert pendingCount > 0 || pendingCount == -1;
-
- if (pendingCount == -1) {
- state.wrappedState.docFreq = state.docFreq;
- state.wrappedState.totalTermFreq = state.totalTermFreq;
- state.bytes = null;
- wrappedPostingsWriter.finishTerm(state.wrappedState);
- } else {
- // There were few enough total occurrences for this
- // term, so we fully inline our postings data into
- // terms dict, now:
-
- // TODO: it'd be better to share this encoding logic
- // in some inner codec that knows how to write a
- // single doc / single position, etc. This way if a
- // given codec wants to store other interesting
- // stuff, it could use this pulsing codec to do so
-
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
- int lastDocID = 0;
- int pendingIDX = 0;
- int lastPayloadLength = -1;
- int lastOffsetLength = -1;
- while(pendingIDX < pendingCount) {
- final Position doc = pending[pendingIDX];
-
- final int delta = doc.docID - lastDocID;
- lastDocID = doc.docID;
-
- // if (DEBUG) System.out.println(" write doc=" + doc.docID + " freq=" + doc.termFreq);
-
- if (doc.termFreq == 1) {
- buffer.writeVInt((delta<<1)|1);
- } else {
- buffer.writeVInt(delta<<1);
- buffer.writeVInt(doc.termFreq);
- }
-
- int lastPos = 0;
- int lastOffset = 0;
- for(int posIDX=0;posIDX<doc.termFreq;posIDX++) {
- final Position pos = pending[pendingIDX++];
- assert pos.docID == doc.docID;
- final int posDelta = pos.pos - lastPos;
- lastPos = pos.pos;
- // if (DEBUG) System.out.println(" write pos=" + pos.pos);
- final int payloadLength = pos.payload == null ? 0 : pos.payload.length;
- if (storePayloads) {
- if (payloadLength != lastPayloadLength) {
- buffer.writeVInt((posDelta << 1)|1);
- buffer.writeVInt(payloadLength);
- lastPayloadLength = payloadLength;
- } else {
- buffer.writeVInt(posDelta << 1);
- }
- } else {
- buffer.writeVInt(posDelta);
- }
-
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) {
- //System.out.println("write=" + pos.startOffset + "," + pos.endOffset);
- int offsetDelta = pos.startOffset - lastOffset;
- int offsetLength = pos.endOffset - pos.startOffset;
- if (offsetLength != lastOffsetLength) {
- buffer.writeVInt(offsetDelta << 1 | 1);
- buffer.writeVInt(offsetLength);
- } else {
- buffer.writeVInt(offsetDelta << 1);
- }
- lastOffset = pos.startOffset;
- lastOffsetLength = offsetLength;
- }
-
- if (payloadLength > 0) {
- assert storePayloads;
- buffer.writeBytes(pos.payload.bytes, 0, pos.payload.length);
- }
- }
- }
- } else if (indexOptions == IndexOptions.DOCS_AND_FREQS) {
- int lastDocID = 0;
- for(int posIDX=0;posIDX<pendingCount;posIDX++) {
- final Position doc = pending[posIDX];
- final int delta = doc.docID - lastDocID;
- assert doc.termFreq != 0;
- if (doc.termFreq == 1) {
- buffer.writeVInt((delta<<1)|1);
- } else {
- buffer.writeVInt(delta<<1);
- buffer.writeVInt(doc.termFreq);
- }
- lastDocID = doc.docID;
- }
- } else if (indexOptions == IndexOptions.DOCS_ONLY) {
- int lastDocID = 0;
- for(int posIDX=0;posIDX<pendingCount;posIDX++) {
- final Position doc = pending[posIDX];
- buffer.writeVInt(doc.docID - lastDocID);
- lastDocID = doc.docID;
- }
- }
-
- state.bytes = new byte[(int) buffer.getFilePointer()];
- buffer.writeTo(state.bytes, 0);
- buffer.reset();
- }
- pendingCount = 0;
- }
-
- @Override
- public void encodeTerm(long[] empty, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
- PulsingTermState state = (PulsingTermState)_state;
- assert empty.length == 0;
- this.absolute = this.absolute || absolute;
- if (state.bytes == null) {
- wrappedPostingsWriter.encodeTerm(longs, buffer, fieldInfo, state.wrappedState, this.absolute);
- for (int i = 0; i < longsSize; i++) {
- out.writeVLong(longs[i]);
- }
- buffer.writeTo(out);
- buffer.reset();
- this.absolute = false;
- } else {
- out.writeVInt(state.bytes.length);
- out.writeBytes(state.bytes, 0, state.bytes.length);
- this.absolute = this.absolute || absolute;
- }
- }
-
- @Override
- public void close() throws IOException {
- wrappedPostingsWriter.close();
- if (wrappedPostingsWriter instanceof TempPulsingPostingsWriter ||
- VERSION_CURRENT < VERSION_META_ARRAY) {
- return;
- }
- String summaryFileName = IndexFileNames.segmentFileName(segmentState.segmentInfo.name, segmentState.segmentSuffix, SUMMARY_EXTENSION);
- IndexOutput out = null;
- try {
- out = segmentState.directory.createOutput(summaryFileName, segmentState.context);
- CodecUtil.writeHeader(out, CODEC, VERSION_CURRENT);
- out.writeVInt(fields.size());
- for (FieldMetaData field : fields) {
- out.writeVInt(field.fieldNumber);
- out.writeVInt(field.longsSize);
- }
- out.close();
- } finally {
- IOUtils.closeWhileHandlingException(out);
- }
- }
-
- // Pushes pending positions to the wrapped codec
- private void push() throws IOException {
- // if (DEBUG) System.out.println("PW now push @ " + pendingCount + " wrapped=" + wrappedPostingsWriter);
- assert pendingCount == pending.length;
-
- wrappedPostingsWriter.startTerm();
-
- // Flush all buffered docs
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
- Position doc = null;
- for(Position pos : pending) {
- if (doc == null) {
- doc = pos;
- // if (DEBUG) System.out.println("PW: wrapped.startDoc docID=" + doc.docID + " tf=" + doc.termFreq);
- wrappedPostingsWriter.startDoc(doc.docID, doc.termFreq);
- } else if (doc.docID != pos.docID) {
- assert pos.docID > doc.docID;
- // if (DEBUG) System.out.println("PW: wrapped.finishDoc");
- wrappedPostingsWriter.finishDoc();
- doc = pos;
- // if (DEBUG) System.out.println("PW: wrapped.startDoc docID=" + doc.docID + " tf=" + doc.termFreq);
- wrappedPostingsWriter.startDoc(doc.docID, doc.termFreq);
- }
- // if (DEBUG) System.out.println("PW: wrapped.addPos pos=" + pos.pos);
- wrappedPostingsWriter.addPosition(pos.pos, pos.payload, pos.startOffset, pos.endOffset);
- }
- //wrappedPostingsWriter.finishDoc();
- } else {
- for(Position doc : pending) {
- wrappedPostingsWriter.startDoc(doc.docID, indexOptions == IndexOptions.DOCS_ONLY ? 0 : doc.termFreq);
- }
- }
- pendingCount = -1;
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempTermOutputs.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempTermOutputs.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/temp/TempTermOutputs.java
rename to lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempTermOutputs.java
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.PostingsFormat
index fb2fe1c5fbb..5316caf9a37 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
@@ -18,8 +18,7 @@ org.apache.lucene.codecs.simpletext.SimpleTextPostingsFormat
org.apache.lucene.codecs.memory.MemoryPostingsFormat
org.apache.lucene.codecs.bloom.BloomFilteringPostingsFormat
org.apache.lucene.codecs.memory.DirectPostingsFormat
-org.apache.lucene.codecs.temp.TempBlockPostingsFormat
-org.apache.lucene.codecs.temp.TempPulsing41PostingsFormat
org.apache.lucene.codecs.temp.TempFSTPulsing41PostingsFormat
org.apache.lucene.codecs.temp.TempFSTOrdPulsing41PostingsFormat
-org.apache.lucene.codecs.temp.TempNestedPulsingPostingsFormat
+org.apache.lucene.codecs.temp.TempFSTPostingsFormat
+org.apache.lucene.codecs.temp.TempFSTOrdPostingsFormat
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/BlockTermState.java b/lucene/core/src/java/org/apache/lucene/codecs/BlockTermState.java
index fc9c145b157..e6d7a92ddaa 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/BlockTermState.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/BlockTermState.java
@@ -34,7 +34,7 @@ public class BlockTermState extends OrdTermState {
/** the term's ord in the current block */
public int termBlockOrd;
/** fp into the terms dict primary file (_X.tim) that holds this term */
- // nocommit: update BTR to nuke this
+ // TODO: update BTR to nuke this
public long blockFilePointer;
/** Sole constructor. (For invocation by subclass
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.java
deleted file mode 100644
index 4b3470fd18e..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.apache.lucene.codecs;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.index.SegmentReadState;
-
-/**
- * Provides a {@link PostingsReaderBase} and {@link
- * PostingsWriterBase}.
- *
- * @lucene.experimental */
-
-// TODO: find a better name; this defines the API that the
-// terms dict impls use to talk to a postings impl.
-// TermsDict + PostingsReader/WriterBase == PostingsConsumer/Producer
-
-// can we clean this up and do this some other way?
-// refactor some of these classes and use covariant return?
-public abstract class TempPostingsBaseFormat {
-
- /** Unique name that's used to retrieve this codec when
- * reading the index */
- public final String name;
-
- /** Sole constructor. */
- protected TempPostingsBaseFormat(String name) {
- this.name = name;
- }
-
- /** Creates the {@link PostingsReaderBase} for this
- * format. */
- public abstract TempPostingsReaderBase postingsReaderBase(SegmentReadState state) throws IOException;
-
- /** Creates the {@link PostingsWriterBase} for this
- * format. */
- public abstract TempPostingsWriterBase postingsWriterBase(SegmentWriteState state) throws IOException;
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsReaderBase.java b/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsReaderBase.java
deleted file mode 100644
index 201baf28043..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsReaderBase.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package org.apache.lucene.codecs;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-import java.io.Closeable;
-
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.store.DataInput;
-import org.apache.lucene.util.Bits;
-
-/** The core terms dictionaries (BlockTermsReader,
- * BlockTreeTermsReader) interact with a single instance
- * of this class to manage creation of {@link DocsEnum} and
- * {@link DocsAndPositionsEnum} instances. It provides an
- * IndexInput (termsIn) where this class may read any
- * previously stored data that it had written in its
- * corresponding {@link PostingsWriterBase} at indexing
- * time.
- * @lucene.experimental */
-
-// TODO: find a better name; this defines the API that the
-// terms dict impls use to talk to a postings impl.
-// TermsDict + PostingsReader/WriterBase == PostingsConsumer/Producer
-public abstract class TempPostingsReaderBase implements Closeable {
-
- /** Sole constructor. (For invocation by subclass
- * constructors, typically implicit.) */
- protected TempPostingsReaderBase() {
- }
-
- /** Performs any initialization, such as reading and
- * verifying the header from the provided terms
- * dictionary {@link IndexInput}. */
- public abstract void init(IndexInput termsIn) throws IOException;
-
- /** Return a newly created empty TermState */
- public abstract BlockTermState newTermState() throws IOException;
-
- /** Actually decode metadata for next term */
- public abstract void decodeTerm(long[] longs, DataInput in, FieldInfo fieldInfo, BlockTermState state, boolean absolute) throws IOException;
-
- /** Must fully consume state, since after this call that
- * TermState may be reused. */
- public abstract DocsEnum docs(FieldInfo fieldInfo, BlockTermState state, Bits skipDocs, DocsEnum reuse, int flags) throws IOException;
-
- /** Must fully consume state, since after this call that
- * TermState may be reused. */
- public abstract DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState state, Bits skipDocs, DocsAndPositionsEnum reuse,
- int flags) throws IOException;
-
- @Override
- public abstract void close() throws IOException;
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsWriterBase.java b/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsWriterBase.java
deleted file mode 100644
index 64571cabd65..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsWriterBase.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package org.apache.lucene.codecs;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-import java.io.Closeable;
-
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.index.FieldInfo;
-
-/**
- * Extension of {@link PostingsConsumer} to support pluggable term dictionaries.
- * <p>
- * This class contains additional hooks to interact with the provided
- * term dictionaries such as {@link BlockTreeTermsWriter}. If you want
- * to re-use an existing implementation and are only interested in
- * customizing the format of the postings list, extend this class
- * instead.
- *
- * @see PostingsReaderBase
- * @lucene.experimental
- */
-// TODO: find a better name; this defines the API that the
-// terms dict impls use to talk to a postings impl.
-// TermsDict + PostingsReader/WriterBase == PostingsConsumer/Producer
-public abstract class TempPostingsWriterBase extends PostingsConsumer implements Closeable {
-
- /** Sole constructor. (For invocation by subclass
- * constructors, typically implicit.) */
- protected TempPostingsWriterBase() {
- }
-
- /** Called once after startup, before any terms have been
- * added. Implementations typically write a header to
- * the provided {@code termsOut}. */
- public abstract void init(IndexOutput termsOut) throws IOException;
-
- /** Return a newly created empty TermState */
- public abstract BlockTermState newTermState() throws IOException;
-
- /** Start a new term. Note that a matching call to {@link
- * #finishTerm(long[], DataOutput, TermStats)} is done, only if the term has at least one
- * document. */
- public abstract void startTerm() throws IOException;
-
- /** Finishes the current term. The provided {@link
- * BlockTermState} contains the term's summary statistics,
- * and will holds metadata from PBF when returned*/
- public abstract void finishTerm(BlockTermState state) throws IOException;
-
- /**
- * Encode metadata as long[] and byte[]. {@code absolute} controls
- * whether current term is delta encoded according to latest term.
- */
- public abstract void encodeTerm(long[] longs, DataOutput out, FieldInfo fieldInfo, BlockTermState state, boolean absolute) throws IOException;
-
- /**
- * Return the fixed length of longs,
- * called when the writing switches to another field. */
- public abstract int setField(FieldInfo fieldInfo);
-
- @Override
- public abstract void close() throws IOException;
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java
index be1fe4df17a..00bb2dfab79 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene41/Lucene41PostingsReader.java
@@ -190,7 +190,6 @@ public final class Lucene41PostingsReader extends PostingsReaderBase {
final boolean fieldHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
final boolean fieldHasPayloads = fieldInfo.hasPayloads();
- // nocommit: use old version
if (absolute) {
termState.docStartFP = 0;
termState.posStartFP = 0;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreePostingsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreePostingsFormat.java
deleted file mode 100644
index 1374f967612..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreePostingsFormat.java
+++ /dev/null
@@ -1,449 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-
-/*
- * 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.CodecUtil;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.MultiLevelSkipListWriter;
-import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util.packed.PackedInts;
-
-/**
- * Lucene 4.1 postings format, which encodes postings in packed integer blocks
- * for fast decode.
- *
- * <p><b>NOTE</b>: this format is still experimental and
- * subject to change without backwards compatibility.
- *
- * <p>
- * Basic idea:
- * <ul>
- * <li>
- * <b>Packed Blocks and VInt Blocks</b>:
- * <p>In packed blocks, integers are encoded with the same bit width ({@link PackedInts packed format}):
- * the block size (i.e. number of integers inside block) is fixed (currently 128). Additionally blocks
- * that are all the same value are encoded in an optimized way.</p>
- * <p>In VInt blocks, integers are encoded as {@link DataOutput#writeVInt VInt}:
- * the block size is variable.</p>
- * </li>
- *
- * <li>
- * <b>Block structure</b>:
- * <p>When the postings are long enough, TempBlockTreePostingsFormat will try to encode most integer data
- * as a packed block.</p>
- * <p>Take a term with 259 documents as an example, the first 256 document ids are encoded as two packed
- * blocks, while the remaining 3 are encoded as one VInt block. </p>
- * <p>Different kinds of data are always encoded separately into different packed blocks, but may
- * possibly be interleaved into the same VInt block. </p>
- * <p>This strategy is applied to pairs:
- * &lt;document number, frequency&gt;,
- * &lt;position, payload length&gt;,
- * &lt;position, offset start, offset length&gt;, and
- * &lt;position, payload length, offsetstart, offset length&gt;.</p>
- * </li>
- *
- * <li>
- * <b>Skipdata settings</b>:
- * <p>The structure of skip table is quite similar to previous version of Lucene. Skip interval is the
- * same as block size, and each skip entry points to the beginning of each block. However, for
- * the first block, skip data is omitted.</p>
- * </li>
- *
- * <li>
- * <b>Positions, Payloads, and Offsets</b>:
- * <p>A position is an integer indicating where the term occurs within one document.
- * A payload is a blob of metadata associated with current position.
- * An offset is a pair of integers indicating the tokenized start/end offsets for given term
- * in current position: it is essentially a specialized payload. </p>
- * <p>When payloads and offsets are not omitted, numPositions==numPayloads==numOffsets (assuming a
- * null payload contributes one count). As mentioned in block structure, it is possible to encode
- * these three either combined or separately.
- * <p>In all cases, payloads and offsets are stored together. When encoded as a packed block,
- * position data is separated out as .pos, while payloads and offsets are encoded in .pay (payload
- * metadata will also be stored directly in .pay). When encoded as VInt blocks, all these three are
- * stored interleaved into the .pos (so is payload metadata).</p>
- * <p>With this strategy, the majority of payload and offset data will be outside .pos file.
- * So for queries that require only position data, running on a full index with payloads and offsets,
- * this reduces disk pre-fetches.</p>
- * </li>
- * </ul>
- * </p>
- *
- * <p>
- * Files and detailed format:
- * <ul>
- * <li><tt>.tim</tt>: <a href="#Termdictionary">Term Dictionary</a></li>
- * <li><tt>.tip</tt>: <a href="#Termindex">Term Index</a></li>
- * <li><tt>.doc</tt>: <a href="#Frequencies">Frequencies and Skip Data</a></li>
- * <li><tt>.pos</tt>: <a href="#Positions">Positions</a></li>
- * <li><tt>.pay</tt>: <a href="#Payloads">Payloads and Offsets</a></li>
- * </ul>
- * </p>
- *
- * <a name="Termdictionary" id="Termdictionary"></a>
- * <dl>
- * <dd>
- * <b>Term Dictionary</b>
- *
- * <p>The .tim file contains the list of terms in each
- * field along with per-term statistics (such as docfreq)
- * and pointers to the frequencies, positions, payload and
- * skip data in the .doc, .pos, and .pay files.
- * See {@link TempBlockTreeTermsWriter} for more details on the format.
- * </p>
- *
- * <p>NOTE: The term dictionary can plug into different postings implementations:
- * the postings writer/reader are actually responsible for encoding
- * and decoding the Postings Metadata and Term Metadata sections described here:</p>
- *
- * <ul>
- * <li>Postings Metadata --&gt; Header, PackedBlockSize</li>
- * <li>Term Metadata --&gt; (DocFPDelta|SingletonDocID), PosFPDelta?, PosVIntBlockFPDelta?, PayFPDelta?,
- * SkipFPDelta?</li>
- * <li>Header, --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>PackedBlockSize, SingletonDocID --&gt; {@link DataOutput#writeVInt VInt}</li>
- * <li>DocFPDelta, PosFPDelta, PayFPDelta, PosVIntBlockFPDelta, SkipFPDelta --&gt; {@link DataOutput#writeVLong VLong}</li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>Header is a {@link CodecUtil#writeHeader CodecHeader} storing the version information
- * for the postings.</li>
- * <li>PackedBlockSize is the fixed block size for packed blocks. In packed block, bit width is
- * determined by the largest integer. Smaller block size result in smaller variance among width
- * of integers hence smaller indexes. Larger block size result in more efficient bulk i/o hence
- * better acceleration. This value should always be a multiple of 64, currently fixed as 128 as
- * a tradeoff. It is also the skip interval used to accelerate {@link DocsEnum#advance(int)}.
- * <li>DocFPDelta determines the position of this term's TermFreqs within the .doc file.
- * In particular, it is the difference of file offset between this term's
- * data and previous term's data (or zero, for the first term in the block).On disk it is
- * stored as the difference from previous value in sequence. </li>
- * <li>PosFPDelta determines the position of this term's TermPositions within the .pos file.
- * While PayFPDelta determines the position of this term's &lt;TermPayloads, TermOffsets?&gt; within
- * the .pay file. Similar to DocFPDelta, it is the difference between two file positions (or
- * neglected, for fields that omit payloads and offsets).</li>
- * <li>PosVIntBlockFPDelta determines the position of this term's last TermPosition in last pos packed
- * block within the .pos file. It is synonym for PayVIntBlockFPDelta or OffsetVIntBlockFPDelta.
- * This is actually used to indicate whether it is necessary to load following
- * payloads and offsets from .pos instead of .pay. Every time a new block of positions are to be
- * loaded, the PostingsReader will use this value to check whether current block is packed format
- * or VInt. When packed format, payloads and offsets are fetched from .pay, otherwise from .pos.
- * (this value is neglected when total number of positions i.e. totalTermFreq is less or equal
- * to PackedBlockSize).
- * <li>SkipFPDelta determines the position of this term's SkipData within the .doc
- * file. In particular, it is the length of the TermFreq data.
- * SkipDelta is only stored if DocFreq is not smaller than SkipMinimum
- * (i.e. 8 in TempBlockTreePostingsFormat).</li>
- * <li>SingletonDocID is an optimization when a term only appears in one document. In this case, instead
- * of writing a file pointer to the .doc file (DocFPDelta), and then a VIntBlock at that location, the
- * single document ID is written to the term dictionary.</li>
- * </ul>
- * </dd>
- * </dl>
- *
- * <a name="Termindex" id="Termindex"></a>
- * <dl>
- * <dd>
- * <b>Term Index</b>
- * <p>The .tip file contains an index into the term dictionary, so that it can be
- * accessed randomly. See {@link TempBlockTreeTermsWriter} for more details on the format.</p>
- * </dd>
- * </dl>
- *
- *
- * <a name="Frequencies" id="Frequencies"></a>
- * <dl>
- * <dd>
- * <b>Frequencies and Skip Data</b>
- *
- * <p>The .doc file contains the lists of documents which contain each term, along
- * with the frequency of the term in that document (except when frequencies are
- * omitted: {@link IndexOptions#DOCS_ONLY}). It also saves skip data to the beginning of
- * each packed or VInt block, when the length of document list is larger than packed block size.</p>
- *
- * <ul>
- * <li>docFile(.doc) --&gt; Header, &lt;TermFreqs, SkipData?&gt;<sup>TermCount</sup></li>
- * <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>TermFreqs --&gt; &lt;PackedBlock&gt; <sup>PackedDocBlockNum</sup>,
- * VIntBlock? </li>
- * <li>PackedBlock --&gt; PackedDocDeltaBlock, PackedFreqBlock?
- * <li>VIntBlock --&gt; &lt;DocDelta[, Freq?]&gt;<sup>DocFreq-PackedBlockSize*PackedDocBlockNum</sup>
- * <li>SkipData --&gt; &lt;&lt;SkipLevelLength, SkipLevel&gt;
- * <sup>NumSkipLevels-1</sup>, SkipLevel&gt;, SkipDatum?</li>
- * <li>SkipLevel --&gt; &lt;SkipDatum&gt; <sup>TrimmedDocFreq/(PackedBlockSize^(Level + 1))</sup></li>
- * <li>SkipDatum --&gt; DocSkip, DocFPSkip, &lt;PosFPSkip, PosBlockOffset, PayLength?,
- * PayFPSkip?&gt;?, SkipChildLevelPointer?</li>
- * <li>PackedDocDeltaBlock, PackedFreqBlock --&gt; {@link PackedInts PackedInts}</li>
- * <li>DocDelta, Freq, DocSkip, DocFPSkip, PosFPSkip, PosBlockOffset, PayByteUpto, PayFPSkip
- * --&gt;
- * {@link DataOutput#writeVInt VInt}</li>
- * <li>SkipChildLevelPointer --&gt; {@link DataOutput#writeVLong VLong}</li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>PackedDocDeltaBlock is theoretically generated from two steps:
- * <ol>
- * <li>Calculate the difference between each document number and previous one,
- * and get a d-gaps list (for the first document, use absolute value); </li>
- * <li>For those d-gaps from first one to PackedDocBlockNum*PackedBlockSize<sup>th</sup>,
- * separately encode as packed blocks.</li>
- * </ol>
- * If frequencies are not omitted, PackedFreqBlock will be generated without d-gap step.
- * </li>
- * <li>VIntBlock stores remaining d-gaps (along with frequencies when possible) with a format
- * that encodes DocDelta and Freq:
- * <p>DocDelta: if frequencies are indexed, this determines both the document
- * number and the frequency. In particular, DocDelta/2 is the difference between
- * this document number and the previous document number (or zero when this is the
- * first document in a TermFreqs). When DocDelta is odd, the frequency is one.
- * When DocDelta is even, the frequency is read as another VInt. If frequencies
- * are omitted, DocDelta contains the gap (not multiplied by 2) between document
- * numbers and no frequency information is stored.</p>
- * <p>For example, the TermFreqs for a term which occurs once in document seven
- * and three times in document eleven, with frequencies indexed, would be the
- * following sequence of VInts:</p>
- * <p>15, 8, 3</p>
- * <p>If frequencies were omitted ({@link IndexOptions#DOCS_ONLY}) it would be this
- * sequence of VInts instead:</p>
- * <p>7,4</p>
- * </li>
- * <li>PackedDocBlockNum is the number of packed blocks for current term's docids or frequencies.
- * In particular, PackedDocBlockNum = floor(DocFreq/PackedBlockSize) </li>
- * <li>TrimmedDocFreq = DocFreq % PackedBlockSize == 0 ? DocFreq - 1 : DocFreq.
- * We use this trick since the definition of skip entry is a little different from base interface.
- * In {@link MultiLevelSkipListWriter}, skip data is assumed to be saved for
- * skipInterval<sup>th</sup>, 2*skipInterval<sup>th</sup> ... posting in the list. However,
- * in TempBlockTreePostingsFormat, the skip data is saved for skipInterval+1<sup>th</sup>,
- * 2*skipInterval+1<sup>th</sup> ... posting (skipInterval==PackedBlockSize in this case).
- * When DocFreq is multiple of PackedBlockSize, MultiLevelSkipListWriter will expect one
- * more skip data than TempSkipWriter. </li>
- * <li>SkipDatum is the metadata of one skip entry.
- * For the first block (no matter packed or VInt), it is omitted.</li>
- * <li>DocSkip records the document number of every PackedBlockSize<sup>th</sup> document number in
- * the postings (i.e. last document number in each packed block). On disk it is stored as the
- * difference from previous value in the sequence. </li>
- * <li>DocFPSkip records the file offsets of each block (excluding )posting at
- * PackedBlockSize+1<sup>th</sup>, 2*PackedBlockSize+1<sup>th</sup> ... , in DocFile.
- * The file offsets are relative to the start of current term's TermFreqs.
- * On disk it is also stored as the difference from previous SkipDatum in the sequence.</li>
- * <li>Since positions and payloads are also block encoded, the skip should skip to related block first,
- * then fetch the values according to in-block offset. PosFPSkip and PayFPSkip record the file
- * offsets of related block in .pos and .pay, respectively. While PosBlockOffset indicates
- * which value to fetch inside the related block (PayBlockOffset is unnecessary since it is always
- * equal to PosBlockOffset). Same as DocFPSkip, the file offsets are relative to the start of
- * current term's TermFreqs, and stored as a difference sequence.</li>
- * <li>PayByteUpto indicates the start offset of the current payload. It is equivalent to
- * the sum of the payload lengths in the current block up to PosBlockOffset</li>
- * </ul>
- * </dd>
- * </dl>
- *
- * <a name="Positions" id="Positions"></a>
- * <dl>
- * <dd>
- * <b>Positions</b>
- * <p>The .pos file contains the lists of positions that each term occurs at within documents. It also
- * sometimes stores part of payloads and offsets for speedup.</p>
- * <ul>
- * <li>PosFile(.pos) --&gt; Header, &lt;TermPositions&gt; <sup>TermCount</sup></li>
- * <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>TermPositions --&gt; &lt;PackedPosDeltaBlock&gt; <sup>PackedPosBlockNum</sup>,
- * VIntBlock? </li>
- * <li>VIntBlock --&gt; &lt;PositionDelta[, PayloadLength?], PayloadData?,
- * OffsetDelta?, OffsetLength?&gt;<sup>PosVIntCount</sup>
- * <li>PackedPosDeltaBlock --&gt; {@link PackedInts PackedInts}</li>
- * <li>PositionDelta, OffsetDelta, OffsetLength --&gt;
- * {@link DataOutput#writeVInt VInt}</li>
- * <li>PayloadData --&gt; {@link DataOutput#writeByte byte}<sup>PayLength</sup></li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>TermPositions are order by term (terms are implicit, from the term dictionary), and position
- * values for each term document pair are incremental, and ordered by document number.</li>
- * <li>PackedPosBlockNum is the number of packed blocks for current term's positions, payloads or offsets.
- * In particular, PackedPosBlockNum = floor(totalTermFreq/PackedBlockSize) </li>
- * <li>PosVIntCount is the number of positions encoded as VInt format. In particular,
- * PosVIntCount = totalTermFreq - PackedPosBlockNum*PackedBlockSize</li>
- * <li>The procedure how PackedPosDeltaBlock is generated is the same as PackedDocDeltaBlock
- * in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.</li>
- * <li>PositionDelta is, if payloads are disabled for the term's field, the
- * difference between the position of the current occurrence in the document and
- * the previous occurrence (or zero, if this is the first occurrence in this
- * document). If payloads are enabled for the term's field, then PositionDelta/2
- * is the difference between the current and the previous position. If payloads
- * are enabled and PositionDelta is odd, then PayloadLength is stored, indicating
- * the length of the payload at the current term position.</li>
- * <li>For example, the TermPositions for a term which occurs as the fourth term in
- * one document, and as the fifth and ninth term in a subsequent document, would
- * be the following sequence of VInts (payloads disabled):
- * <p>4, 5, 4</p></li>
- * <li>PayloadData is metadata associated with the current term position. If
- * PayloadLength is stored at the current position, then it indicates the length
- * of this payload. If PayloadLength is not stored, then this payload has the same
- * length as the payload at the previous position.</li>
- * <li>OffsetDelta/2 is the difference between this position's startOffset from the
- * previous occurrence (or zero, if this is the first occurrence in this document).
- * If OffsetDelta is odd, then the length (endOffset-startOffset) differs from the
- * previous occurrence and an OffsetLength follows. Offset data is only written for
- * {@link IndexOptions#DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS}.</li>
- * </ul>
- * </dd>
- * </dl>
- *
- * <a name="Payloads" id="Payloads"></a>
- * <dl>
- * <dd>
- * <b>Payloads and Offsets</b>
- * <p>The .pay file will store payloads and offsets associated with certain term-document positions.
- * Some payloads and offsets will be separated out into .pos file, for performance reasons.</p>
- * <ul>
- * <li>PayFile(.pay): --&gt; Header, &lt;TermPayloads, TermOffsets?&gt; <sup>TermCount</sup></li>
- * <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>TermPayloads --&gt; &lt;PackedPayLengthBlock, SumPayLength, PayData&gt; <sup>PackedPayBlockNum</sup>
- * <li>TermOffsets --&gt; &lt;PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock&gt; <sup>PackedPayBlockNum</sup>
- * <li>PackedPayLengthBlock, PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock --&gt; {@link PackedInts PackedInts}</li>
- * <li>SumPayLength --&gt; {@link DataOutput#writeVInt VInt}</li>
- * <li>PayData --&gt; {@link DataOutput#writeByte byte}<sup>SumPayLength</sup></li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>The order of TermPayloads/TermOffsets will be the same as TermPositions, note that part of
- * payload/offsets are stored in .pos.</li>
- * <li>The procedure how PackedPayLengthBlock and PackedOffsetLengthBlock are generated is the
- * same as PackedFreqBlock in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.
- * While PackedStartDeltaBlock follows a same procedure as PackedDocDeltaBlock.</li>
- * <li>PackedPayBlockNum is always equal to PackedPosBlockNum, for the same term. It is also synonym
- * for PackedOffsetBlockNum.</li>
- * <li>SumPayLength is the total length of payloads written within one block, should be the sum
- * of PayLengths in one packed block.</li>
- * <li>PayLength in PackedPayLengthBlock is the length of each payload associated with the current
- * position.</li>
- * </ul>
- * </dd>
- * </dl>
- * </p>
- *
- * @lucene.experimental
- */
-
-public final class TempBlockTreePostingsFormat extends PostingsFormat {
- /**
- * Filename extension for document number, frequencies, and skip data.
- * See chapter: <a href="#Frequencies">Frequencies and Skip Data</a>
- */
- public static final String DOC_EXTENSION = "doc";
-
- /**
- * Filename extension for positions.
- * See chapter: <a href="#Positions">Positions</a>
- */
- public static final String POS_EXTENSION = "pos";
-
- /**
- * Filename extension for payloads and offsets.
- * See chapter: <a href="#Payloads">Payloads and Offsets</a>
- */
- public static final String PAY_EXTENSION = "pay";
-
- 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 TempBlockTreePostingsFormat} with default
- * settings. */
- public TempBlockTreePostingsFormat() {
- this(TempBlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, TempBlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
- }
-
- /** Creates {@code TempBlockTreePostingsFormat} with custom
- * values for {@code minBlockSize} and {@code
- * maxBlockSize} passed to block terms dictionary.
- * @see TempBlockTreeTermsWriter#TempBlockTreeTermsWriter(SegmentWriteState,TempPostingsWriterBase,int,int) */
- public TempBlockTreePostingsFormat(int minTermBlockSize, int maxTermBlockSize) {
- super("TempBlockTree");
- 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 {
- TempPostingsWriterBase postingsWriter = new TempPostingsWriter(state);
-
- boolean success = false;
- try {
- FieldsConsumer ret = new TempBlockTreeTermsWriter(state,
- postingsWriter,
- minTermBlockSize,
- maxTermBlockSize);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(postingsWriter);
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postingsReader = new TempPostingsReader(state.directory,
- state.fieldInfos,
- state.segmentInfo,
- state.context,
- state.segmentSuffix);
- boolean success = false;
- try {
- FieldsProducer ret = new TempBlockTreeTermsReader(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/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsReader.java
deleted file mode 100644
index 903507bfc35..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsReader.java
+++ /dev/null
@@ -1,2979 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.TreeMap;
-import java.util.Arrays;
-
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-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.TermState;
-import org.apache.lucene.index.Terms;
-import org.apache.lucene.index.TermsEnum;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-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.IOUtils;
-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.automaton.Transition;
-import org.apache.lucene.util.fst.ByteSequenceOutputs;
-import org.apache.lucene.util.fst.FST;
-import org.apache.lucene.util.fst.Outputs;
-import org.apache.lucene.util.fst.Util;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.PostingsBaseFormat; // javadoc
-
-/** A block-based terms index and dictionary that assigns
- * terms to variable length blocks according to how they
- * share prefixes. The terms index is a prefix trie
- * whose leaves are term blocks. The advantage of this
- * approach is that seekExact is often able to
- * determine a term cannot exist without doing any IO, and
- * intersection with Automata is very fast. Note that this
- * terms dictionary has it's own fixed terms index (ie, it
- * does not support a pluggable terms index
- * implementation).
- *
- * <p><b>NOTE</b>: this terms dictionary supports
- * min/maxItemsPerBlock during indexing to control how
- * much memory the terms index uses.</p>
- *
- * <p>The data structure used by this implementation is very
- * similar to a burst trie
- * (http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.18.3499),
- * but with added logic to break up too-large blocks of all
- * terms sharing a given prefix into smaller ones.</p>
- *
- * <p>Use {@link org.apache.lucene.index.CheckIndex} with the <code>-verbose</code>
- * option to see summary statistics on the blocks in the
- * dictionary.
- *
- * See {@link TempBlockTreeTermsWriter}.
- *
- * @lucene.experimental
- */
-
-public class TempBlockTreeTermsReader extends FieldsProducer {
-
- // Open input to the main terms dict file (_X.tib)
- private final IndexInput in;
-
- //private static final boolean DEBUG = TempBlockTreeTermsWriter.DEBUG;
-
- // Reads the terms dict entries, to gather state to
- // produce DocsEnum on demand
- private final TempPostingsReaderBase postingsReader;
-
- private final TreeMap<String,FieldReader> fields = new TreeMap<String,FieldReader>();
-
- /** 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;
-
- private String segment;
-
- private final int version;
-
- /** Sole constructor. */
- public TempBlockTreeTermsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo info,
- TempPostingsReaderBase postingsReader, IOContext ioContext,
- String segmentSuffix)
- throws IOException {
-
- this.postingsReader = postingsReader;
-
- this.segment = info.name;
- in = dir.openInput(IndexFileNames.segmentFileName(segment, segmentSuffix, TempBlockTreeTermsWriter.TERMS_EXTENSION),
- ioContext);
-
- boolean success = false;
- IndexInput indexIn = null;
-
- try {
- version = readHeader(in);
- indexIn = dir.openInput(IndexFileNames.segmentFileName(segment, segmentSuffix, TempBlockTreeTermsWriter.TERMS_INDEX_EXTENSION),
- ioContext);
- int indexVersion = readIndexHeader(indexIn);
- if (indexVersion != version) {
- throw new CorruptIndexException("mixmatched version files: " + in + "=" + version + "," + indexIn + "=" + indexVersion);
- }
-
- // 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;
- final int numBytes = in.readVInt();
- final BytesRef rootCode = new BytesRef(new byte[numBytes]);
- in.readBytes(rootCode.bytes, 0, numBytes);
- rootCode.length = numBytes;
- final FieldInfo fieldInfo = fieldInfos.fieldInfo(field);
- assert fieldInfo != null: "field=" + field;
- 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();
- 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();
- FieldReader previous = fields.put(fieldInfo.name, new FieldReader(fieldInfo, numTerms, rootCode, sumTotalTermFreq, sumDocFreq, docCount, indexStartFP, longsSize, indexIn));
- 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);
- }
- }
- }
-
- /** Reads terms file header. */
- private int readHeader(IndexInput input) throws IOException {
- int version = CodecUtil.checkHeader(input, TempBlockTreeTermsWriter.TERMS_CODEC_NAME,
- TempBlockTreeTermsWriter.TERMS_VERSION_START,
- TempBlockTreeTermsWriter.TERMS_VERSION_CURRENT);
- if (version < TempBlockTreeTermsWriter.TERMS_VERSION_APPEND_ONLY) {
- dirOffset = input.readLong();
- }
- return version;
- }
-
- /** Reads index file header. */
- private int readIndexHeader(IndexInput input) throws IOException {
- int version = CodecUtil.checkHeader(input, TempBlockTreeTermsWriter.TERMS_INDEX_CODEC_NAME,
- TempBlockTreeTermsWriter.TERMS_INDEX_VERSION_START,
- TempBlockTreeTermsWriter.TERMS_INDEX_VERSION_CURRENT);
- if (version < TempBlockTreeTermsWriter.TERMS_INDEX_VERSION_APPEND_ONLY) {
- indexDirOffset = input.readLong();
- }
- return version;
- }
-
- /** Seek {@code input} to the directory offset. */
- private void seekDir(IndexInput input, long dirOffset)
- throws IOException {
- if (version >= TempBlockTreeTermsWriter.TERMS_INDEX_VERSION_APPEND_ONLY) {
- input.seek(input.length() - 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();
- }
- }
- }
-
- /**
- * Temp statistics for a single field
- * returned by {@link FieldReader#computeStats()}.
- */
- public static class Stats {
- /** How many nodes in the index FST. */
- public long indexNodeCount;
-
- /** How many arcs in the index FST. */
- public long indexArcCount;
-
- /** Byte size of the index. */
- public long indexNumBytes;
-
- /** Total number of terms in the field. */
- public long totalTermCount;
-
- /** Total number of bytes (sum of term lengths) across all terms in the field. */
- public long totalTermBytes;
-
- /** The number of normal (non-floor) blocks in the terms file. */
- public int nonFloorBlockCount;
-
- /** The number of floor blocks (meta-blocks larger than the
- * allowed {@code maxItemsPerBlock}) in the terms file. */
- public int floorBlockCount;
-
- /** The number of sub-blocks within the floor blocks. */
- public int floorSubBlockCount;
-
- /** The number of "internal" blocks (that have both
- * terms and sub-blocks). */
- public int mixedBlockCount;
-
- /** The number of "leaf" blocks (blocks that have only
- * terms). */
- public int termsOnlyBlockCount;
-
- /** The number of "internal" blocks that do not contain
- * terms (have only sub-blocks). */
- public int subBlocksOnlyBlockCount;
-
- /** Total number of blocks. */
- public int totalBlockCount;
-
- /** Number of blocks at each prefix depth. */
- public int[] blockCountByPrefixLen = new int[10];
- private int startBlockCount;
- private int endBlockCount;
-
- /** Total number of bytes used to store term suffixes. */
- public long totalBlockSuffixBytes;
-
- /** Total number of bytes used to store term stats (not
- * including what the {@link PostingsBaseFormat}
- * stores. */
- public long totalBlockStatsBytes;
-
- /** Total bytes stored by the {@link PostingsBaseFormat},
- * plus the other few vInts stored in the frame. */
- public long totalBlockOtherBytes;
-
- /** Segment name. */
- public final String segment;
-
- /** Field name. */
- public final String field;
-
- Stats(String segment, String field) {
- this.segment = segment;
- this.field = field;
- }
-
- void startBlock(FieldReader.SegmentTermsEnum.Frame frame, boolean isFloor) {
- totalBlockCount++;
- if (isFloor) {
- if (frame.fp == frame.fpOrig) {
- floorBlockCount++;
- }
- floorSubBlockCount++;
- } else {
- nonFloorBlockCount++;
- }
-
- if (blockCountByPrefixLen.length <= frame.prefix) {
- blockCountByPrefixLen = ArrayUtil.grow(blockCountByPrefixLen, 1+frame.prefix);
- }
- blockCountByPrefixLen[frame.prefix]++;
- startBlockCount++;
- totalBlockSuffixBytes += frame.suffixesReader.length();
- totalBlockStatsBytes += frame.statsReader.length();
- }
-
- void endBlock(FieldReader.SegmentTermsEnum.Frame frame) {
- final int termCount = frame.isLeafBlock ? frame.entCount : frame.state.termBlockOrd;
- final int subBlockCount = frame.entCount - termCount;
- totalTermCount += termCount;
- if (termCount != 0 && subBlockCount != 0) {
- mixedBlockCount++;
- } else if (termCount != 0) {
- termsOnlyBlockCount++;
- } else if (subBlockCount != 0) {
- subBlocksOnlyBlockCount++;
- } else {
- throw new IllegalStateException();
- }
- endBlockCount++;
- final long otherBytes = frame.fpEnd - frame.fp - frame.suffixesReader.length() - frame.statsReader.length();
- assert otherBytes > 0 : "otherBytes=" + otherBytes + " frame.fp=" + frame.fp + " frame.fpEnd=" + frame.fpEnd;
- totalBlockOtherBytes += otherBytes;
- }
-
- void term(BytesRef term) {
- totalTermBytes += term.length;
- }
-
- void finish() {
- assert startBlockCount == endBlockCount: "startBlockCount=" + startBlockCount + " endBlockCount=" + endBlockCount;
- assert totalBlockCount == floorSubBlockCount + nonFloorBlockCount: "floorSubBlockCount=" + floorSubBlockCount + " nonFloorBlockCount=" + nonFloorBlockCount + " totalBlockCount=" + totalBlockCount;
- assert totalBlockCount == mixedBlockCount + termsOnlyBlockCount + subBlocksOnlyBlockCount: "totalBlockCount=" + totalBlockCount + " mixedBlockCount=" + mixedBlockCount + " subBlocksOnlyBlockCount=" + subBlocksOnlyBlockCount + " termsOnlyBlockCount=" + termsOnlyBlockCount;
- }
-
- @Override
- public String toString() {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- PrintStream out;
- try {
- out = new PrintStream(bos, false, "UTF-8");
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
-
- out.println(" index FST:");
- out.println(" " + indexNodeCount + " nodes");
- out.println(" " + indexArcCount + " arcs");
- out.println(" " + indexNumBytes + " bytes");
- out.println(" terms:");
- out.println(" " + totalTermCount + " terms");
- out.println(" " + totalTermBytes + " bytes" + (totalTermCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalTermBytes)/totalTermCount) + " bytes/term)" : ""));
- out.println(" blocks:");
- out.println(" " + totalBlockCount + " blocks");
- out.println(" " + termsOnlyBlockCount + " terms-only blocks");
- out.println(" " + subBlocksOnlyBlockCount + " sub-block-only blocks");
- out.println(" " + mixedBlockCount + " mixed blocks");
- out.println(" " + floorBlockCount + " floor blocks");
- out.println(" " + (totalBlockCount-floorSubBlockCount) + " non-floor blocks");
- out.println(" " + floorSubBlockCount + " floor sub-blocks");
- out.println(" " + totalBlockSuffixBytes + " term suffix bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockSuffixBytes)/totalBlockCount) + " suffix-bytes/block)" : ""));
- out.println(" " + totalBlockStatsBytes + " term stats bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockStatsBytes)/totalBlockCount) + " stats-bytes/block)" : ""));
- out.println(" " + totalBlockOtherBytes + " other bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockOtherBytes)/totalBlockCount) + " other-bytes/block)" : ""));
- if (totalBlockCount != 0) {
- out.println(" by prefix length:");
- int total = 0;
- for(int prefix=0;prefix<blockCountByPrefixLen.length;prefix++) {
- final int blockCount = blockCountByPrefixLen[prefix];
- total += blockCount;
- if (blockCount != 0) {
- out.println(" " + String.format(Locale.ROOT, "%2d", prefix) + ": " + blockCount);
- }
- }
- assert totalBlockCount == total;
- }
-
- try {
- return bos.toString("UTF-8");
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
- }
- }
-
- final Outputs<BytesRef> fstOutputs = ByteSequenceOutputs.getSingleton();
- final BytesRef NO_OUTPUT = fstOutputs.getNoOutput();
-
- /** Temp's implementation of {@link Terms}. */
- public final class FieldReader extends Terms {
- final long numTerms;
- final FieldInfo fieldInfo;
- final long sumTotalTermFreq;
- final long sumDocFreq;
- final int docCount;
- final long indexStartFP;
- final long rootBlockFP;
- final BytesRef rootCode;
- final int longsSize;
-
- private final FST<BytesRef> index;
- //private boolean DEBUG;
-
- FieldReader(FieldInfo fieldInfo, long numTerms, BytesRef rootCode, long sumTotalTermFreq, long sumDocFreq, int docCount, long indexStartFP, int longsSize, IndexInput indexIn) throws IOException {
- assert numTerms > 0;
- this.fieldInfo = fieldInfo;
- //DEBUG = TempBlockTreeTermsReader.DEBUG && fieldInfo.name.equals("id");
- this.numTerms = numTerms;
- this.sumTotalTermFreq = sumTotalTermFreq;
- this.sumDocFreq = sumDocFreq;
- this.docCount = docCount;
- this.indexStartFP = indexStartFP;
- this.rootCode = rootCode;
- this.longsSize = longsSize;
- // if (DEBUG) {
- // System.out.println("BTTR: seg=" + segment + " field=" + fieldInfo.name + " rootBlockCode=" + rootCode + " divisor=" + indexDivisor);
- // }
-
- rootBlockFP = (new ByteArrayDataInput(rootCode.bytes, rootCode.offset, rootCode.length)).readVLong() >>> TempBlockTreeTermsWriter.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<BytesRef>(clone, ByteSequenceOutputs.getSingleton());
-
- /*
- if (false) {
- final String dotFileName = 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;
- }
- }
-
- /** For debugging -- used by CheckIndex too*/
- // TODO: maybe push this into Terms?
- public Stats computeStats() throws IOException {
- return new SegmentTermsEnum().computeBlockStats();
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- @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 SegmentTermsEnum();
- }
-
- @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 IntersectEnum(compiled, startTerm);
- }
-
- // NOTE: cannot seek!
- private final class IntersectEnum extends TermsEnum {
- private final IndexInput in;
-
- private Frame[] stack;
-
- @SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<BytesRef>[] arcs = new FST.Arc[5];
-
- private final RunAutomaton runAutomaton;
- private final CompiledAutomaton compiledAutomaton;
-
- private Frame currentFrame;
-
- private final BytesRef term = new BytesRef();
-
- private final FST.BytesReader fstReader;
-
- // TODO: can we share this with the frame in STE?
- private final class Frame {
- 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;
-
- // 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[] transitions;
- int curTransitionMax;
- int transitionIndex;
-
- FST.Arc<BytesRef> arc;
-
- final BlockTermState termState;
-
- // metadata buffer, holding monotonical values
- public long[] longs;
- // metadata buffer, holding general values
- public byte[] bytes;
- ByteArrayDataInput bytesReader;
-
- // Cumulative output so far
- BytesRef outputPrefix;
-
- private int startBytePos;
- private int suffix;
-
- public Frame(int ord) throws IOException {
- this.ord = ord;
- this.termState = postingsReader.newTermState();
- this.termState.totalTermFreq = -1;
- this.longs = new long[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;
- } else {
- nextFloorLabel = 256;
- }
- // if (DEBUG) System.out.println(" nextFloorLabel=" + (char) nextFloorLabel);
- } while (numFollowFloorBlocks != 0 && nextFloorLabel <= transitions[transitionIndex].getMin());
-
- load(null);
- }
-
- public void setState(int state) {
- this.state = state;
- transitionIndex = 0;
- transitions = compiledAutomaton.sortedTransitions[state];
- if (transitions.length != 0) {
- curTransitionMax = transitions[0].getMax();
- } else {
- curTransitionMax = -1;
- }
- }
-
- void load(BytesRef frameIndexData) 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 (frameIndexData != null && transitions.length != 0) {
- // 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);
- // Skip first long -- has redundant fp, hasTerms
- // flag, isFloor flag
- final long code = floorDataReader.readVLong();
- if ((code & TempBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR) != 0) {
- numFollowFloorBlocks = floorDataReader.readVInt();
- nextFloorLabel = floorDataReader.readByte() & 0xff;
- // 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 (!runAutomaton.isAccept(state)) {
- // Maybe skip floor blocks:
- while (numFollowFloorBlocks != 0 && nextFloorLabel <= transitions[0].getMin()) {
- 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;
- } else {
- nextFloorLabel = 256;
- }
- }
- }
- }
- }
-
- in.seek(fp);
- int code = in.readVInt();
- entCount = code >>> 1;
- assert entCount > 0;
- isLastInFloor = (code & 1) != 0;
-
- // term suffixes:
- code = 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)];
- }
- in.readBytes(suffixBytes, 0, numBytes);
- suffixesReader.reset(suffixBytes, 0, numBytes);
-
- // stats
- numBytes = in.readVInt();
- if (statBytes.length < numBytes) {
- statBytes = new byte[ArrayUtil.oversize(numBytes, 1)];
- }
- in.readBytes(statBytes, 0, numBytes);
- statsReader.reset(statBytes, 0, numBytes);
- metaDataUpto = 0;
-
- termState.termBlockOrd = 0;
- nextEnt = 0;
-
- // metadata
- numBytes = 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)];
- }
- 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 = 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();
- 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 (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- termState.totalTermFreq = termState.docFreq + statsReader.readVLong();
- }
- // metadata
- for (int i = 0; i < longsSize; i++) {
- longs[i] = bytesReader.readVLong();
- }
- postingsReader.decodeTerm(longs, bytesReader, fieldInfo, termState, absolute);
-
- metaDataUpto++;
- absolute = false;
- }
- termState.termBlockOrd = metaDataUpto;
- }
- }
-
- private BytesRef savedStartTerm;
-
- // TODO: in some cases we can filter by length? eg
- // regexp foo*bar must be at least length 6 bytes
- public IntersectEnum(CompiledAutomaton compiled, BytesRef startTerm) throws IOException {
- // if (DEBUG) {
- // System.out.println("\nintEnum.init seg=" + segment + " commonSuffix=" + brToString(compiled.commonSuffixRef));
- // }
- runAutomaton = compiled.runAutomaton;
- compiledAutomaton = compiled;
- in = TempBlockTreeTermsReader.this.in.clone();
- stack = new Frame[5];
- for(int idx=0;idx<stack.length;idx++) {
- stack[idx] = new Frame(idx);
- }
- for(int arcIdx=0;arcIdx<arcs.length;arcIdx++) {
- arcs[arcIdx] = new FST.Arc<BytesRef>();
- }
-
- if (index == null) {
- fstReader = null;
- } else {
- fstReader = 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<BytesRef> arc = 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 Frame f = stack[0];
- f.fp = f.fpOrig = rootBlockFP;
- f.prefix = 0;
- f.setState(runAutomaton.getInitialState());
- f.arc = arc;
- f.outputPrefix = arc.output;
- f.load(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 Frame getFrame(int ord) throws IOException {
- if (ord >= stack.length) {
- final Frame[] next = new Frame[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 Frame(stackOrd);
- }
- stack = next;
- }
- assert stack[ord].ord == ord;
- return stack[ord];
- }
-
- private FST.Arc<BytesRef> getArc(int ord) {
- if (ord >= arcs.length) {
- @SuppressWarnings({"rawtypes","unchecked"}) final FST.Arc<BytesRef>[] 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<BytesRef>();
- }
- arcs = next;
- }
- return arcs[ord];
- }
-
- private Frame pushFrame(int state) throws IOException {
- final Frame 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<BytesRef> arc = currentFrame.arc;
- int idx = currentFrame.prefix;
- assert currentFrame.suffix > 0;
- BytesRef 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 = index.findTargetArc(target, arc, getArc(1+idx), fstReader);
- assert arc != null;
- output = fstOutputs.add(output, arc.output);
- idx++;
- }
-
- f.arc = arc;
- f.outputPrefix = output;
- assert arc.isFinal();
- f.load(fstOutputs.add(output, arc.nextFinalOutput));
- return f;
- }
-
- @Override
- public BytesRef term() {
- return term;
- }
-
- @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 postingsReader.docs(fieldInfo, currentFrame.termState, skipDocs, reuse, flags);
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {
- if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
- // Positions were not indexed:
- return null;
- }
-
- currentFrame.decodeMetaData();
- return postingsReader.docsAndPositions(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<BytesRef> 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.transitions.length-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++;
- currentFrame.curTransitionMax = currentFrame.transitions[currentFrame.transitionIndex].getMax();
- //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 Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- @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();
- }
- }
-
- // Iterates through terms in this field
- private final class SegmentTermsEnum extends TermsEnum {
- private IndexInput in;
-
- private Frame[] stack;
- private final Frame staticFrame;
- private Frame currentFrame;
- private boolean termExists;
-
- 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<BytesRef>[] arcs =
- new FST.Arc[1];
-
- public SegmentTermsEnum() throws IOException {
- //if (DEBUG) System.out.println("BTTR.init seg=" + segment);
- stack = new Frame[0];
-
- // Used to hold seek by TermState, or cached seek
- staticFrame = new Frame(-1);
-
- if (index == null) {
- fstReader = null;
- } else {
- fstReader = 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<BytesRef>();
- }
-
- currentFrame = staticFrame;
- final FST.Arc<BytesRef> arc;
- if (index != null) {
- arc = index.getFirstArc(arcs[0]);
- // Empty string prefix must have an output in the index!
- assert arc.isFinal();
- } else {
- arc = null;
- }
- currentFrame = staticFrame;
- //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 = TempBlockTreeTermsReader.this.in.clone();
- }
- }
-
- /** Runs next() through the entire terms dict,
- * computing aggregate statistics. */
- public Stats computeBlockStats() throws IOException {
-
- Stats stats = new Stats(segment, fieldInfo.name);
- if (index != null) {
- stats.indexNodeCount = index.getNodeCount();
- stats.indexArcCount = index.getArcCount();
- stats.indexNumBytes = index.sizeInBytes();
- }
-
- currentFrame = staticFrame;
- FST.Arc<BytesRef> arc;
- if (index != null) {
- arc = index.getFirstArc(arcs[0]);
- // Empty string prefix must have an output in the index!
- assert arc.isFinal();
- } else {
- arc = null;
- }
-
- // Empty string prefix must have an output in the
- // index!
- currentFrame = pushFrame(arc, rootCode, 0);
- currentFrame.fpOrig = currentFrame.fp;
- currentFrame.loadBlock();
- validIndexPrefix = 0;
-
- stats.startBlock(currentFrame, !currentFrame.isLastInFloor);
-
- allTerms:
- while (true) {
-
- // Pop finished blocks
- while (currentFrame.nextEnt == currentFrame.entCount) {
- stats.endBlock(currentFrame);
- if (!currentFrame.isLastInFloor) {
- currentFrame.loadNextFloorBlock();
- stats.startBlock(currentFrame, true);
- } else {
- if (currentFrame.ord == 0) {
- break allTerms;
- }
- final long lastFP = currentFrame.fpOrig;
- currentFrame = stack[currentFrame.ord-1];
- assert lastFP == currentFrame.lastSubFP;
- // if (DEBUG) {
- // System.out.println(" reset validIndexPrefix=" + validIndexPrefix);
- // }
- }
- }
-
- while(true) {
- if (currentFrame.next()) {
- // Push to new block:
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
- currentFrame.fpOrig = currentFrame.fp;
- // 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();
- stats.startBlock(currentFrame, !currentFrame.isLastInFloor);
- } else {
- stats.term(term);
- break;
- }
- }
- }
-
- stats.finish();
-
- // Put root frame back:
- currentFrame = staticFrame;
- if (index != null) {
- arc = 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.rewind();
- currentFrame.loadBlock();
- validIndexPrefix = 0;
- term.length = 0;
-
- return stats;
- }
-
- private Frame getFrame(int ord) throws IOException {
- if (ord >= stack.length) {
- final Frame[] next = new Frame[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 Frame(stackOrd);
- }
- stack = next;
- }
- assert stack[ord].ord == ord;
- return stack[ord];
- }
-
- private FST.Arc<BytesRef> getArc(int ord) {
- if (ord >= arcs.length) {
- @SuppressWarnings({"rawtypes","unchecked"}) final FST.Arc<BytesRef>[] 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<BytesRef>();
- }
- arcs = next;
- }
- return arcs[ord];
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- // Pushes a frame we seek'd to
- Frame pushFrame(FST.Arc<BytesRef> arc, BytesRef frameData, int length) throws IOException {
- scratchReader.reset(frameData.bytes, frameData.offset, frameData.length);
- final long code = scratchReader.readVLong();
- final long fpSeek = code >>> TempBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS;
- final Frame f = getFrame(1+currentFrame.ord);
- f.hasTerms = (code & TempBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS) != 0;
- f.hasTermsOrig = f.hasTerms;
- f.isFloor = (code & TempBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR) != 0;
- if (f.isFloor) {
- f.setFloorData(scratchReader, frameData);
- }
- pushFrame(arc, fpSeek, length);
-
- return f;
- }
-
- // Pushes next'd frame or seek'd frame; we later
- // lazy-load the frame only when needed
- Frame pushFrame(FST.Arc<BytesRef> arc, long fp, int length) throws IOException {
- final Frame f = getFrame(1+currentFrame.ord);
- f.arc = arc;
- 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) {
- 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.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;
- }
-
- @Override
- public boolean seekExact(final BytesRef target) throws IOException {
-
- if (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=" + segment + " target=" + fieldInfo.name + ":" + brToString(target) + " current=" + brToString(term) + " (exists?=" + termExists + ") validIndexPrefix=" + validIndexPrefix);
- // printSeekState();
- // }
-
- FST.Arc<BytesRef> arc;
- int targetUpto;
- BytesRef output;
-
- targetBeforeCurrentLength = currentFrame.ord;
-
- if (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;
-
- Frame 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];
- //if (arc.label != (target.bytes[target.offset + targetUpto] & 0xFF)) {
- //System.out.println("FAIL: arc.label=" + (char) arc.label + " targetLabel=" + (char) (target.bytes[target.offset + targetUpto] & 0xFF));
- //}
- 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 != NO_OUTPUT) {
- output = fstOutputs.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 = 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 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 = 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, fstOutputs.add(output, arc.nextFinalOutput), 0);
- }
-
- // if (DEBUG) {
- // System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);
- // }
-
- while (targetUpto < target.length) {
-
- final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;
-
- final FST.Arc<BytesRef> nextArc = 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 != NO_OUTPUT) {
- output = fstOutputs.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, fstOutputs.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 (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<BytesRef> arc;
- int targetUpto;
- BytesRef output;
-
- targetBeforeCurrentLength = currentFrame.ord;
-
- if (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;
-
- Frame 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 != NO_OUTPUT) {
- output = fstOutputs.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 = 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, fstOutputs.add(output, arc.nextFinalOutput), 0);
- }
-
- //if (DEBUG) {
- //System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord+1=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);
- //}
-
- while (targetUpto < target.length) {
-
- final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;
-
- final FST.Arc<BytesRef> nextArc = 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 != NO_OUTPUT) {
- output = fstOutputs.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, fstOutputs.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) {
- Frame 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=" + prefix + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<TempBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? TempBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? TempBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd());
- } else {
- out.println(" frame " + (isSeekFrame ? "(seek, loaded)" : "(next, loaded)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + prefix + " nextEnt=" + f.nextEnt + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<TempBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? TempBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? TempBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " lastSubFP=" + f.lastSubFP + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd());
- }
- if (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");
- }
- BytesRef output = Util.get(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, output.offset, output.length);
- final long codeOrig = reader.readVLong();
- final long code = (f.fp << TempBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) | (f.hasTerms ? TempBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) | (f.isFloor ? TempBlockTreeTermsWriter.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<BytesRef> arc;
- if (index != null) {
- arc = 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();
- }
-
- 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) {
- // 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;
- 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) {
- if (currentFrame.next()) {
- // Push to new block:
- //if (DEBUG) System.out.println(" push frame");
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
- // 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);
- return term;
- }
- }
- }
-
- @Override
- public BytesRef term() {
- assert !eof;
- return term;
- }
-
- @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 postingsReader.docs(fieldInfo, currentFrame.state, skipDocs, reuse, flags);
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {
- if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) {
- // Positions were not indexed:
- return null;
- }
-
- assert !eof;
- currentFrame.decodeMetaData();
- return postingsReader.docsAndPositions(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;
- currentFrame = staticFrame;
- currentFrame.state.copyFrom(otherState);
- term.copyBytes(target);
- currentFrame.metaDataUpto = currentFrame.getTermBlockOrd();
- assert currentFrame.metaDataUpto > 0;
- validIndexPrefix = 0;
- } else {
- // if (DEBUG) {
- // System.out.println(" skip seek: already on target state=" + currentFrame.state);
- // }
- }
- }
-
- @Override
- public TermState termState() throws IOException {
- assert !eof;
- currentFrame.decodeMetaData();
- TermState ts = currentFrame.state.clone();
- //if (DEBUG) System.out.println("BTTR.termState seg=" + segment + " state=" + ts);
- return ts;
- }
-
- @Override
- public void seekExact(long ord) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public long ord() {
- throw new UnsupportedOperationException();
- }
-
- // Not static -- references term, postingsReader,
- // fieldInfo, in
- private final class Frame {
- // Our index in stack[]:
- final int ord;
-
- boolean hasTerms;
- boolean hasTermsOrig;
- boolean isFloor;
-
- FST.Arc<BytesRef> 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;
-
- // 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;
-
- int nextFloorLabel;
- 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 monotonical values
- public long[] longs;
- // metadata buffer, holding general values
- public byte[] bytes;
- ByteArrayDataInput bytesReader;
-
- public Frame(int ord) throws IOException {
- this.ord = ord;
- this.state = postingsReader.newTermState();
- this.state.totalTermFreq = -1;
- this.longs = new long[longsSize];
- }
-
- public void setFloorData(ByteArrayDataInput in, BytesRef source) {
- final int numBytes = source.length - (in.getPosition() - source.offset);
- 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;
- //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;
- 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:
- initIndexInput();
-
- if (nextEnt != -1) {
- // Already loaded
- return;
- }
- //System.out.println("blc=" + blockLoadCount);
-
- in.seek(fp);
- int code = 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 = in.readVInt();
- isLeafBlock = (code & 1) != 0;
- int numBytes = code >>> 1;
- if (suffixBytes.length < numBytes) {
- suffixBytes = new byte[ArrayUtil.oversize(numBytes, 1)];
- }
- 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 = in.readVInt();
- if (statBytes.length < numBytes) {
- statBytes = new byte[ArrayUtil.oversize(numBytes, 1)];
- }
- 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 = 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)];
- }
- 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 = in.getFilePointer();
- // if (DEBUG) {
- // System.out.println(" fpEnd=" + fpEnd);
- // }
- }
-
- void rewind() {
-
- // Force reload:
- fp = fpOrig;
- nextEnt = -1;
- hasTerms = hasTermsOrig;
- if (isFloor) {
- floorDataReader.rewind();
- numFollowFloorBlocks = floorDataReader.readVInt();
- nextFloorLabel = floorDataReader.readByte() & 0xff;
- }
-
- /*
- //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;
- nextEnt++;
- suffix = suffixesReader.readVInt();
- startBytePos = suffixesReader.getPosition();
- term.length = prefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- suffixesReader.readBytes(term.bytes, prefix, suffix);
- // A normal term
- 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();
- term.length = prefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- suffixesReader.readBytes(term.bytes, prefix, suffix);
- if ((code & 1) == 0) {
- // A normal term
- termExists = true;
- subCode = 0;
- state.termBlockOrd++;
- return false;
- } else {
- // A sub-block; make sub-FP absolute:
- termExists = false;
- subCode = 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=" + toHex(targetLabel) + " vs nextFloorLabel=" + toHex(nextFloorLabel) + " numFollowFloorBlocks=" + numFollowFloorBlocks);
- // }
-
- if (targetLabel < nextFloorLabel) {
- // if (DEBUG) {
- // System.out.println(" already on correct block");
- // }
- return;
- }
-
- assert numFollowFloorBlocks != 0;
-
- long newFP = fpOrig;
- while (true) {
- final long code = floorDataReader.readVLong();
- newFP = fpOrig + (code >>> 1);
- hasTerms = (code & 1) != 0;
- // if (DEBUG) {
- // System.out.println(" label=" + toHex(nextFloorLabel) + " fp=" + newFP + " hasTerms?=" + hasTerms + " numFollowFloor=" + numFollowFloorBlocks);
- // }
-
- isLastInFloor = numFollowFloorBlocks == 1;
- numFollowFloorBlocks--;
-
- if (isLastInFloor) {
- nextFloorLabel = 256;
- // if (DEBUG) {
- // System.out.println(" stop! last block nextFloorLabel=" + toHex(nextFloorLabel));
- // }
- break;
- } else {
- nextFloorLabel = floorDataReader.readByte() & 0xff;
- if (targetLabel < nextFloorLabel) {
- // if (DEBUG) {
- // System.out.println(" stop! nextFloorLabel=" + toHex(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;
- fp = newFP;
- } else {
- // if (DEBUG) {
- // System.out.println(" stay on same fp=" + newFP);
- // }
- }
- }
-
- public void decodeMetaData() throws IOException {
-
- //if (DEBUG) System.out.println("\nBTTR.decodeMetadata seg=" + segment + " mdUpto=" + metaDataUpto + " vs termBlockOrd=" + state.termBlockOrd);
-
- // 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
- state.docFreq = statsReader.readVInt();
- if (fieldInfo.getIndexOptions() != IndexOptions.DOCS_ONLY) {
- state.totalTermFreq = state.docFreq + statsReader.readVLong();
- }
- // metadata
- for (int i = 0; i < longsSize; i++) {
- longs[i] = bytesReader.readVLong();
- }
- postingsReader.decodeTerm(longs, bytesReader, 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] != 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();
- //if (DEBUG) System.out.println(" subCode=" + subCode);
- if (targetSubCode == subCode) {
- //if (DEBUG) System.out.println(" match!");
- lastSubFP = subFP;
- return;
- }
- } else {
- state.termBlockOrd++;
- }
- }
- }
-
- // 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=" + brToString(target) + " term=" + brToString(term));
-
- assert nextEnt != -1;
-
- 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++;
-
- 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=" + 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 && !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):
- currentFrame = pushFrame(null, currentFrame.lastSubFP, termLen);
- currentFrame.loadBlock();
- while (currentFrame.next()) {
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
- 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 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=" + brToString(target) + " term=" + brToString(term));
-
- assert nextEnt != -1;
-
- if (nextEnt == entCount) {
- if (exactOnly) {
- fillTerm();
- 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));
- // }
-
- termExists = (code & 1) == 0;
- final int termLen = prefix + suffix;
- startBytePos = suffixesReader.getPosition();
- suffixesReader.skipBytes(suffix);
- if (termExists) {
- state.termBlockOrd++;
- subCode = 0;
- } else {
- subCode = 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 && !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):
- currentFrame = pushFrame(null, currentFrame.lastSubFP, termLen);
- currentFrame.loadBlock();
- while (currentFrame.next()) {
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
- 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 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;
- term.length = prefix + suffix;
- if (term.bytes.length < termLength) {
- term.grow(termLength);
- }
- System.arraycopy(suffixBytes, startBytePos, term.bytes, prefix, suffix);
- }
- }
- }
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsWriter.java
deleted file mode 100644
index 299d9fca118..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempBlockTreeTermsWriter.java
+++ /dev/null
@@ -1,1143 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.Comparator;
-import java.util.List;
-import java.util.Arrays;
-
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfos;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-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.IOUtils;
-import org.apache.lucene.util.IntsRef;
-import org.apache.lucene.util.fst.Builder;
-import org.apache.lucene.util.fst.ByteSequenceOutputs;
-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;
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.PostingsConsumer;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.TermsConsumer;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.codecs.CodecUtil;
-
-/*
- 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.
-*/
-
-/**
- * Block-based terms index and dictionary writer.
- * <p>
- * Writes terms dict and index, block-encoding (column
- * stride) each term's metadata for each set of terms
- * between two index terms.
- * <p>
- * Files:
- * <ul>
- * <li><tt>.tim</tt>: <a href="#Termdictionary">Term Dictionary</a></li>
- * <li><tt>.tip</tt>: <a href="#Termindex">Term Index</a></li>
- * </ul>
- * <p>
- * <a name="Termdictionary" id="Termdictionary"></a>
- * <h3>Term Dictionary</h3>
- *
- * <p>The .tim file contains the list of terms in each
- * field along with per-term statistics (such as docfreq)
- * and per-term metadata (typically pointers to the postings list
- * for that term in the inverted index).
- * </p>
- *
- * <p>The .tim is arranged in blocks: with blocks containing
- * a variable number of entries (by default 25-48), where
- * each entry is either a term or a reference to a
- * sub-block.</p>
- *
- * <p>NOTE: The term dictionary can plug into different postings implementations:
- * the postings writer/reader are actually responsible for encoding
- * and decoding the Postings Metadata and Term Metadata sections.</p>
- *
- * <ul>
- * <li>TermsDict (.tim) --&gt; Header, <i>Postings Header</i>, NodeBlock<sup>NumBlocks</sup>,
- * FieldSummary, DirOffset</li>
- * <li>NodeBlock --&gt; (OuterNode | InnerNode)</li>
- * <li>OuterNode --&gt; EntryCount, SuffixLength, Byte<sup>SuffixLength</sup>, StatsLength, &lt; TermStats &gt;<sup>EntryCount</sup>, MetaLength, &lt;<i>Term Metadata</i>&gt;<sup>EntryCount</sup></li>
- * <li>InnerNode --&gt; EntryCount, SuffixLength[,Sub?], Byte<sup>SuffixLength</sup>, StatsLength, &lt; TermStats ? &gt;<sup>EntryCount</sup>, MetaLength, &lt;<i>Term Metadata ? </i>&gt;<sup>EntryCount</sup></li>
- * <li>TermStats --&gt; DocFreq, TotalTermFreq </li>
- * <li>FieldSummary --&gt; NumFields, &lt;FieldNumber, NumTerms, RootCodeLength, Byte<sup>RootCodeLength</sup>,
- * SumDocFreq, DocCount&gt;<sup>NumFields</sup></li>
- * <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>DirOffset --&gt; {@link DataOutput#writeLong Uint64}</li>
- * <li>EntryCount,SuffixLength,StatsLength,DocFreq,MetaLength,NumFields,
- * FieldNumber,RootCodeLength,DocCount --&gt; {@link DataOutput#writeVInt VInt}</li>
- * <li>TotalTermFreq,NumTerms,SumTotalTermFreq,SumDocFreq --&gt;
- * {@link DataOutput#writeVLong VLong}</li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>Header is a {@link CodecUtil#writeHeader CodecHeader} storing the version information
- * for the BlockTree implementation.</li>
- * <li>DirOffset is a pointer to the FieldSummary section.</li>
- * <li>DocFreq is the count of documents which contain the term.</li>
- * <li>TotalTermFreq is the total number of occurrences of the term. This is encoded
- * as the difference between the total number of occurrences and the DocFreq.</li>
- * <li>FieldNumber is the fields number from {@link FieldInfos}. (.fnm)</li>
- * <li>NumTerms is the number of unique terms for the field.</li>
- * <li>RootCode points to the root block for the field.</li>
- * <li>SumDocFreq is the total number of postings, the number of term-document pairs across
- * the entire field.</li>
- * <li>DocCount is the number of documents that have at least one posting for this field.</li>
- * <li>PostingsMetadata and TermMetadata are plugged into by the specific postings implementation:
- * these contain arbitrary per-file data (such as parameters or versioning information)
- * and per-term data (such as pointers to inverted files).</li>
- * <li>For inner nodes of the tree, every entry will steal one bit to mark whether it points
- * to child nodes(sub-block). If so, the corresponding TermStats and TermMetaData are omitted </li>
- * </ul>
- * <a name="Termindex" id="Termindex"></a>
- * <h3>Term Index</h3>
- * <p>The .tip file contains an index into the term dictionary, so that it can be
- * accessed randomly. The index is also used to determine
- * when a given term cannot exist on disk (in the .tim file), saving a disk seek.</p>
- * <ul>
- * <li>TermsIndex (.tip) --&gt; Header, FSTIndex<sup>NumFields</sup>
- * &lt;IndexStartFP&gt;<sup>NumFields</sup>, DirOffset</li>
- * <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
- * <li>DirOffset --&gt; {@link DataOutput#writeLong Uint64}</li>
- * <li>IndexStartFP --&gt; {@link DataOutput#writeVLong VLong}</li>
- * <!-- TODO: better describe FST output here -->
- * <li>FSTIndex --&gt; {@link FST FST&lt;byte[]&gt;}</li>
- * </ul>
- * <p>Notes:</p>
- * <ul>
- * <li>The .tip file contains a separate FST for each
- * field. The FST maps a term prefix to the on-disk
- * block that holds all terms starting with that
- * prefix. Each field's IndexStartFP points to its
- * FST.</li>
- * <li>DirOffset is a pointer to the start of the IndexStartFPs
- * for all fields</li>
- * <li>It's possible that an on-disk block would contain
- * too many terms (more than the allowed maximum
- * (default: 48)). When this happens, the block is
- * sub-divided into new blocks (called "floor
- * blocks"), and then the output in the FST for the
- * block's prefix encodes the leading byte of each
- * sub-block, and its file pointer.
- * </ul>
- *
- * @see TempBlockTreeTermsReader
- * @lucene.experimental
- */
-
-public class TempBlockTreeTermsWriter extends FieldsConsumer {
-
- /** Suggested default value for the {@code
- * minItemsInBlock} parameter to {@link
- * #TempBlockTreeTermsWriter(SegmentWriteState,TempPostingsWriterBase,int,int)}. */
- public final static int DEFAULT_MIN_BLOCK_SIZE = 25;
-
- /** Suggested default value for the {@code
- * maxItemsInBlock} parameter to {@link
- * #TempBlockTreeTermsWriter(SegmentWriteState,TempPostingsWriterBase,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 = "tim";
- final static String TERMS_CODEC_NAME = "BLOCK_TREE_TERMS_DICT";
-
- /** Initial terms format. */
- public static final int TERMS_VERSION_START = 0;
-
- /** Append-only */
- public static final int TERMS_VERSION_APPEND_ONLY = 1;
-
- /** Current terms format. */
- public static final int TERMS_VERSION_CURRENT = TERMS_VERSION_APPEND_ONLY;
-
- /** Extension of terms index file */
- static final String TERMS_INDEX_EXTENSION = "tip";
- final static String TERMS_INDEX_CODEC_NAME = "BLOCK_TREE_TERMS_INDEX";
-
- /** Initial index format. */
- public static final int TERMS_INDEX_VERSION_START = 0;
-
- /** Append-only */
- public static final int TERMS_INDEX_VERSION_APPEND_ONLY = 1;
-
- /** Current index format. */
- public static final int TERMS_INDEX_VERSION_CURRENT = TERMS_INDEX_VERSION_APPEND_ONLY;
-
- private final IndexOutput out;
- private final IndexOutput indexOut;
- final int minItemsInBlock;
- final int maxItemsInBlock;
-
- final TempPostingsWriterBase postingsWriter;
- final FieldInfos fieldInfos;
- FieldInfo currentField;
-
- private static class FieldMetaData {
- public final FieldInfo fieldInfo;
- public final BytesRef 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 FieldMetaData(FieldInfo fieldInfo, BytesRef rootCode, long numTerms, long indexStartFP, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize) {
- 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;
- }
- }
-
- private final List<FieldMetaData> fields = new ArrayList<FieldMetaData>();
- // 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 TempBlockTreeTermsWriter(
- SegmentWriteState state,
- TempPostingsWriterBase 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);
- }
-
- 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;
- writeHeader(out);
-
- //DEBUG = state.segmentName.equals("_4a");
-
- final String termsIndexFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TERMS_INDEX_EXTENSION);
- indexOut = state.directory.createOutput(termsIndexFileName, state.context);
- writeIndexHeader(indexOut);
-
- currentField = null;
- this.postingsWriter = postingsWriter;
- // segment = state.segmentName;
-
- // 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;
- }
-
- /** Writes the terms file header. */
- private void writeHeader(IndexOutput out) throws IOException {
- CodecUtil.writeHeader(out, TERMS_CODEC_NAME, TERMS_VERSION_CURRENT);
- }
-
- /** Writes the index file header. */
- private void writeIndexHeader(IndexOutput out) throws IOException {
- CodecUtil.writeHeader(out, TERMS_INDEX_CODEC_NAME, TERMS_INDEX_VERSION_CURRENT);
- }
-
- /** Writes the terms file trailer. */
- private void writeTrailer(IndexOutput out, long dirStart) throws IOException {
- out.writeLong(dirStart);
- }
-
- /** Writes the index file trailer. */
- private void writeIndexTrailer(IndexOutput indexOut, long dirStart) throws IOException {
- indexOut.writeLong(dirStart);
- }
-
- @Override
- public TermsConsumer addField(FieldInfo field) throws IOException {
- //DEBUG = field.name.equals("id");
- //if (DEBUG) System.out.println("\nBTTW.addField seg=" + segment + " field=" + field.name);
- assert currentField == null || currentField.name.compareTo(field.name) < 0;
- currentField = field;
- return new TermsWriter(field);
- }
-
- 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 PendingBlock extends PendingEntry {
- public final BytesRef prefix;
- public final long fp;
- public FST<BytesRef> index;
- public List<FST<BytesRef>> subIndices;
- public final boolean hasTerms;
- public final boolean isFloor;
- public final int floorLeadByte;
- private final IntsRef scratchIntsRef = new IntsRef();
-
- public PendingBlock(BytesRef prefix, long fp, boolean hasTerms, boolean isFloor, int floorLeadByte, List<FST<BytesRef>> subIndices) {
- super(false);
- this.prefix = prefix;
- this.fp = fp;
- this.hasTerms = hasTerms;
- 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
- 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);
- assert sub.fp > fp;
- scratchBytes.writeVLong((sub.fp - fp) << 1 | (sub.hasTerms ? 1 : 0));
- }
- }
-
- final ByteSequenceOutputs outputs = ByteSequenceOutputs.getSingleton();
- final Builder<BytesRef> indexBuilder = new Builder<BytesRef>(FST.INPUT_TYPE.BYTE1,
- 0, 0, true, false, Integer.MAX_VALUE,
- 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;
- scratchBytes.writeTo(bytes, 0);
- indexBuilder.add(Util.toIntsRef(prefix, scratchIntsRef), new BytesRef(bytes, 0, bytes.length));
- scratchBytes.reset();
-
- // Copy over index for all sub-blocks
-
- if (subIndices != null) {
- for(FST<BytesRef> subIndex : subIndices) {
- append(indexBuilder, subIndex);
- }
- }
-
- if (floorBlocks != null) {
- for (PendingBlock sub : floorBlocks) {
- if (sub.subIndices != null) {
- for(FST<BytesRef> subIndex : sub.subIndices) {
- append(indexBuilder, subIndex);
- }
- }
- sub.subIndices = null;
- }
- }
-
- 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<BytesRef> builder, FST<BytesRef> subIndex) throws IOException {
- final BytesRefFSTEnum<BytesRef> subIndexEnum = new BytesRefFSTEnum<BytesRef>(subIndex);
- BytesRefFSTEnum.InputOutput<BytesRef> indexEnt;
- while((indexEnt = subIndexEnum.next()) != null) {
- //if (DEBUG) {
- // System.out.println(" add sub=" + indexEnt.input + " " + indexEnt.input + " output=" + indexEnt.output);
- //}
- builder.add(Util.toIntsRef(indexEnt.input, scratchIntsRef), indexEnt.output);
- }
- }
- }
-
- final RAMOutputStream scratchBytes = new RAMOutputStream();
-
- class TermsWriter extends TermsConsumer {
- private final FieldInfo fieldInfo;
- private final int longsSize;
- private long numTerms;
- long sumTotalTermFreq;
- long sumDocFreq;
- int docCount;
- 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<PendingEntry>();
-
- // 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<Object>(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 (prefixLength == 0 || 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=" + 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>();
- 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;
- }
-
- // 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();
-
- final BytesRef prefix = new BytesRef(indexPrefixLength);
- for(int m=0;m<indexPrefixLength;m++) {
- prefix.bytes[m] = (byte) prevTerm.ints[m];
- }
- prefix.length = indexPrefixLength;
-
- // 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;
- }
-
- final List<FST<BytesRef>> subIndices;
-
- int termCount;
-
- long[] longs = new long[longsSize];
- boolean absolute = true;
-
- 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(" write term suffix=" + 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);
- }
-
- // 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;
- } else {
- subIndices = new ArrayList<FST<BytesRef>>();
- termCount = 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(" write term suffix=" + suffixBytes);
- // }
- // 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++;
- } else {
- PendingBlock block = (PendingBlock) ent;
- final int suffix = block.prefix.length - prefixLength;
-
- assert suffix > 0;
-
- // For non-leaf block we borrow 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;
-
- // if (DEBUG) {
- // BytesRef suffixBytes = new BytesRef(suffix);
- // System.arraycopy(block.prefix.bytes, prefixLength, suffixBytes.bytes, 0, suffix);
- // suffixBytes.length = suffix;
- // System.out.println(" write sub-block suffix=" + toString(suffixBytes) + " subFP=" + block.fp + " subCode=" + (startFP-block.fp) + " floor=" + block.isFloor);
- // }
-
- suffixWriter.writeVLong(startFP - block.fp);
- subIndices.add(block.index);
- }
- }
-
- 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());
- 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, isFloor, floorLeadByte, subIndices);
- }
-
- TermsWriter(FieldInfo fieldInfo) {
- this.fieldInfo = fieldInfo;
-
- 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<Object>(FST.INPUT_TYPE.BYTE1,
- 0, 0, true,
- true, Integer.MAX_VALUE,
- noOutputs,
- new FindBlocks(), false,
- PackedInts.COMPACT,
- true, 15);
-
- this.longsSize = postingsWriter.setField(fieldInfo);
- }
-
- @Override
- public Comparator<BytesRef> getComparator() {
- return BytesRef.getUTF8SortedAsUnicodeComparator();
- }
-
- @Override
- public PostingsConsumer startTerm(BytesRef text) throws IOException {
- //if (DEBUG) System.out.println("\nBTTW.startTerm term=" + fieldInfo.name + ":" + toString(text) + " seg=" + segment);
- postingsWriter.startTerm();
- /*
- if (fieldInfo.name.equals("id")) {
- postingsWriter.termID = Integer.parseInt(text.utf8ToString());
- } else {
- postingsWriter.termID = -1;
- }
- */
- return postingsWriter;
- }
-
- private final IntsRef scratchIntsRef = new IntsRef();
-
- @Override
- public void finishTerm(BytesRef text, TermStats stats) throws IOException {
-
- assert stats.docFreq > 0;
- //if (DEBUG) System.out.println("BTTW.finishTerm term=" + fieldInfo.name + ":" + toString(text) + " seg=" + segment + " df=" + stats.docFreq);
-
- blockBuilder.add(Util.toIntsRef(text, scratchIntsRef), noOutputs.getNoOutput());
- BlockTermState state = postingsWriter.newTermState();
- state.docFreq = stats.docFreq;
- state.totalTermFreq = stats.totalTermFreq;
- postingsWriter.finishTerm(state);
-
- PendingTerm term = new PendingTerm(BytesRef.deepCopyOf(text), state);
- pending.add(term);
- numTerms++;
- }
-
- // Finishes all terms in this field
- @Override
- public void finish(long sumTotalTermFreq, long sumDocFreq, int docCount) 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;
-
- this.sumTotalTermFreq = sumTotalTermFreq;
- this.sumDocFreq = sumDocFreq;
- this.docCount = docCount;
-
- // 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,
- docCount,
- longsSize));
- } else {
- assert sumTotalTermFreq == 0 || fieldInfo.getIndexOptions() == IndexOptions.DOCS_ONLY && sumTotalTermFreq == -1;
- assert sumDocFreq == 0;
- assert docCount == 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 {
-
- IOException ioe = null;
- 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");
- out.writeVInt(field.fieldInfo.number);
- out.writeVLong(field.numTerms);
- out.writeVInt(field.rootCode.length);
- out.writeBytes(field.rootCode.bytes, field.rootCode.offset, field.rootCode.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);
- }
- writeTrailer(out, dirStart);
- writeIndexTrailer(indexOut, indexDirStart);
- } catch (IOException ioe2) {
- ioe = ioe2;
- } finally {
- IOUtils.closeWhileHandlingException(ioe, out, indexOut, postingsWriter);
- }
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.java
deleted file mode 100644
index 821313fc679..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-
-/**
- * Provides a {@link PostingsReaderBase} and {@link
- * PostingsWriterBase}.
- *
- * @lucene.experimental */
-
-// TODO: should these also be named / looked up via SPI?
-public final class TempPostingsBaseFormat extends org.apache.lucene.codecs.TempPostingsBaseFormat {
-
- /** Sole constructor. */
- public TempPostingsBaseFormat() {
- super("Temp");
- }
-
- @Override
- public TempPostingsReaderBase postingsReaderBase(SegmentReadState state) throws IOException {
- return new TempPostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
- }
-
- @Override
- public TempPostingsWriterBase postingsWriterBase(SegmentWriteState state) throws IOException {
- return new TempPostingsWriter(state);
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsReader.java
deleted file mode 100644
index 3b74eb37d4e..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsReader.java
+++ /dev/null
@@ -1,1559 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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 static org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat.BLOCK_SIZE;
-import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_DATA_SIZE;
-import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_ENCODED_SIZE;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.FieldInfos;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentInfo;
-import org.apache.lucene.index.TermState;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.DataInput;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-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.IOUtils;
-import org.apache.lucene.codecs.lucene41.ForUtil;
-import org.apache.lucene.codecs.lucene41.Lucene41SkipReader;
-
-
-/**
- * Concrete class that reads docId(maybe frq,pos,offset,payloads) list
- * with postings format.
- *
- * @see Lucene41SkipReader for details
- * @lucene.experimental
- */
-public final class TempPostingsReader extends TempPostingsReaderBase {
-
- private final IndexInput docIn;
- private final IndexInput posIn;
- private final IndexInput payIn;
-
- private final ForUtil forUtil;
-
- // public static boolean DEBUG = false;
-
- /** Sole constructor. */
- public TempPostingsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo segmentInfo, IOContext ioContext, String segmentSuffix) throws IOException {
- boolean success = false;
- IndexInput docIn = null;
- IndexInput posIn = null;
- IndexInput payIn = null;
- try {
- docIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempBlockTreePostingsFormat.DOC_EXTENSION),
- ioContext);
- CodecUtil.checkHeader(docIn,
- TempPostingsWriter.DOC_CODEC,
- TempPostingsWriter.VERSION_CURRENT,
- TempPostingsWriter.VERSION_CURRENT);
- forUtil = new ForUtil(docIn);
-
- if (fieldInfos.hasProx()) {
- posIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempBlockTreePostingsFormat.POS_EXTENSION),
- ioContext);
- CodecUtil.checkHeader(posIn,
- TempPostingsWriter.POS_CODEC,
- TempPostingsWriter.VERSION_CURRENT,
- TempPostingsWriter.VERSION_CURRENT);
-
- if (fieldInfos.hasPayloads() || fieldInfos.hasOffsets()) {
- payIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, TempBlockTreePostingsFormat.PAY_EXTENSION),
- ioContext);
- CodecUtil.checkHeader(payIn,
- TempPostingsWriter.PAY_CODEC,
- TempPostingsWriter.VERSION_CURRENT,
- TempPostingsWriter.VERSION_CURRENT);
- }
- }
-
- this.docIn = docIn;
- this.posIn = posIn;
- this.payIn = payIn;
- success = true;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docIn, posIn, payIn);
- }
- }
- }
-
- @Override
- public void init(IndexInput termsIn) throws IOException {
- // Make sure we are talking to the matching postings writer
- CodecUtil.checkHeader(termsIn,
- TempPostingsWriter.TERMS_CODEC,
- TempPostingsWriter.VERSION_CURRENT,
- TempPostingsWriter.VERSION_CURRENT);
- final int indexBlockSize = termsIn.readVInt();
- if (indexBlockSize != BLOCK_SIZE) {
- throw new IllegalStateException("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + BLOCK_SIZE + ")");
- }
- }
-
- /**
- * Read values that have been written using variable-length encoding instead of bit-packing.
- */
- static void readVIntBlock(IndexInput docIn, int[] docBuffer,
- int[] freqBuffer, int num, boolean indexHasFreq) throws IOException {
- if (indexHasFreq) {
- for(int i=0;i<num;i++) {
- final int code = docIn.readVInt();
- docBuffer[i] = code >>> 1;
- if ((code & 1) != 0) {
- freqBuffer[i] = 1;
- } else {
- freqBuffer[i] = docIn.readVInt();
- }
- }
- } else {
- for(int i=0;i<num;i++) {
- docBuffer[i] = docIn.readVInt();
- }
- }
- }
-
- // Must keep final because we do non-standard clone
- private final static class IntBlockTermState extends BlockTermState {
- long docStartFP;
- long posStartFP;
- long payStartFP;
- long skipOffset;
- long lastPosBlockOffset;
- // docid when there is a single pulsed posting, otherwise -1
- // freq is always implicitly totalTermFreq in this case.
- int singletonDocID;
-
- @Override
- public IntBlockTermState clone() {
- IntBlockTermState other = new IntBlockTermState();
- other.copyFrom(this);
- return other;
- }
-
- @Override
- public void copyFrom(TermState _other) {
- super.copyFrom(_other);
- IntBlockTermState other = (IntBlockTermState) _other;
- docStartFP = other.docStartFP;
- posStartFP = other.posStartFP;
- payStartFP = other.payStartFP;
- lastPosBlockOffset = other.lastPosBlockOffset;
- skipOffset = other.skipOffset;
- singletonDocID = other.singletonDocID;
- }
-
- @Override
- public String toString() {
- return super.toString() + " docStartFP=" + docStartFP + " posStartFP=" + posStartFP + " payStartFP=" + payStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;
- }
- }
-
- @Override
- public IntBlockTermState newTermState() {
- return new IntBlockTermState();
- }
-
- @Override
- public void close() throws IOException {
- IOUtils.close(docIn, posIn, payIn);
- }
-
- @Override
- public void decodeTerm(long[] longs, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute)
- throws IOException {
- final IntBlockTermState termState = (IntBlockTermState) _termState;
- final boolean fieldHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
- final boolean fieldHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- final boolean fieldHasPayloads = fieldInfo.hasPayloads();
-
- if (absolute) {
- termState.docStartFP = 0;
- termState.posStartFP = 0;
- termState.payStartFP = 0;
- }
- termState.docStartFP += longs[0];
- if (fieldHasPositions) {
- termState.posStartFP += longs[1];
- if (fieldHasOffsets || fieldHasPayloads) {
- termState.payStartFP += longs[2];
- }
- }
-
- if (termState.docFreq == 1) {
- termState.singletonDocID = in.readVInt();
- } else {
- termState.singletonDocID = -1;
- }
- if (fieldHasPositions) {
- if (termState.totalTermFreq > BLOCK_SIZE) {
- termState.lastPosBlockOffset = in.readVLong();
- } else {
- termState.lastPosBlockOffset = -1;
- }
- }
-
- if (termState.docFreq > BLOCK_SIZE) {
- termState.skipOffset = in.readVLong();
- } else {
- termState.skipOffset = -1;
- }
- }
-
- @Override
- public DocsEnum docs(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
- BlockDocsEnum docsEnum;
- if (reuse instanceof BlockDocsEnum) {
- docsEnum = (BlockDocsEnum) reuse;
- if (!docsEnum.canReuse(docIn, fieldInfo)) {
- docsEnum = new BlockDocsEnum(fieldInfo);
- }
- } else {
- docsEnum = new BlockDocsEnum(fieldInfo);
- }
- return docsEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
- }
-
- // TODO: specialize to liveDocs vs not
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs,
- DocsAndPositionsEnum reuse, int flags)
- throws IOException {
-
- boolean indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- boolean indexHasPayloads = fieldInfo.hasPayloads();
-
- if ((!indexHasOffsets || (flags & DocsAndPositionsEnum.FLAG_OFFSETS) == 0) &&
- (!indexHasPayloads || (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) == 0)) {
- BlockDocsAndPositionsEnum docsAndPositionsEnum;
- if (reuse instanceof BlockDocsAndPositionsEnum) {
- docsAndPositionsEnum = (BlockDocsAndPositionsEnum) reuse;
- if (!docsAndPositionsEnum.canReuse(docIn, fieldInfo)) {
- docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
- }
- } else {
- docsAndPositionsEnum = new BlockDocsAndPositionsEnum(fieldInfo);
- }
- return docsAndPositionsEnum.reset(liveDocs, (IntBlockTermState) termState);
- } else {
- EverythingEnum everythingEnum;
- if (reuse instanceof EverythingEnum) {
- everythingEnum = (EverythingEnum) reuse;
- if (!everythingEnum.canReuse(docIn, fieldInfo)) {
- everythingEnum = new EverythingEnum(fieldInfo);
- }
- } else {
- everythingEnum = new EverythingEnum(fieldInfo);
- }
- return everythingEnum.reset(liveDocs, (IntBlockTermState) termState, flags);
- }
- }
-
- final class BlockDocsEnum extends DocsEnum {
- private final byte[] encoded;
-
- private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
- private final int[] freqBuffer = new int[MAX_DATA_SIZE];
-
- private int docBufferUpto;
-
- private Lucene41SkipReader skipper;
- private boolean skipped;
-
- final IndexInput startDocIn;
-
- IndexInput docIn;
- final boolean indexHasFreq;
- final boolean indexHasPos;
- final boolean indexHasOffsets;
- final boolean indexHasPayloads;
-
- private int docFreq; // number of docs in this posting list
- private long totalTermFreq; // sum of freqs in this posting list (or docFreq when omitted)
- private int docUpto; // how many docs we've read
- private int doc; // doc we last read
- private int accum; // accumulator for doc deltas
- private int freq; // freq we last read
-
- // Where this term's postings start in the .doc file:
- private long docTermStartFP;
-
- // Where this term's skip data starts (after
- // docTermStartFP) in the .doc file (or -1 if there is
- // no skip data for this term):
- private long skipOffset;
-
- // docID for next skip point, we won't use skipper if
- // target docID is not larger than this
- private int nextSkipDoc;
-
- private Bits liveDocs;
-
- private boolean needsFreq; // true if the caller actually needs frequencies
- private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
-
- public BlockDocsEnum(FieldInfo fieldInfo) throws IOException {
- this.startDocIn = TempPostingsReader.this.docIn;
- this.docIn = null;
- indexHasFreq = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
- indexHasPos = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
- indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- indexHasPayloads = fieldInfo.hasPayloads();
- encoded = new byte[MAX_ENCODED_SIZE];
- }
-
- public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
- return docIn == startDocIn &&
- indexHasFreq == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0) &&
- indexHasPos == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) &&
- indexHasPayloads == fieldInfo.hasPayloads();
- }
-
- public DocsEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
- this.liveDocs = liveDocs;
- // if (DEBUG) {
- // System.out.println(" FPR.reset: termState=" + termState);
- // }
- docFreq = termState.docFreq;
- totalTermFreq = indexHasFreq ? termState.totalTermFreq : docFreq;
- docTermStartFP = termState.docStartFP;
- skipOffset = termState.skipOffset;
- singletonDocID = termState.singletonDocID;
- if (docFreq > 1) {
- if (docIn == null) {
- // lazy init
- docIn = startDocIn.clone();
- }
- docIn.seek(docTermStartFP);
- }
-
- doc = -1;
- this.needsFreq = (flags & DocsEnum.FLAG_FREQS) != 0;
- if (!indexHasFreq) {
- Arrays.fill(freqBuffer, 1);
- }
- accum = 0;
- docUpto = 0;
- nextSkipDoc = BLOCK_SIZE - 1; // we won't skip if target is found in first block
- docBufferUpto = BLOCK_SIZE;
- skipped = false;
- return this;
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- private void refillDocs() throws IOException {
- final int left = docFreq - docUpto;
- assert left > 0;
-
- if (left >= BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
- // }
- forUtil.readBlock(docIn, encoded, docDeltaBuffer);
-
- if (indexHasFreq) {
- // if (DEBUG) {
- // System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
- // }
- if (needsFreq) {
- forUtil.readBlock(docIn, encoded, freqBuffer);
- } else {
- forUtil.skipBlock(docIn); // skip over freqs
- }
- }
- } else if (docFreq == 1) {
- docDeltaBuffer[0] = singletonDocID;
- freqBuffer[0] = (int) totalTermFreq;
- } else {
- // Read vInts:
- // if (DEBUG) {
- // System.out.println(" fill last vInt block from fp=" + docIn.getFilePointer());
- // }
- readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, indexHasFreq);
- }
- docBufferUpto = 0;
- }
-
- @Override
- public int nextDoc() throws IOException {
- // if (DEBUG) {
- // System.out.println("\nFPR.nextDoc");
- // }
- while (true) {
- // if (DEBUG) {
- // System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
- // }
-
- if (docUpto == docFreq) {
- // if (DEBUG) {
- // System.out.println(" return doc=END");
- // }
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
-
- // if (DEBUG) {
- // System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- docUpto++;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- doc = accum;
- freq = freqBuffer[docBufferUpto];
- docBufferUpto++;
- // if (DEBUG) {
- // System.out.println(" return doc=" + doc + " freq=" + freq);
- // }
- return doc;
- }
- // if (DEBUG) {
- // System.out.println(" doc=" + accum + " is deleted; try next doc");
- // }
- docBufferUpto++;
- }
- }
-
- @Override
- public int advance(int target) throws IOException {
- // TODO: make frq block load lazy/skippable
- // if (DEBUG) {
- // System.out.println(" FPR.advance target=" + target);
- // }
-
- // current skip docID < docIDs generated from current buffer <= next skip docID
- // we don't need to skip if target is buffered already
- if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
-
- // if (DEBUG) {
- // System.out.println("load skipper");
- // }
-
- if (skipper == null) {
- // Lazy init: first time this enum has ever been used for skipping
- skipper = new Lucene41SkipReader(docIn.clone(),
- TempPostingsWriter.maxSkipLevels,
- BLOCK_SIZE,
- indexHasPos,
- indexHasOffsets,
- indexHasPayloads);
- }
-
- if (!skipped) {
- assert skipOffset != -1;
- // This is the first time this enum has skipped
- // since reset() was called; load the skip data:
- skipper.init(docTermStartFP+skipOffset, docTermStartFP, 0, 0, docFreq);
- skipped = true;
- }
-
- // always plus one to fix the result, since skip position in Lucene41SkipReader
- // is a little different from MultiLevelSkipListReader
- final int newDocUpto = skipper.skipTo(target) + 1;
-
- if (newDocUpto > docUpto) {
- // Skipper moved
- // if (DEBUG) {
- // System.out.println("skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer());
- // }
- assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
- docUpto = newDocUpto;
-
- // Force to read next block
- docBufferUpto = BLOCK_SIZE;
- accum = skipper.getDoc(); // actually, this is just lastSkipEntry
- docIn.seek(skipper.getDocPointer()); // now point to the block we want to search
- }
- // next time we call advance, this is used to
- // foresee whether skipper is necessary.
- nextSkipDoc = skipper.getNextSkipDoc();
- }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
-
- // Now scan... this is an inlined/pared down version
- // of nextDoc():
- while (true) {
- // if (DEBUG) {
- // System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- docUpto++;
-
- if (accum >= target) {
- break;
- }
- docBufferUpto++;
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- }
-
- if (liveDocs == null || liveDocs.get(accum)) {
- // if (DEBUG) {
- // System.out.println(" return doc=" + accum);
- // }
- freq = freqBuffer[docBufferUpto];
- docBufferUpto++;
- return doc = accum;
- } else {
- // if (DEBUG) {
- // System.out.println(" now do nextDoc()");
- // }
- docBufferUpto++;
- return nextDoc();
- }
- }
-
- @Override
- public long cost() {
- return docFreq;
- }
- }
-
-
- final class BlockDocsAndPositionsEnum extends DocsAndPositionsEnum {
-
- private final byte[] encoded;
-
- private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
- private final int[] freqBuffer = new int[MAX_DATA_SIZE];
- private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
-
- private int docBufferUpto;
- private int posBufferUpto;
-
- private Lucene41SkipReader skipper;
- private boolean skipped;
-
- final IndexInput startDocIn;
-
- IndexInput docIn;
- final IndexInput posIn;
-
- final boolean indexHasOffsets;
- final boolean indexHasPayloads;
-
- private int docFreq; // number of docs in this posting list
- private long totalTermFreq; // number of positions in this posting list
- private int docUpto; // how many docs we've read
- private int doc; // doc we last read
- private int accum; // accumulator for doc deltas
- private int freq; // freq we last read
- private int position; // current position
-
- // how many positions "behind" we are; nextPosition must
- // skip these to "catch up":
- private int posPendingCount;
-
- // Lazy pos seek: if != -1 then we must seek to this FP
- // before reading positions:
- private long posPendingFP;
-
- // Where this term's postings start in the .doc file:
- private long docTermStartFP;
-
- // Where this term's postings start in the .pos file:
- private long posTermStartFP;
-
- // Where this term's payloads/offsets start in the .pay
- // file:
- private long payTermStartFP;
-
- // File pointer where the last (vInt encoded) pos delta
- // block is. We need this to know whether to bulk
- // decode vs vInt decode the block:
- private long lastPosBlockFP;
-
- // Where this term's skip data starts (after
- // docTermStartFP) in the .doc file (or -1 if there is
- // no skip data for this term):
- private long skipOffset;
-
- private int nextSkipDoc;
-
- private Bits liveDocs;
- private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
-
- public BlockDocsAndPositionsEnum(FieldInfo fieldInfo) throws IOException {
- this.startDocIn = TempPostingsReader.this.docIn;
- this.docIn = null;
- this.posIn = TempPostingsReader.this.posIn.clone();
- encoded = new byte[MAX_ENCODED_SIZE];
- indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- indexHasPayloads = fieldInfo.hasPayloads();
- }
-
- public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
- return docIn == startDocIn &&
- indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
- indexHasPayloads == fieldInfo.hasPayloads();
- }
-
- public DocsAndPositionsEnum reset(Bits liveDocs, IntBlockTermState termState) throws IOException {
- this.liveDocs = liveDocs;
- // if (DEBUG) {
- // System.out.println(" FPR.reset: termState=" + termState);
- // }
- docFreq = termState.docFreq;
- docTermStartFP = termState.docStartFP;
- posTermStartFP = termState.posStartFP;
- payTermStartFP = termState.payStartFP;
- skipOffset = termState.skipOffset;
- totalTermFreq = termState.totalTermFreq;
- singletonDocID = termState.singletonDocID;
- if (docFreq > 1) {
- if (docIn == null) {
- // lazy init
- docIn = startDocIn.clone();
- }
- docIn.seek(docTermStartFP);
- }
- posPendingFP = posTermStartFP;
- posPendingCount = 0;
- if (termState.totalTermFreq < BLOCK_SIZE) {
- lastPosBlockFP = posTermStartFP;
- } else if (termState.totalTermFreq == BLOCK_SIZE) {
- lastPosBlockFP = -1;
- } else {
- lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
- }
-
- doc = -1;
- accum = 0;
- docUpto = 0;
- nextSkipDoc = BLOCK_SIZE - 1;
- docBufferUpto = BLOCK_SIZE;
- skipped = false;
- return this;
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- private void refillDocs() throws IOException {
- final int left = docFreq - docUpto;
- assert left > 0;
-
- if (left >= BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
- // }
- forUtil.readBlock(docIn, encoded, docDeltaBuffer);
- // if (DEBUG) {
- // System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
- // }
- forUtil.readBlock(docIn, encoded, freqBuffer);
- } else if (docFreq == 1) {
- docDeltaBuffer[0] = singletonDocID;
- freqBuffer[0] = (int) totalTermFreq;
- } else {
- // Read vInts:
- // if (DEBUG) {
- // System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
- // }
- readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
- }
- docBufferUpto = 0;
- }
-
- private void refillPositions() throws IOException {
- // if (DEBUG) {
- // System.out.println(" refillPositions");
- // }
- if (posIn.getFilePointer() == lastPosBlockFP) {
- // if (DEBUG) {
- // System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
- // }
- final int count = (int) (totalTermFreq % BLOCK_SIZE);
- int payloadLength = 0;
- for(int i=0;i<count;i++) {
- int code = posIn.readVInt();
- if (indexHasPayloads) {
- if ((code & 1) != 0) {
- payloadLength = posIn.readVInt();
- }
- posDeltaBuffer[i] = code >>> 1;
- if (payloadLength != 0) {
- posIn.seek(posIn.getFilePointer() + payloadLength);
- }
- } else {
- posDeltaBuffer[i] = code;
- }
- if (indexHasOffsets) {
- if ((posIn.readVInt() & 1) != 0) {
- // offset length changed
- posIn.readVInt();
- }
- }
- }
- } else {
- // if (DEBUG) {
- // System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
- // }
- forUtil.readBlock(posIn, encoded, posDeltaBuffer);
- }
- }
-
- @Override
- public int nextDoc() throws IOException {
- // if (DEBUG) {
- // System.out.println(" FPR.nextDoc");
- // }
- while (true) {
- // if (DEBUG) {
- // System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
- // }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
- // if (DEBUG) {
- // System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- freq = freqBuffer[docBufferUpto];
- posPendingCount += freq;
- docBufferUpto++;
- docUpto++;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- doc = accum;
- position = 0;
- // if (DEBUG) {
- // System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
- // }
- return doc;
- }
- // if (DEBUG) {
- // System.out.println(" doc=" + accum + " is deleted; try next doc");
- // }
- }
- }
-
- @Override
- public int advance(int target) throws IOException {
- // TODO: make frq block load lazy/skippable
- // if (DEBUG) {
- // System.out.println(" FPR.advance target=" + target);
- // }
-
- if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
- // if (DEBUG) {
- // System.out.println(" try skipper");
- // }
- if (skipper == null) {
- // Lazy init: first time this enum has ever been used for skipping
- // if (DEBUG) {
- // System.out.println(" create skipper");
- // }
- skipper = new Lucene41SkipReader(docIn.clone(),
- TempPostingsWriter.maxSkipLevels,
- BLOCK_SIZE,
- true,
- indexHasOffsets,
- indexHasPayloads);
- }
-
- if (!skipped) {
- assert skipOffset != -1;
- // This is the first time this enum has skipped
- // since reset() was called; load the skip data:
- // if (DEBUG) {
- // System.out.println(" init skipper");
- // }
- skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
- skipped = true;
- }
-
- final int newDocUpto = skipper.skipTo(target) + 1;
-
- if (newDocUpto > docUpto) {
- // Skipper moved
- // if (DEBUG) {
- // System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto());
- // }
-
- assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
- docUpto = newDocUpto;
-
- // Force to read next block
- docBufferUpto = BLOCK_SIZE;
- accum = skipper.getDoc();
- docIn.seek(skipper.getDocPointer());
- posPendingFP = skipper.getPosPointer();
- posPendingCount = skipper.getPosBufferUpto();
- }
- nextSkipDoc = skipper.getNextSkipDoc();
- }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
-
- // Now scan... this is an inlined/pared down version
- // of nextDoc():
- while (true) {
- // if (DEBUG) {
- // System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- freq = freqBuffer[docBufferUpto];
- posPendingCount += freq;
- docBufferUpto++;
- docUpto++;
-
- if (accum >= target) {
- break;
- }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- }
-
- if (liveDocs == null || liveDocs.get(accum)) {
- // if (DEBUG) {
- // System.out.println(" return doc=" + accum);
- // }
- position = 0;
- return doc = accum;
- } else {
- // if (DEBUG) {
- // System.out.println(" now do nextDoc()");
- // }
- return nextDoc();
- }
- }
-
- // TODO: in theory we could avoid loading frq block
- // when not needed, ie, use skip data to load how far to
- // seek the pos pointer ... instead of having to load frq
- // blocks only to sum up how many positions to skip
- private void skipPositions() throws IOException {
- // Skip positions now:
- int toSkip = posPendingCount - freq;
- // if (DEBUG) {
- // System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
- // }
-
- final int leftInBlock = BLOCK_SIZE - posBufferUpto;
- if (toSkip < leftInBlock) {
- posBufferUpto += toSkip;
- // if (DEBUG) {
- // System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
- // }
- } else {
- toSkip -= leftInBlock;
- while(toSkip >= BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
- // }
- assert posIn.getFilePointer() != lastPosBlockFP;
- forUtil.skipBlock(posIn);
- toSkip -= BLOCK_SIZE;
- }
- refillPositions();
- posBufferUpto = toSkip;
- // if (DEBUG) {
- // System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
- // }
- }
-
- position = 0;
- }
-
- @Override
- public int nextPosition() throws IOException {
- // if (DEBUG) {
- // System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto);
- // }
- if (posPendingFP != -1) {
- // if (DEBUG) {
- // System.out.println(" seek to pendingFP=" + posPendingFP);
- // }
- posIn.seek(posPendingFP);
- posPendingFP = -1;
-
- // Force buffer refill:
- posBufferUpto = BLOCK_SIZE;
- }
-
- if (posPendingCount > freq) {
- skipPositions();
- posPendingCount = freq;
- }
-
- if (posBufferUpto == BLOCK_SIZE) {
- refillPositions();
- posBufferUpto = 0;
- }
- position += posDeltaBuffer[posBufferUpto++];
- posPendingCount--;
- // if (DEBUG) {
- // System.out.println(" return pos=" + position);
- // }
- return position;
- }
-
- @Override
- public int startOffset() {
- return -1;
- }
-
- @Override
- public int endOffset() {
- return -1;
- }
-
- @Override
- public BytesRef getPayload() {
- return null;
- }
-
- @Override
- public long cost() {
- return docFreq;
- }
- }
-
- // Also handles payloads + offsets
- final class EverythingEnum extends DocsAndPositionsEnum {
-
- private final byte[] encoded;
-
- private final int[] docDeltaBuffer = new int[MAX_DATA_SIZE];
- private final int[] freqBuffer = new int[MAX_DATA_SIZE];
- private final int[] posDeltaBuffer = new int[MAX_DATA_SIZE];
-
- private final int[] payloadLengthBuffer;
- private final int[] offsetStartDeltaBuffer;
- private final int[] offsetLengthBuffer;
-
- private byte[] payloadBytes;
- private int payloadByteUpto;
- private int payloadLength;
-
- private int lastStartOffset;
- private int startOffset;
- private int endOffset;
-
- private int docBufferUpto;
- private int posBufferUpto;
-
- private Lucene41SkipReader skipper;
- private boolean skipped;
-
- final IndexInput startDocIn;
-
- IndexInput docIn;
- final IndexInput posIn;
- final IndexInput payIn;
- final BytesRef payload;
-
- final boolean indexHasOffsets;
- final boolean indexHasPayloads;
-
- private int docFreq; // number of docs in this posting list
- private long totalTermFreq; // number of positions in this posting list
- private int docUpto; // how many docs we've read
- private int doc; // doc we last read
- private int accum; // accumulator for doc deltas
- private int freq; // freq we last read
- private int position; // current position
-
- // how many positions "behind" we are; nextPosition must
- // skip these to "catch up":
- private int posPendingCount;
-
- // Lazy pos seek: if != -1 then we must seek to this FP
- // before reading positions:
- private long posPendingFP;
-
- // Lazy pay seek: if != -1 then we must seek to this FP
- // before reading payloads/offsets:
- private long payPendingFP;
-
- // Where this term's postings start in the .doc file:
- private long docTermStartFP;
-
- // Where this term's postings start in the .pos file:
- private long posTermStartFP;
-
- // Where this term's payloads/offsets start in the .pay
- // file:
- private long payTermStartFP;
-
- // File pointer where the last (vInt encoded) pos delta
- // block is. We need this to know whether to bulk
- // decode vs vInt decode the block:
- private long lastPosBlockFP;
-
- // Where this term's skip data starts (after
- // docTermStartFP) in the .doc file (or -1 if there is
- // no skip data for this term):
- private long skipOffset;
-
- private int nextSkipDoc;
-
- private Bits liveDocs;
-
- private boolean needsOffsets; // true if we actually need offsets
- private boolean needsPayloads; // true if we actually need payloads
- private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
-
- public EverythingEnum(FieldInfo fieldInfo) throws IOException {
- this.startDocIn = TempPostingsReader.this.docIn;
- this.docIn = null;
- this.posIn = TempPostingsReader.this.posIn.clone();
- this.payIn = TempPostingsReader.this.payIn.clone();
- encoded = new byte[MAX_ENCODED_SIZE];
- indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- if (indexHasOffsets) {
- offsetStartDeltaBuffer = new int[MAX_DATA_SIZE];
- offsetLengthBuffer = new int[MAX_DATA_SIZE];
- } else {
- offsetStartDeltaBuffer = null;
- offsetLengthBuffer = null;
- startOffset = -1;
- endOffset = -1;
- }
-
- indexHasPayloads = fieldInfo.hasPayloads();
- if (indexHasPayloads) {
- payloadLengthBuffer = new int[MAX_DATA_SIZE];
- payloadBytes = new byte[128];
- payload = new BytesRef();
- } else {
- payloadLengthBuffer = null;
- payloadBytes = null;
- payload = null;
- }
- }
-
- public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
- return docIn == startDocIn &&
- indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
- indexHasPayloads == fieldInfo.hasPayloads();
- }
-
- public EverythingEnum reset(Bits liveDocs, IntBlockTermState termState, int flags) throws IOException {
- this.liveDocs = liveDocs;
- // if (DEBUG) {
- // System.out.println(" FPR.reset: termState=" + termState);
- // }
- docFreq = termState.docFreq;
- docTermStartFP = termState.docStartFP;
- posTermStartFP = termState.posStartFP;
- payTermStartFP = termState.payStartFP;
- skipOffset = termState.skipOffset;
- totalTermFreq = termState.totalTermFreq;
- singletonDocID = termState.singletonDocID;
- if (docFreq > 1) {
- if (docIn == null) {
- // lazy init
- docIn = startDocIn.clone();
- }
- docIn.seek(docTermStartFP);
- }
- posPendingFP = posTermStartFP;
- payPendingFP = payTermStartFP;
- posPendingCount = 0;
- if (termState.totalTermFreq < BLOCK_SIZE) {
- lastPosBlockFP = posTermStartFP;
- } else if (termState.totalTermFreq == BLOCK_SIZE) {
- lastPosBlockFP = -1;
- } else {
- lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
- }
-
- this.needsOffsets = (flags & DocsAndPositionsEnum.FLAG_OFFSETS) != 0;
- this.needsPayloads = (flags & DocsAndPositionsEnum.FLAG_PAYLOADS) != 0;
-
- doc = -1;
- accum = 0;
- docUpto = 0;
- nextSkipDoc = BLOCK_SIZE - 1;
- docBufferUpto = BLOCK_SIZE;
- skipped = false;
- return this;
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- private void refillDocs() throws IOException {
- final int left = docFreq - docUpto;
- assert left > 0;
-
- if (left >= BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" fill doc block from fp=" + docIn.getFilePointer());
- // }
- forUtil.readBlock(docIn, encoded, docDeltaBuffer);
- // if (DEBUG) {
- // System.out.println(" fill freq block from fp=" + docIn.getFilePointer());
- // }
- forUtil.readBlock(docIn, encoded, freqBuffer);
- } else if (docFreq == 1) {
- docDeltaBuffer[0] = singletonDocID;
- freqBuffer[0] = (int) totalTermFreq;
- } else {
- // if (DEBUG) {
- // System.out.println(" fill last vInt doc block from fp=" + docIn.getFilePointer());
- // }
- readVIntBlock(docIn, docDeltaBuffer, freqBuffer, left, true);
- }
- docBufferUpto = 0;
- }
-
- private void refillPositions() throws IOException {
- // if (DEBUG) {
- // System.out.println(" refillPositions");
- // }
- if (posIn.getFilePointer() == lastPosBlockFP) {
- // if (DEBUG) {
- // System.out.println(" vInt pos block @ fp=" + posIn.getFilePointer() + " hasPayloads=" + indexHasPayloads + " hasOffsets=" + indexHasOffsets);
- // }
- final int count = (int) (totalTermFreq % BLOCK_SIZE);
- int payloadLength = 0;
- int offsetLength = 0;
- payloadByteUpto = 0;
- for(int i=0;i<count;i++) {
- int code = posIn.readVInt();
- if (indexHasPayloads) {
- if ((code & 1) != 0) {
- payloadLength = posIn.readVInt();
- }
- // if (DEBUG) {
- // System.out.println(" i=" + i + " payloadLen=" + payloadLength);
- // }
- payloadLengthBuffer[i] = payloadLength;
- posDeltaBuffer[i] = code >>> 1;
- if (payloadLength != 0) {
- if (payloadByteUpto + payloadLength > payloadBytes.length) {
- payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payloadLength);
- }
- //System.out.println(" read payload @ pos.fp=" + posIn.getFilePointer());
- posIn.readBytes(payloadBytes, payloadByteUpto, payloadLength);
- payloadByteUpto += payloadLength;
- }
- } else {
- posDeltaBuffer[i] = code;
- }
-
- if (indexHasOffsets) {
- // if (DEBUG) {
- // System.out.println(" i=" + i + " read offsets from posIn.fp=" + posIn.getFilePointer());
- // }
- int deltaCode = posIn.readVInt();
- if ((deltaCode & 1) != 0) {
- offsetLength = posIn.readVInt();
- }
- offsetStartDeltaBuffer[i] = deltaCode >>> 1;
- offsetLengthBuffer[i] = offsetLength;
- // if (DEBUG) {
- // System.out.println(" startOffDelta=" + offsetStartDeltaBuffer[i] + " offsetLen=" + offsetLengthBuffer[i]);
- // }
- }
- }
- payloadByteUpto = 0;
- } else {
- // if (DEBUG) {
- // System.out.println(" bulk pos block @ fp=" + posIn.getFilePointer());
- // }
- forUtil.readBlock(posIn, encoded, posDeltaBuffer);
-
- if (indexHasPayloads) {
- // if (DEBUG) {
- // System.out.println(" bulk payload block @ pay.fp=" + payIn.getFilePointer());
- // }
- if (needsPayloads) {
- forUtil.readBlock(payIn, encoded, payloadLengthBuffer);
- int numBytes = payIn.readVInt();
- // if (DEBUG) {
- // System.out.println(" " + numBytes + " payload bytes @ pay.fp=" + payIn.getFilePointer());
- // }
- if (numBytes > payloadBytes.length) {
- payloadBytes = ArrayUtil.grow(payloadBytes, numBytes);
- }
- payIn.readBytes(payloadBytes, 0, numBytes);
- } else {
- // this works, because when writing a vint block we always force the first length to be written
- forUtil.skipBlock(payIn); // skip over lengths
- int numBytes = payIn.readVInt(); // read length of payloadBytes
- payIn.seek(payIn.getFilePointer() + numBytes); // skip over payloadBytes
- }
- payloadByteUpto = 0;
- }
-
- if (indexHasOffsets) {
- // if (DEBUG) {
- // System.out.println(" bulk offset block @ pay.fp=" + payIn.getFilePointer());
- // }
- if (needsOffsets) {
- forUtil.readBlock(payIn, encoded, offsetStartDeltaBuffer);
- forUtil.readBlock(payIn, encoded, offsetLengthBuffer);
- } else {
- // this works, because when writing a vint block we always force the first length to be written
- forUtil.skipBlock(payIn); // skip over starts
- forUtil.skipBlock(payIn); // skip over lengths
- }
- }
- }
- }
-
- @Override
- public int nextDoc() throws IOException {
- // if (DEBUG) {
- // System.out.println(" FPR.nextDoc");
- // }
- while (true) {
- // if (DEBUG) {
- // System.out.println(" docUpto=" + docUpto + " (of df=" + docFreq + ") docBufferUpto=" + docBufferUpto);
- // }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
- // if (DEBUG) {
- // System.out.println(" accum=" + accum + " docDeltaBuffer[" + docBufferUpto + "]=" + docDeltaBuffer[docBufferUpto]);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- freq = freqBuffer[docBufferUpto];
- posPendingCount += freq;
- docBufferUpto++;
- docUpto++;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- doc = accum;
- // if (DEBUG) {
- // System.out.println(" return doc=" + doc + " freq=" + freq + " posPendingCount=" + posPendingCount);
- // }
- position = 0;
- lastStartOffset = 0;
- return doc;
- }
-
- // if (DEBUG) {
- // System.out.println(" doc=" + accum + " is deleted; try next doc");
- // }
- }
- }
-
- @Override
- public int advance(int target) throws IOException {
- // TODO: make frq block load lazy/skippable
- // if (DEBUG) {
- // System.out.println(" FPR.advance target=" + target);
- // }
-
- if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
-
- // if (DEBUG) {
- // System.out.println(" try skipper");
- // }
-
- if (skipper == null) {
- // Lazy init: first time this enum has ever been used for skipping
- // if (DEBUG) {
- // System.out.println(" create skipper");
- // }
- skipper = new Lucene41SkipReader(docIn.clone(),
- TempPostingsWriter.maxSkipLevels,
- BLOCK_SIZE,
- true,
- indexHasOffsets,
- indexHasPayloads);
- }
-
- if (!skipped) {
- assert skipOffset != -1;
- // This is the first time this enum has skipped
- // since reset() was called; load the skip data:
- // if (DEBUG) {
- // System.out.println(" init skipper");
- // }
- skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
- skipped = true;
- }
-
- final int newDocUpto = skipper.skipTo(target) + 1;
-
- if (newDocUpto > docUpto) {
- // Skipper moved
- // if (DEBUG) {
- // System.out.println(" skipper moved to docUpto=" + newDocUpto + " vs current=" + docUpto + "; docID=" + skipper.getDoc() + " fp=" + skipper.getDocPointer() + " pos.fp=" + skipper.getPosPointer() + " pos.bufferUpto=" + skipper.getPosBufferUpto() + " pay.fp=" + skipper.getPayPointer() + " lastStartOffset=" + lastStartOffset);
- // }
- assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
- docUpto = newDocUpto;
-
- // Force to read next block
- docBufferUpto = BLOCK_SIZE;
- accum = skipper.getDoc();
- docIn.seek(skipper.getDocPointer());
- posPendingFP = skipper.getPosPointer();
- payPendingFP = skipper.getPayPointer();
- posPendingCount = skipper.getPosBufferUpto();
- lastStartOffset = 0; // new document
- payloadByteUpto = skipper.getPayloadByteUpto();
- }
- nextSkipDoc = skipper.getNextSkipDoc();
- }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- if (docBufferUpto == BLOCK_SIZE) {
- refillDocs();
- }
-
- // Now scan:
- while (true) {
- // if (DEBUG) {
- // System.out.println(" scan doc=" + accum + " docBufferUpto=" + docBufferUpto);
- // }
- accum += docDeltaBuffer[docBufferUpto];
- freq = freqBuffer[docBufferUpto];
- posPendingCount += freq;
- docBufferUpto++;
- docUpto++;
-
- if (accum >= target) {
- break;
- }
- if (docUpto == docFreq) {
- return doc = NO_MORE_DOCS;
- }
- }
-
- if (liveDocs == null || liveDocs.get(accum)) {
- // if (DEBUG) {
- // System.out.println(" return doc=" + accum);
- // }
- position = 0;
- lastStartOffset = 0;
- return doc = accum;
- } else {
- // if (DEBUG) {
- // System.out.println(" now do nextDoc()");
- // }
- return nextDoc();
- }
- }
-
- // TODO: in theory we could avoid loading frq block
- // when not needed, ie, use skip data to load how far to
- // seek the pos pointer ... instead of having to load frq
- // blocks only to sum up how many positions to skip
- private void skipPositions() throws IOException {
- // Skip positions now:
- int toSkip = posPendingCount - freq;
- // if (DEBUG) {
- // System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
- // }
-
- final int leftInBlock = BLOCK_SIZE - posBufferUpto;
- if (toSkip < leftInBlock) {
- int end = posBufferUpto + toSkip;
- while(posBufferUpto < end) {
- if (indexHasPayloads) {
- payloadByteUpto += payloadLengthBuffer[posBufferUpto];
- }
- posBufferUpto++;
- }
- // if (DEBUG) {
- // System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
- // }
- } else {
- toSkip -= leftInBlock;
- while(toSkip >= BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" skip whole block @ fp=" + posIn.getFilePointer());
- // }
- assert posIn.getFilePointer() != lastPosBlockFP;
- forUtil.skipBlock(posIn);
-
- if (indexHasPayloads) {
- // Skip payloadLength block:
- forUtil.skipBlock(payIn);
-
- // Skip payloadBytes block:
- int numBytes = payIn.readVInt();
- payIn.seek(payIn.getFilePointer() + numBytes);
- }
-
- if (indexHasOffsets) {
- forUtil.skipBlock(payIn);
- forUtil.skipBlock(payIn);
- }
- toSkip -= BLOCK_SIZE;
- }
- refillPositions();
- payloadByteUpto = 0;
- posBufferUpto = 0;
- while(posBufferUpto < toSkip) {
- if (indexHasPayloads) {
- payloadByteUpto += payloadLengthBuffer[posBufferUpto];
- }
- posBufferUpto++;
- }
- // if (DEBUG) {
- // System.out.println(" skip w/in block to posBufferUpto=" + posBufferUpto);
- // }
- }
-
- position = 0;
- lastStartOffset = 0;
- }
-
- @Override
- public int nextPosition() throws IOException {
- // if (DEBUG) {
- // System.out.println(" FPR.nextPosition posPendingCount=" + posPendingCount + " posBufferUpto=" + posBufferUpto + " payloadByteUpto=" + payloadByteUpto)// ;
- // }
- if (posPendingFP != -1) {
- // if (DEBUG) {
- // System.out.println(" seek pos to pendingFP=" + posPendingFP);
- // }
- posIn.seek(posPendingFP);
- posPendingFP = -1;
-
- if (payPendingFP != -1) {
- // if (DEBUG) {
- // System.out.println(" seek pay to pendingFP=" + payPendingFP);
- // }
- payIn.seek(payPendingFP);
- payPendingFP = -1;
- }
-
- // Force buffer refill:
- posBufferUpto = BLOCK_SIZE;
- }
-
- if (posPendingCount > freq) {
- skipPositions();
- posPendingCount = freq;
- }
-
- if (posBufferUpto == BLOCK_SIZE) {
- refillPositions();
- posBufferUpto = 0;
- }
- position += posDeltaBuffer[posBufferUpto];
-
- if (indexHasPayloads) {
- payloadLength = payloadLengthBuffer[posBufferUpto];
- payload.bytes = payloadBytes;
- payload.offset = payloadByteUpto;
- payload.length = payloadLength;
- payloadByteUpto += payloadLength;
- }
-
- if (indexHasOffsets) {
- startOffset = lastStartOffset + offsetStartDeltaBuffer[posBufferUpto];
- endOffset = startOffset + offsetLengthBuffer[posBufferUpto];
- lastStartOffset = startOffset;
- }
-
- posBufferUpto++;
- posPendingCount--;
- // if (DEBUG) {
- // System.out.println(" return pos=" + position);
- // }
- return position;
- }
-
- @Override
- public int startOffset() {
- return startOffset;
- }
-
- @Override
- public int endOffset() {
- return endOffset;
- }
-
- @Override
- public BytesRef getPayload() {
- // if (DEBUG) {
- // System.out.println(" FPR.getPayload payloadLength=" + payloadLength + " payloadByteUpto=" + payloadByteUpto);
- // }
- if (payloadLength == 0) {
- return null;
- } else {
- return payload;
- }
- }
-
- @Override
- public long cost() {
- return docFreq;
- }
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java
deleted file mode 100644
index 16168b73cb7..00000000000
--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java
+++ /dev/null
@@ -1,571 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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 static org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat.BLOCK_SIZE;
-import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_DATA_SIZE;
-import static org.apache.lucene.codecs.lucene41.ForUtil.MAX_ENCODED_SIZE;
-
-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.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.codecs.lucene41.Lucene41SkipWriter;
-import org.apache.lucene.codecs.lucene41.ForUtil;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-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.IOUtils;
-import org.apache.lucene.util.packed.PackedInts;
-
-
-/**
- * Concrete class that writes docId(maybe frq,pos,offset,payloads) list
- * with postings format.
- *
- * Postings list for each term will be stored separately.
- *
- * @see Lucene41SkipWriter for details about skipping setting and postings layout.
- * @lucene.experimental
- */
-public final class TempPostingsWriter extends TempPostingsWriterBase {
-
- /**
- * Expert: The maximum number of skip levels. Smaller values result in
- * slightly smaller indexes, but slower skipping in big posting lists.
- */
- static final int maxSkipLevels = 10;
-
- final static String TERMS_CODEC = "TempPostingsWriterTerms";
- final static String DOC_CODEC = "TempPostingsWriterDoc";
- final static String POS_CODEC = "TempPostingsWriterPos";
- final static String PAY_CODEC = "TempPostingsWriterPay";
-
- // Increment version to change it
- final static int VERSION_START = 0;
- final static int VERSION_CURRENT = VERSION_START;
-
- final IndexOutput docOut;
- final IndexOutput posOut;
- final IndexOutput payOut;
-
- final static IntBlockTermState emptyState = new IntBlockTermState();
- IntBlockTermState lastState;
-
- // How current field indexes postings:
- private boolean fieldHasFreqs;
- private boolean fieldHasPositions;
- private boolean fieldHasOffsets;
- private boolean fieldHasPayloads;
-
- // Holds starting file pointers for current term:
- private long docTermStartFP;
- private long posTermStartFP;
- private long payTermStartFP;
-
- final int[] docDeltaBuffer;
- final int[] freqBuffer;
- private int docBufferUpto;
-
- final int[] posDeltaBuffer;
- final int[] payloadLengthBuffer;
- final int[] offsetStartDeltaBuffer;
- final int[] offsetLengthBuffer;
- private int posBufferUpto;
-
- private byte[] payloadBytes;
- private int payloadByteUpto;
-
- private int lastBlockDocID;
- private long lastBlockPosFP;
- private long lastBlockPayFP;
- private int lastBlockPosBufferUpto;
- private int lastBlockPayloadByteUpto;
-
- private int lastDocID;
- private int lastPosition;
- private int lastStartOffset;
- private int docCount;
-
- final byte[] encoded;
-
- private final ForUtil forUtil;
- private final Lucene41SkipWriter skipWriter;
-
- /** Creates a postings writer with the specified PackedInts overhead ratio */
- // TODO: does this ctor even make sense?
- public TempPostingsWriter(SegmentWriteState state, float acceptableOverheadRatio) throws IOException {
- super();
-
- docOut = state.directory.createOutput(IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempBlockTreePostingsFormat.DOC_EXTENSION),
- state.context);
- IndexOutput posOut = null;
- IndexOutput payOut = null;
- boolean success = false;
- try {
- CodecUtil.writeHeader(docOut, DOC_CODEC, VERSION_CURRENT);
- forUtil = new ForUtil(acceptableOverheadRatio, docOut);
- if (state.fieldInfos.hasProx()) {
- posDeltaBuffer = new int[MAX_DATA_SIZE];
- posOut = state.directory.createOutput(IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempBlockTreePostingsFormat.POS_EXTENSION),
- state.context);
- CodecUtil.writeHeader(posOut, POS_CODEC, VERSION_CURRENT);
-
- if (state.fieldInfos.hasPayloads()) {
- payloadBytes = new byte[128];
- payloadLengthBuffer = new int[MAX_DATA_SIZE];
- } else {
- payloadBytes = null;
- payloadLengthBuffer = null;
- }
-
- if (state.fieldInfos.hasOffsets()) {
- offsetStartDeltaBuffer = new int[MAX_DATA_SIZE];
- offsetLengthBuffer = new int[MAX_DATA_SIZE];
- } else {
- offsetStartDeltaBuffer = null;
- offsetLengthBuffer = null;
- }
-
- if (state.fieldInfos.hasPayloads() || state.fieldInfos.hasOffsets()) {
- payOut = state.directory.createOutput(IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, TempBlockTreePostingsFormat.PAY_EXTENSION),
- state.context);
- CodecUtil.writeHeader(payOut, PAY_CODEC, VERSION_CURRENT);
- }
- } else {
- posDeltaBuffer = null;
- payloadLengthBuffer = null;
- offsetStartDeltaBuffer = null;
- offsetLengthBuffer = null;
- payloadBytes = null;
- }
- this.payOut = payOut;
- this.posOut = posOut;
- success = true;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(docOut, posOut, payOut);
- }
- }
-
- docDeltaBuffer = new int[MAX_DATA_SIZE];
- freqBuffer = new int[MAX_DATA_SIZE];
-
- // TODO: should we try skipping every 2/4 blocks...?
- skipWriter = new Lucene41SkipWriter(maxSkipLevels,
- BLOCK_SIZE,
- state.segmentInfo.getDocCount(),
- docOut,
- posOut,
- payOut);
-
- encoded = new byte[MAX_ENCODED_SIZE];
- }
-
- /** Creates a postings writer with <code>PackedInts.COMPACT</code> */
- public TempPostingsWriter(SegmentWriteState state) throws IOException {
- this(state, PackedInts.COMPACT);
- }
-
- private final static class IntBlockTermState extends BlockTermState {
- long docTermStartFP = 0;
- long posTermStartFP = 0;
- long payTermStartFP = 0;
- long skipOffset = -1;
- long lastPosBlockOffset = -1;
- int singletonDocID = -1;
- @Override
- public String toString() {
- return super.toString() + " docStartFP=" + docTermStartFP + " posStartFP=" + posTermStartFP + " payStartFP=" + payTermStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;
- }
- }
-
- @Override
- public IntBlockTermState newTermState() {
- return new IntBlockTermState();
- }
-
- @Override
- public void init(IndexOutput termsOut) throws IOException {
- CodecUtil.writeHeader(termsOut, TERMS_CODEC, VERSION_CURRENT);
- termsOut.writeVInt(BLOCK_SIZE);
- }
-
- // nocommit better name?
-
- @Override
- public int setField(FieldInfo fieldInfo) {
- IndexOptions indexOptions = fieldInfo.getIndexOptions();
- fieldHasFreqs = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
- fieldHasPositions = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
- fieldHasOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- fieldHasPayloads = fieldInfo.hasPayloads();
- skipWriter.setField(fieldHasPositions, fieldHasOffsets, fieldHasPayloads);
- lastState = emptyState;
- if (fieldHasPositions) {
- if (fieldHasPayloads || fieldHasOffsets) {
- return 3; // doc + pos + pay FP
- } else {
- return 2; // doc + pos FP
- }
- } else {
- return 1; // doc FP
- }
- }
-
- @Override
- public void startTerm() {
- docTermStartFP = docOut.getFilePointer();
- if (fieldHasPositions) {
- posTermStartFP = posOut.getFilePointer();
- if (fieldHasPayloads || fieldHasOffsets) {
- payTermStartFP = payOut.getFilePointer();
- }
- }
- lastDocID = 0;
- lastBlockDocID = -1;
- // if (DEBUG) {
- // System.out.println("FPW.startTerm startFP=" + docTermStartFP);
- // }
- skipWriter.resetSkip();
- }
-
- @Override
- public void startDoc(int docID, int termDocFreq) throws IOException {
- // if (DEBUG) {
- // System.out.println("FPW.startDoc docID["+docBufferUpto+"]=" + docID);
- // }
- // Have collected a block of docs, and get a new doc.
- // Should write skip data as well as postings list for
- // current block.
- if (lastBlockDocID != -1 && docBufferUpto == 0) {
- // if (DEBUG) {
- // System.out.println(" bufferSkip at writeBlock: lastDocID=" + lastBlockDocID + " docCount=" + (docCount-1));
- // }
- skipWriter.bufferSkip(lastBlockDocID, docCount, lastBlockPosFP, lastBlockPayFP, lastBlockPosBufferUpto, lastBlockPayloadByteUpto);
- }
-
- final int docDelta = docID - lastDocID;
-
- if (docID < 0 || (docCount > 0 && docDelta <= 0)) {
- throw new CorruptIndexException("docs out of order (" + docID + " <= " + lastDocID + " ) (docOut: " + docOut + ")");
- }
-
- docDeltaBuffer[docBufferUpto] = docDelta;
- // if (DEBUG) {
- // System.out.println(" docDeltaBuffer[" + docBufferUpto + "]=" + docDelta);
- // }
- if (fieldHasFreqs) {
- freqBuffer[docBufferUpto] = termDocFreq;
- }
- docBufferUpto++;
- docCount++;
-
- if (docBufferUpto == BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" write docDelta block @ fp=" + docOut.getFilePointer());
- // }
- forUtil.writeBlock(docDeltaBuffer, encoded, docOut);
- if (fieldHasFreqs) {
- // if (DEBUG) {
- // System.out.println(" write freq block @ fp=" + docOut.getFilePointer());
- // }
- forUtil.writeBlock(freqBuffer, encoded, docOut);
- }
- // NOTE: don't set docBufferUpto back to 0 here;
- // finishDoc will do so (because it needs to see that
- // the block was filled so it can save skip data)
- }
-
-
- lastDocID = docID;
- lastPosition = 0;
- lastStartOffset = 0;
- }
-
- /** Add a new position & payload */
- @Override
- public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {
- // if (DEBUG) {
- // System.out.println("FPW.addPosition pos=" + position + " posBufferUpto=" + posBufferUpto + (fieldHasPayloads ? " payloadByteUpto=" + payloadByteUpto: ""));
- // }
- posDeltaBuffer[posBufferUpto] = position - lastPosition;
- if (fieldHasPayloads) {
- if (payload == null || payload.length == 0) {
- // no payload
- payloadLengthBuffer[posBufferUpto] = 0;
- } else {
- payloadLengthBuffer[posBufferUpto] = payload.length;
- if (payloadByteUpto + payload.length > payloadBytes.length) {
- payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payload.length);
- }
- System.arraycopy(payload.bytes, payload.offset, payloadBytes, payloadByteUpto, payload.length);
- payloadByteUpto += payload.length;
- }
- }
-
- if (fieldHasOffsets) {
- assert startOffset >= lastStartOffset;
- assert endOffset >= startOffset;
- offsetStartDeltaBuffer[posBufferUpto] = startOffset - lastStartOffset;
- offsetLengthBuffer[posBufferUpto] = endOffset - startOffset;
- lastStartOffset = startOffset;
- }
-
- posBufferUpto++;
- lastPosition = position;
- if (posBufferUpto == BLOCK_SIZE) {
- // if (DEBUG) {
- // System.out.println(" write pos bulk block @ fp=" + posOut.getFilePointer());
- // }
- forUtil.writeBlock(posDeltaBuffer, encoded, posOut);
-
- if (fieldHasPayloads) {
- forUtil.writeBlock(payloadLengthBuffer, encoded, payOut);
- payOut.writeVInt(payloadByteUpto);
- payOut.writeBytes(payloadBytes, 0, payloadByteUpto);
- payloadByteUpto = 0;
- }
- if (fieldHasOffsets) {
- forUtil.writeBlock(offsetStartDeltaBuffer, encoded, payOut);
- forUtil.writeBlock(offsetLengthBuffer, encoded, payOut);
- }
- posBufferUpto = 0;
- }
- }
-
- @Override
- public void finishDoc() throws IOException {
- // Since we don't know df for current term, we had to buffer
- // those skip data for each block, and when a new doc comes,
- // write them to skip file.
- if (docBufferUpto == BLOCK_SIZE) {
- lastBlockDocID = lastDocID;
- if (posOut != null) {
- if (payOut != null) {
- lastBlockPayFP = payOut.getFilePointer();
- }
- lastBlockPosFP = posOut.getFilePointer();
- lastBlockPosBufferUpto = posBufferUpto;
- lastBlockPayloadByteUpto = payloadByteUpto;
- }
- // if (DEBUG) {
- // System.out.println(" docBufferUpto="+docBufferUpto+" now get lastBlockDocID="+lastBlockDocID+" lastBlockPosFP=" + lastBlockPosFP + " lastBlockPosBufferUpto=" + lastBlockPosBufferUpto + " lastBlockPayloadByteUpto=" + lastBlockPayloadByteUpto);
- // }
- docBufferUpto = 0;
- }
- }
-
- /** Called when we are done adding docs to this term */
- @Override
- public void finishTerm(BlockTermState _state) throws IOException {
- IntBlockTermState state = (IntBlockTermState) _state;
- assert state.docFreq > 0;
-
- // TODO: wasteful we are counting this (counting # docs
- // for this term) in two places?
- assert state.docFreq == docCount: state.docFreq + " vs " + docCount;
-
- // if (DEBUG) {
- // System.out.println("FPW.finishTerm docFreq=" + state.docFreq);
- // }
-
- // if (DEBUG) {
- // if (docBufferUpto > 0) {
- // System.out.println(" write doc/freq vInt block (count=" + docBufferUpto + ") at fp=" + docOut.getFilePointer() + " docTermStartFP=" + docTermStartFP);
- // }
- // }
-
- // docFreq == 1, don't write the single docid/freq to a separate file along with a pointer to it.
- final int singletonDocID;
- if (state.docFreq == 1) {
- // pulse the singleton docid into the term dictionary, freq is implicitly totalTermFreq
- singletonDocID = docDeltaBuffer[0];
- } else {
- singletonDocID = -1;
- // vInt encode the remaining doc deltas and freqs:
- for(int i=0;i<docBufferUpto;i++) {
- final int docDelta = docDeltaBuffer[i];
- final int freq = freqBuffer[i];
- if (!fieldHasFreqs) {
- docOut.writeVInt(docDelta);
- } else if (freqBuffer[i] == 1) {
- docOut.writeVInt((docDelta<<1)|1);
- } else {
- docOut.writeVInt(docDelta<<1);
- docOut.writeVInt(freq);
- }
- }
- }
-
- final long lastPosBlockOffset;
-
- if (fieldHasPositions) {
- // if (DEBUG) {
- // if (posBufferUpto > 0) {
- // System.out.println(" write pos vInt block (count=" + posBufferUpto + ") at fp=" + posOut.getFilePointer() + " posTermStartFP=" + posTermStartFP + " hasPayloads=" + fieldHasPayloads + " hasOffsets=" + fieldHasOffsets);
- // }
- // }
-
- // totalTermFreq is just total number of positions(or payloads, or offsets)
- // associated with current term.
- assert state.totalTermFreq != -1;
- if (state.totalTermFreq > BLOCK_SIZE) {
- // record file offset for last pos in last block
- lastPosBlockOffset = posOut.getFilePointer() - posTermStartFP;
- } else {
- lastPosBlockOffset = -1;
- }
- if (posBufferUpto > 0) {
- // TODO: should we send offsets/payloads to
- // .pay...? seems wasteful (have to store extra
- // vLong for low (< BLOCK_SIZE) DF terms = vast vast
- // majority)
-
- // vInt encode the remaining positions/payloads/offsets:
- int lastPayloadLength = -1; // force first payload length to be written
- int lastOffsetLength = -1; // force first offset length to be written
- int payloadBytesReadUpto = 0;
- for(int i=0;i<posBufferUpto;i++) {
- final int posDelta = posDeltaBuffer[i];
- if (fieldHasPayloads) {
- final int payloadLength = payloadLengthBuffer[i];
- if (payloadLength != lastPayloadLength) {
- lastPayloadLength = payloadLength;
- posOut.writeVInt((posDelta<<1)|1);
- posOut.writeVInt(payloadLength);
- } else {
- posOut.writeVInt(posDelta<<1);
- }
-
- // if (DEBUG) {
- // System.out.println(" i=" + i + " payloadLen=" + payloadLength);
- // }
-
- if (payloadLength != 0) {
- // if (DEBUG) {
- // System.out.println(" write payload @ pos.fp=" + posOut.getFilePointer());
- // }
- posOut.writeBytes(payloadBytes, payloadBytesReadUpto, payloadLength);
- payloadBytesReadUpto += payloadLength;
- }
- } else {
- posOut.writeVInt(posDelta);
- }
-
- if (fieldHasOffsets) {
- // if (DEBUG) {
- // System.out.println(" write offset @ pos.fp=" + posOut.getFilePointer());
- // }
- int delta = offsetStartDeltaBuffer[i];
- int length = offsetLengthBuffer[i];
- if (length == lastOffsetLength) {
- posOut.writeVInt(delta << 1);
- } else {
- posOut.writeVInt(delta << 1 | 1);
- posOut.writeVInt(length);
- lastOffsetLength = length;
- }
- }
- }
-
- if (fieldHasPayloads) {
- assert payloadBytesReadUpto == payloadByteUpto;
- payloadByteUpto = 0;
- }
- }
- // if (DEBUG) {
- // System.out.println(" totalTermFreq=" + state.totalTermFreq + " lastPosBlockOffset=" + lastPosBlockOffset);
- // }
- } else {
- lastPosBlockOffset = -1;
- }
-
- long skipOffset;
- if (docCount > BLOCK_SIZE) {
- skipOffset = skipWriter.writeSkip(docOut) - docTermStartFP;
-
- // if (DEBUG) {
- // System.out.println("skip packet " + (docOut.getFilePointer() - (docTermStartFP + skipOffset)) + " bytes");
- // }
- } else {
- skipOffset = -1;
- // if (DEBUG) {
- // System.out.println(" no skip: docCount=" + docCount);
- // }
- }
- // if (DEBUG) {
- // System.out.println(" payStartFP=" + payStartFP);
- // }
- state.docTermStartFP = docTermStartFP;
- state.posTermStartFP = posTermStartFP;
- state.payTermStartFP = payTermStartFP;
- state.singletonDocID = singletonDocID;
- state.skipOffset = skipOffset;
- state.lastPosBlockOffset = lastPosBlockOffset;
- docBufferUpto = 0;
- posBufferUpto = 0;
- lastDocID = 0;
- docCount = 0;
- }
-
- // nocommit explain about the "don't care" values
-
- @Override
- public void encodeTerm(long[] longs, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
- IntBlockTermState state = (IntBlockTermState)_state;
- if (absolute) {
- lastState = emptyState;
- }
- longs[0] = state.docTermStartFP - lastState.docTermStartFP;
- if (fieldHasPositions) {
- longs[1] = state.posTermStartFP - lastState.posTermStartFP;
- if (fieldHasPayloads || fieldHasOffsets) {
- longs[2] = state.payTermStartFP - lastState.payTermStartFP;
- }
- }
- if (state.singletonDocID != -1) {
- out.writeVInt(state.singletonDocID);
- }
- if (fieldHasPositions) {
- if (state.lastPosBlockOffset != -1) {
- out.writeVLong(state.lastPosBlockOffset);
- }
- }
- if (state.skipOffset != -1) {
- out.writeVLong(state.skipOffset);
- }
- lastState = state;
- }
-
- @Override
- public void close() throws IOException {
- IOUtils.close(docOut, posOut, payOut);
- }
-}
diff --git a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
index 9ac754d6d45..023d9c9e1a6 100644
--- a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
+++ b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
@@ -15,6 +15,3 @@
org.apache.lucene.codecs.lucene40.Lucene40PostingsFormat
org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat
-org.apache.lucene.codecs.temp.TempBlockTreePostingsFormat
-org.apache.lucene.codecs.temp.TempFSTPostingsFormat
-org.apache.lucene.codecs.temp.TempFSTOrdPostingsFormat
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java b/lucene/core/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
index e66321adaa5..8d9529a35bc 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
@@ -74,7 +74,7 @@ import org.junit.Ignore;
// we won't even be running the actual code, only the impostor
// @SuppressCodecs("Lucene4x")
// Sep codec cannot yet handle the offsets in our 4.x index!
-@SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom", "Lucene40", "Lucene41", "Lucene42", "TempSep", "TempFixedIntBlock", "TempVariableIntBlock", "TempRandom"})
+@SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom", "Lucene40", "Lucene41", "Lucene42"})
public class TestBackwardsCompatibility extends LuceneTestCase {
// Uncomment these cases & run them on an older Lucene version,
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
index 37cf6044737..b7456251db4 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
@@ -49,7 +49,7 @@ import org.apache.lucene.util._TestUtil;
// TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs.
// not all codecs store prx separate...
// TODO: fix sep codec to index offsets so we can greatly reduce this list!
-@SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom", "TempSep", "TempFixedIntBlock", "TempVariableIntBlock", "TempRandom"})
+@SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom"})
public class TestPostingsOffsets extends LuceneTestCase {
IndexWriterConfig iwc;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsReader.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsReader.java
deleted file mode 100644
index f37cd1c81df..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsReader.java
+++ /dev/null
@@ -1,1165 +0,0 @@
-package org.apache.lucene.codecs.lucene40;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.index.DocsAndPositionsEnum;
-import org.apache.lucene.index.DocsEnum;
-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.TermState;
-import org.apache.lucene.store.ByteArrayDataInput;
-import org.apache.lucene.store.DataInput;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-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.IOUtils;
-
-/**
- * Concrete class that reads the 4.0 frq/prox
- * postings format.
- *
- * @see Temp40RWPostingsFormat
- * @deprecated Only for reading old 4.0 segments */
-@Deprecated
-public class Temp40PostingsReader extends TempPostingsReaderBase {
-
- final static String TERMS_CODEC = "Temp40PostingsWriterTerms";
- final static String FRQ_CODEC = "Temp40PostingsWriterFrq";
- final static String PRX_CODEC = "Temp40PostingsWriterPrx";
-
- //private static boolean DEBUG = BlockTreeTermsWriter.DEBUG;
-
- // Increment version to change it:
- final static int VERSION_START = 0;
- final static int VERSION_LONG_SKIP = 1;
- final static int VERSION_CURRENT = VERSION_LONG_SKIP;
-
- private final IndexInput freqIn;
- private final IndexInput proxIn;
- // public static boolean DEBUG = BlockTreeTermsWriter.DEBUG;
-
- int skipInterval;
- int maxSkipLevels;
- int skipMinimum;
-
- // private String segment;
-
- /** Sole constructor. */
- public Temp40PostingsReader(Directory dir, FieldInfos fieldInfos, SegmentInfo segmentInfo, IOContext ioContext, String segmentSuffix) throws IOException {
- boolean success = false;
- IndexInput freqIn = null;
- IndexInput proxIn = null;
- try {
- freqIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Temp40RWPostingsFormat.FREQ_EXTENSION),
- ioContext);
- CodecUtil.checkHeader(freqIn, FRQ_CODEC, VERSION_START, VERSION_CURRENT);
- // TODO: hasProx should (somehow!) become codec private,
- // but it's tricky because 1) FIS.hasProx is global (it
- // could be all fields that have prox are written by a
- // different codec), 2) the field may have had prox in
- // the past but all docs w/ that field were deleted.
- // Really we'd need to init prxOut lazily on write, and
- // then somewhere record that we actually wrote it so we
- // know whether to open on read:
- if (fieldInfos.hasProx()) {
- proxIn = dir.openInput(IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, Temp40RWPostingsFormat.PROX_EXTENSION),
- ioContext);
- CodecUtil.checkHeader(proxIn, PRX_CODEC, VERSION_START, VERSION_CURRENT);
- } else {
- proxIn = null;
- }
- this.freqIn = freqIn;
- this.proxIn = proxIn;
- success = true;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(freqIn, proxIn);
- }
- }
- }
-
- @Override
- public void init(IndexInput termsIn) throws IOException {
-
- // Make sure we are talking to the matching past writer
- CodecUtil.checkHeader(termsIn, TERMS_CODEC, VERSION_START, VERSION_CURRENT);
-
- skipInterval = termsIn.readInt();
- maxSkipLevels = termsIn.readInt();
- skipMinimum = termsIn.readInt();
- }
-
- // Must keep final because we do non-standard clone
- private final static class StandardTermState extends BlockTermState {
- long freqOffset;
- long proxOffset;
- long skipOffset;
-
- @Override
- public StandardTermState clone() {
- StandardTermState other = new StandardTermState();
- other.copyFrom(this);
- return other;
- }
-
- @Override
- public void copyFrom(TermState _other) {
- super.copyFrom(_other);
- StandardTermState other = (StandardTermState) _other;
- freqOffset = other.freqOffset;
- proxOffset = other.proxOffset;
- skipOffset = other.skipOffset;
- }
-
- @Override
- public String toString() {
- return super.toString() + " freqFP=" + freqOffset + " proxFP=" + proxOffset + " skipOffset=" + skipOffset;
- }
- }
-
- @Override
- public BlockTermState newTermState() {
- return new StandardTermState();
- }
-
- @Override
- public void close() throws IOException {
- try {
- if (freqIn != null) {
- freqIn.close();
- }
- } finally {
- if (proxIn != null) {
- proxIn.close();
- }
- }
- }
-
- @Override
- public void decodeTerm(long[] longs, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute)
- throws IOException {
- final StandardTermState termState = (StandardTermState) _termState;
- // if (DEBUG) System.out.println("SPR: nextTerm seg=" + segment + " tbOrd=" + termState.termBlockOrd + " bytesReader.fp=" + termState.bytesReader.getPosition());
- final boolean isFirstTerm = termState.termBlockOrd == 0;
- if (absolute) {
- termState.freqOffset = 0;
- termState.proxOffset = 0;
- }
-
- termState.freqOffset += in.readVLong();
- /*
- if (DEBUG) {
- System.out.println(" dF=" + termState.docFreq);
- System.out.println(" freqFP=" + termState.freqOffset);
- }
- */
- assert termState.freqOffset < freqIn.length();
-
- if (termState.docFreq >= skipMinimum) {
- termState.skipOffset = in.readVLong();
- // if (DEBUG) System.out.println(" skipOffset=" + termState.skipOffset + " vs freqIn.length=" + freqIn.length());
- assert termState.freqOffset + termState.skipOffset < freqIn.length();
- } else {
- // undefined
- }
-
- if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
- termState.proxOffset += in.readVLong();
- // if (DEBUG) System.out.println(" proxFP=" + termState.proxOffset);
- }
- }
-
- @Override
- public DocsEnum docs(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
- if (canReuse(reuse, liveDocs)) {
- // if (DEBUG) System.out.println("SPR.docs ts=" + termState);
- return ((SegmentDocsEnumBase) reuse).reset(fieldInfo, (StandardTermState)termState);
- }
- return newDocsEnum(liveDocs, fieldInfo, (StandardTermState)termState);
- }
-
- private boolean canReuse(DocsEnum reuse, Bits liveDocs) {
- if (reuse != null && (reuse instanceof SegmentDocsEnumBase)) {
- SegmentDocsEnumBase docsEnum = (SegmentDocsEnumBase) reuse;
- // If you are using ParellelReader, and pass in a
- // reused DocsEnum, it could have come from another
- // reader also using standard codec
- if (docsEnum.startFreqIn == freqIn) {
- // we only reuse if the the actual the incoming enum has the same liveDocs as the given liveDocs
- return liveDocs == docsEnum.liveDocs;
- }
- }
- return false;
- }
-
- private DocsEnum newDocsEnum(Bits liveDocs, FieldInfo fieldInfo, StandardTermState termState) throws IOException {
- if (liveDocs == null) {
- return new AllDocsSegmentDocsEnum(freqIn).reset(fieldInfo, termState);
- } else {
- return new LiveDocsSegmentDocsEnum(freqIn, liveDocs).reset(fieldInfo, termState);
- }
- }
-
- @Override
- public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs,
- DocsAndPositionsEnum reuse, int flags)
- throws IOException {
-
- boolean hasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
-
- // TODO: can we optimize if FLAG_PAYLOADS / FLAG_OFFSETS
- // isn't passed?
-
- // TODO: refactor
- if (fieldInfo.hasPayloads() || hasOffsets) {
- SegmentFullPositionsEnum docsEnum;
- if (reuse == null || !(reuse instanceof SegmentFullPositionsEnum)) {
- docsEnum = new SegmentFullPositionsEnum(freqIn, proxIn);
- } else {
- docsEnum = (SegmentFullPositionsEnum) reuse;
- if (docsEnum.startFreqIn != freqIn) {
- // If you are using ParellelReader, and pass in a
- // reused DocsEnum, it could have come from another
- // reader also using standard codec
- docsEnum = new SegmentFullPositionsEnum(freqIn, proxIn);
- }
- }
- return docsEnum.reset(fieldInfo, (StandardTermState) termState, liveDocs);
- } else {
- SegmentDocsAndPositionsEnum docsEnum;
- if (reuse == null || !(reuse instanceof SegmentDocsAndPositionsEnum)) {
- docsEnum = new SegmentDocsAndPositionsEnum(freqIn, proxIn);
- } else {
- docsEnum = (SegmentDocsAndPositionsEnum) reuse;
- if (docsEnum.startFreqIn != freqIn) {
- // If you are using ParellelReader, and pass in a
- // reused DocsEnum, it could have come from another
- // reader also using standard codec
- docsEnum = new SegmentDocsAndPositionsEnum(freqIn, proxIn);
- }
- }
- return docsEnum.reset(fieldInfo, (StandardTermState) termState, liveDocs);
- }
- }
-
- static final int BUFFERSIZE = 64;
-
- private abstract class SegmentDocsEnumBase extends DocsEnum {
-
- protected final int[] docs = new int[BUFFERSIZE];
- protected final int[] freqs = new int[BUFFERSIZE];
-
- final IndexInput freqIn; // reuse
- final IndexInput startFreqIn; // reuse
- Lucene40SkipListReader skipper; // reuse - lazy loaded
-
- protected boolean indexOmitsTF; // does current field omit term freq?
- protected boolean storePayloads; // does current field store payloads?
- protected boolean storeOffsets; // does current field store offsets?
-
- protected int limit; // number of docs in this posting
- protected int ord; // how many docs we've read
- protected int doc; // doc we last read
- protected int accum; // accumulator for doc deltas
- protected int freq; // freq we last read
- protected int maxBufferedDocId;
-
- protected int start;
- protected int count;
-
-
- protected long freqOffset;
- protected long skipOffset;
-
- protected boolean skipped;
- protected final Bits liveDocs;
-
- SegmentDocsEnumBase(IndexInput startFreqIn, Bits liveDocs) {
- this.startFreqIn = startFreqIn;
- this.freqIn = startFreqIn.clone();
- this.liveDocs = liveDocs;
-
- }
-
-
- DocsEnum reset(FieldInfo fieldInfo, StandardTermState termState) throws IOException {
- indexOmitsTF = fieldInfo.getIndexOptions() == IndexOptions.DOCS_ONLY;
- storePayloads = fieldInfo.hasPayloads();
- storeOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- freqOffset = termState.freqOffset;
- skipOffset = termState.skipOffset;
-
- // TODO: for full enum case (eg segment merging) this
- // seek is unnecessary; maybe we can avoid in such
- // cases
- freqIn.seek(termState.freqOffset);
- limit = termState.docFreq;
- assert limit > 0;
- ord = 0;
- doc = -1;
- accum = 0;
- // if (DEBUG) System.out.println(" sde limit=" + limit + " freqFP=" + freqOffset);
- skipped = false;
-
- start = -1;
- count = 0;
- freq = 1;
- if (indexOmitsTF) {
- Arrays.fill(freqs, 1);
- }
- maxBufferedDocId = -1;
- return this;
- }
-
- @Override
- public final int freq() {
- return freq;
- }
-
- @Override
- public final int docID() {
- return doc;
- }
-
- @Override
- public final int advance(int target) throws IOException {
- // last doc in our buffer is >= target, binary search + next()
- if (++start < count && maxBufferedDocId >= target) {
- if ((count-start) > 32) { // 32 seemed to be a sweetspot here so use binsearch if the pending results are a lot
- start = binarySearch(count - 1, start, target, docs);
- return nextDoc();
- } else {
- return linearScan(target);
- }
- }
-
- start = count; // buffer is consumed
-
- return doc = skipTo(target);
- }
-
- private final int binarySearch(int hi, int low, int target, int[] docs) {
- while (low <= hi) {
- int mid = (hi + low) >>> 1;
- int doc = docs[mid];
- if (doc < target) {
- low = mid + 1;
- } else if (doc > target) {
- hi = mid - 1;
- } else {
- low = mid;
- break;
- }
- }
- return low-1;
- }
-
- final int readFreq(final IndexInput freqIn, final int code)
- throws IOException {
- if ((code & 1) != 0) { // if low bit is set
- return 1; // freq is one
- } else {
- return freqIn.readVInt(); // else read freq
- }
- }
-
- protected abstract int linearScan(int scanTo) throws IOException;
-
- protected abstract int scanTo(int target) throws IOException;
-
- protected final int refill() throws IOException {
- final int doc = nextUnreadDoc();
- count = 0;
- start = -1;
- if (doc == NO_MORE_DOCS) {
- return NO_MORE_DOCS;
- }
- final int numDocs = Math.min(docs.length, limit - ord);
- ord += numDocs;
- if (indexOmitsTF) {
- count = fillDocs(numDocs);
- } else {
- count = fillDocsAndFreqs(numDocs);
- }
- maxBufferedDocId = count > 0 ? docs[count-1] : NO_MORE_DOCS;
- return doc;
- }
-
-
- protected abstract int nextUnreadDoc() throws IOException;
-
-
- private final int fillDocs(int size) throws IOException {
- final IndexInput freqIn = this.freqIn;
- final int docs[] = this.docs;
- int docAc = accum;
- for (int i = 0; i < size; i++) {
- docAc += freqIn.readVInt();
- docs[i] = docAc;
- }
- accum = docAc;
- return size;
- }
-
- private final int fillDocsAndFreqs(int size) throws IOException {
- final IndexInput freqIn = this.freqIn;
- final int docs[] = this.docs;
- final int freqs[] = this.freqs;
- int docAc = accum;
- for (int i = 0; i < size; i++) {
- final int code = freqIn.readVInt();
- docAc += code >>> 1; // shift off low bit
- freqs[i] = readFreq(freqIn, code);
- docs[i] = docAc;
- }
- accum = docAc;
- return size;
-
- }
-
- private final int skipTo(int target) throws IOException {
- if ((target - skipInterval) >= accum && limit >= skipMinimum) {
-
- // There are enough docs in the posting to have
- // skip data, and it isn't too close.
-
- if (skipper == null) {
- // This is the first time this enum has ever been used for skipping -- do lazy init
- skipper = new Lucene40SkipListReader(freqIn.clone(), maxSkipLevels, skipInterval);
- }
-
- if (!skipped) {
-
- // This is the first time this posting has
- // skipped since reset() was called, so now we
- // load the skip data for this posting
-
- skipper.init(freqOffset + skipOffset,
- freqOffset, 0,
- limit, storePayloads, storeOffsets);
-
- skipped = true;
- }
-
- final int newOrd = skipper.skipTo(target);
-
- if (newOrd > ord) {
- // Skipper moved
-
- ord = newOrd;
- accum = skipper.getDoc();
- freqIn.seek(skipper.getFreqPointer());
- }
- }
- return scanTo(target);
- }
-
- @Override
- public long cost() {
- return limit;
- }
- }
-
- private final class AllDocsSegmentDocsEnum extends SegmentDocsEnumBase {
-
- AllDocsSegmentDocsEnum(IndexInput startFreqIn) {
- super(startFreqIn, null);
- assert liveDocs == null;
- }
-
- @Override
- public final int nextDoc() throws IOException {
- if (++start < count) {
- freq = freqs[start];
- return doc = docs[start];
- }
- return doc = refill();
- }
-
-
- @Override
- protected final int linearScan(int scanTo) throws IOException {
- final int[] docs = this.docs;
- final int upTo = count;
- for (int i = start; i < upTo; i++) {
- final int d = docs[i];
- if (scanTo <= d) {
- start = i;
- freq = freqs[i];
- return doc = docs[i];
- }
- }
- return doc = refill();
- }
-
- @Override
- protected int scanTo(int target) throws IOException {
- int docAcc = accum;
- int frq = 1;
- final IndexInput freqIn = this.freqIn;
- final boolean omitTF = indexOmitsTF;
- final int loopLimit = limit;
- for (int i = ord; i < loopLimit; i++) {
- int code = freqIn.readVInt();
- if (omitTF) {
- docAcc += code;
- } else {
- docAcc += code >>> 1; // shift off low bit
- frq = readFreq(freqIn, code);
- }
- if (docAcc >= target) {
- freq = frq;
- ord = i + 1;
- return accum = docAcc;
- }
- }
- ord = limit;
- freq = frq;
- accum = docAcc;
- return NO_MORE_DOCS;
- }
-
- @Override
- protected final int nextUnreadDoc() throws IOException {
- if (ord++ < limit) {
- int code = freqIn.readVInt();
- if (indexOmitsTF) {
- accum += code;
- } else {
- accum += code >>> 1; // shift off low bit
- freq = readFreq(freqIn, code);
- }
- return accum;
- } else {
- return NO_MORE_DOCS;
- }
- }
-
- }
-
- private final class LiveDocsSegmentDocsEnum extends SegmentDocsEnumBase {
-
- LiveDocsSegmentDocsEnum(IndexInput startFreqIn, Bits liveDocs) {
- super(startFreqIn, liveDocs);
- assert liveDocs != null;
- }
-
- @Override
- public final int nextDoc() throws IOException {
- final Bits liveDocs = this.liveDocs;
- for (int i = start+1; i < count; i++) {
- int d = docs[i];
- if (liveDocs.get(d)) {
- start = i;
- freq = freqs[i];
- return doc = d;
- }
- }
- start = count;
- return doc = refill();
- }
-
- @Override
- protected final int linearScan(int scanTo) throws IOException {
- final int[] docs = this.docs;
- final int upTo = count;
- final Bits liveDocs = this.liveDocs;
- for (int i = start; i < upTo; i++) {
- int d = docs[i];
- if (scanTo <= d && liveDocs.get(d)) {
- start = i;
- freq = freqs[i];
- return doc = docs[i];
- }
- }
- return doc = refill();
- }
-
- @Override
- protected int scanTo(int target) throws IOException {
- int docAcc = accum;
- int frq = 1;
- final IndexInput freqIn = this.freqIn;
- final boolean omitTF = indexOmitsTF;
- final int loopLimit = limit;
- final Bits liveDocs = this.liveDocs;
- for (int i = ord; i < loopLimit; i++) {
- int code = freqIn.readVInt();
- if (omitTF) {
- docAcc += code;
- } else {
- docAcc += code >>> 1; // shift off low bit
- frq = readFreq(freqIn, code);
- }
- if (docAcc >= target && liveDocs.get(docAcc)) {
- freq = frq;
- ord = i + 1;
- return accum = docAcc;
- }
- }
- ord = limit;
- freq = frq;
- accum = docAcc;
- return NO_MORE_DOCS;
- }
-
- @Override
- protected final int nextUnreadDoc() throws IOException {
- int docAcc = accum;
- int frq = 1;
- final IndexInput freqIn = this.freqIn;
- final boolean omitTF = indexOmitsTF;
- final int loopLimit = limit;
- final Bits liveDocs = this.liveDocs;
- for (int i = ord; i < loopLimit; i++) {
- int code = freqIn.readVInt();
- if (omitTF) {
- docAcc += code;
- } else {
- docAcc += code >>> 1; // shift off low bit
- frq = readFreq(freqIn, code);
- }
- if (liveDocs.get(docAcc)) {
- freq = frq;
- ord = i + 1;
- return accum = docAcc;
- }
- }
- ord = limit;
- freq = frq;
- accum = docAcc;
- return NO_MORE_DOCS;
-
- }
- }
-
- // TODO specialize DocsAndPosEnum too
-
- // Decodes docs & positions. payloads nor offsets are present.
- private final class SegmentDocsAndPositionsEnum extends DocsAndPositionsEnum {
- final IndexInput startFreqIn;
- private final IndexInput freqIn;
- private final IndexInput proxIn;
- int limit; // number of docs in this posting
- int ord; // how many docs we've read
- int doc = -1; // doc we last read
- int accum; // accumulator for doc deltas
- int freq; // freq we last read
- int position;
-
- Bits liveDocs;
-
- long freqOffset;
- long skipOffset;
- long proxOffset;
-
- int posPendingCount;
-
- boolean skipped;
- Lucene40SkipListReader skipper;
- private long lazyProxPointer;
-
- public SegmentDocsAndPositionsEnum(IndexInput freqIn, IndexInput proxIn) {
- startFreqIn = freqIn;
- this.freqIn = freqIn.clone();
- this.proxIn = proxIn.clone();
- }
-
- public SegmentDocsAndPositionsEnum reset(FieldInfo fieldInfo, StandardTermState termState, Bits liveDocs) throws IOException {
- assert fieldInfo.getIndexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
- assert !fieldInfo.hasPayloads();
-
- this.liveDocs = liveDocs;
-
- // TODO: for full enum case (eg segment merging) this
- // seek is unnecessary; maybe we can avoid in such
- // cases
- freqIn.seek(termState.freqOffset);
- lazyProxPointer = termState.proxOffset;
-
- limit = termState.docFreq;
- assert limit > 0;
-
- ord = 0;
- doc = -1;
- accum = 0;
- position = 0;
-
- skipped = false;
- posPendingCount = 0;
-
- freqOffset = termState.freqOffset;
- proxOffset = termState.proxOffset;
- skipOffset = termState.skipOffset;
- // if (DEBUG) System.out.println("StandardR.D&PE reset seg=" + segment + " limit=" + limit + " freqFP=" + freqOffset + " proxFP=" + proxOffset);
-
- return this;
- }
-
- @Override
- public int nextDoc() throws IOException {
- // if (DEBUG) System.out.println("SPR.nextDoc seg=" + segment + " freqIn.fp=" + freqIn.getFilePointer());
- while(true) {
- if (ord == limit) {
- // if (DEBUG) System.out.println(" return END");
- return doc = NO_MORE_DOCS;
- }
-
- ord++;
-
- // Decode next doc/freq pair
- final int code = freqIn.readVInt();
-
- accum += code >>> 1; // shift off low bit
- if ((code & 1) != 0) { // if low bit is set
- freq = 1; // freq is one
- } else {
- freq = freqIn.readVInt(); // else read freq
- }
- posPendingCount += freq;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- break;
- }
- }
-
- position = 0;
-
- // if (DEBUG) System.out.println(" return doc=" + doc);
- return (doc = accum);
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- @Override
- public int freq() {
- return freq;
- }
-
- @Override
- public int advance(int target) throws IOException {
-
- //System.out.println("StandardR.D&PE advance target=" + target);
-
- if ((target - skipInterval) >= doc && limit >= skipMinimum) {
-
- // There are enough docs in the posting to have
- // skip data, and it isn't too close
-
- if (skipper == null) {
- // This is the first time this enum has ever been used for skipping -- do lazy init
- skipper = new Lucene40SkipListReader(freqIn.clone(), maxSkipLevels, skipInterval);
- }
-
- if (!skipped) {
-
- // This is the first time this posting has
- // skipped, since reset() was called, so now we
- // load the skip data for this posting
-
- skipper.init(freqOffset+skipOffset,
- freqOffset, proxOffset,
- limit, false, false);
-
- skipped = true;
- }
-
- final int newOrd = skipper.skipTo(target);
-
- if (newOrd > ord) {
- // Skipper moved
- ord = newOrd;
- doc = accum = skipper.getDoc();
- freqIn.seek(skipper.getFreqPointer());
- lazyProxPointer = skipper.getProxPointer();
- posPendingCount = 0;
- position = 0;
- }
- }
-
- // Now, linear scan for the rest:
- do {
- nextDoc();
- } while (target > doc);
-
- return doc;
- }
-
- @Override
- public int nextPosition() throws IOException {
-
- if (lazyProxPointer != -1) {
- proxIn.seek(lazyProxPointer);
- lazyProxPointer = -1;
- }
-
- // scan over any docs that were iterated without their positions
- if (posPendingCount > freq) {
- position = 0;
- while(posPendingCount != freq) {
- if ((proxIn.readByte() & 0x80) == 0) {
- posPendingCount--;
- }
- }
- }
-
- position += proxIn.readVInt();
-
- posPendingCount--;
-
- assert posPendingCount >= 0: "nextPosition() was called too many times (more than freq() times) posPendingCount=" + posPendingCount;
-
- return position;
- }
-
- @Override
- public int startOffset() {
- return -1;
- }
-
- @Override
- public int endOffset() {
- return -1;
- }
-
- /** Returns the payload at this position, or null if no
- * payload was indexed. */
- @Override
- public BytesRef getPayload() throws IOException {
- return null;
- }
-
- @Override
- public long cost() {
- return limit;
- }
- }
-
- // Decodes docs & positions & (payloads and/or offsets)
- private class SegmentFullPositionsEnum extends DocsAndPositionsEnum {
- final IndexInput startFreqIn;
- private final IndexInput freqIn;
- private final IndexInput proxIn;
-
- int limit; // number of docs in this posting
- int ord; // how many docs we've read
- int doc = -1; // doc we last read
- int accum; // accumulator for doc deltas
- int freq; // freq we last read
- int position;
-
- Bits liveDocs;
-
- long freqOffset;
- long skipOffset;
- long proxOffset;
-
- int posPendingCount;
- int payloadLength;
- boolean payloadPending;
-
- boolean skipped;
- Lucene40SkipListReader skipper;
- private BytesRef payload;
- private long lazyProxPointer;
-
- boolean storePayloads;
- boolean storeOffsets;
-
- int offsetLength;
- int startOffset;
-
- public SegmentFullPositionsEnum(IndexInput freqIn, IndexInput proxIn) {
- startFreqIn = freqIn;
- this.freqIn = freqIn.clone();
- this.proxIn = proxIn.clone();
- }
-
- public SegmentFullPositionsEnum reset(FieldInfo fieldInfo, StandardTermState termState, Bits liveDocs) throws IOException {
- storeOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- storePayloads = fieldInfo.hasPayloads();
- assert fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
- assert storePayloads || storeOffsets;
- if (payload == null) {
- payload = new BytesRef();
- payload.bytes = new byte[1];
- }
-
- this.liveDocs = liveDocs;
-
- // TODO: for full enum case (eg segment merging) this
- // seek is unnecessary; maybe we can avoid in such
- // cases
- freqIn.seek(termState.freqOffset);
- lazyProxPointer = termState.proxOffset;
-
- limit = termState.docFreq;
- ord = 0;
- doc = -1;
- accum = 0;
- position = 0;
- startOffset = 0;
-
- skipped = false;
- posPendingCount = 0;
- payloadPending = false;
-
- freqOffset = termState.freqOffset;
- proxOffset = termState.proxOffset;
- skipOffset = termState.skipOffset;
- //System.out.println("StandardR.D&PE reset seg=" + segment + " limit=" + limit + " freqFP=" + freqOffset + " proxFP=" + proxOffset + " this=" + this);
-
- return this;
- }
-
- @Override
- public int nextDoc() throws IOException {
- while(true) {
- if (ord == limit) {
- //System.out.println("StandardR.D&PE seg=" + segment + " nextDoc return doc=END");
- return doc = NO_MORE_DOCS;
- }
-
- ord++;
-
- // Decode next doc/freq pair
- final int code = freqIn.readVInt();
-
- accum += code >>> 1; // shift off low bit
- if ((code & 1) != 0) { // if low bit is set
- freq = 1; // freq is one
- } else {
- freq = freqIn.readVInt(); // else read freq
- }
- posPendingCount += freq;
-
- if (liveDocs == null || liveDocs.get(accum)) {
- break;
- }
- }
-
- position = 0;
- startOffset = 0;
-
- //System.out.println("StandardR.D&PE nextDoc seg=" + segment + " return doc=" + doc);
- return (doc = accum);
- }
-
- @Override
- public int docID() {
- return doc;
- }
-
- @Override
- public int freq() throws IOException {
- return freq;
- }
-
- @Override
- public int advance(int target) throws IOException {
-
- //System.out.println("StandardR.D&PE advance seg=" + segment + " target=" + target + " this=" + this);
-
- if ((target - skipInterval) >= doc && limit >= skipMinimum) {
-
- // There are enough docs in the posting to have
- // skip data, and it isn't too close
-
- if (skipper == null) {
- // This is the first time this enum has ever been used for skipping -- do lazy init
- skipper = new Lucene40SkipListReader(freqIn.clone(), maxSkipLevels, skipInterval);
- }
-
- if (!skipped) {
-
- // This is the first time this posting has
- // skipped, since reset() was called, so now we
- // load the skip data for this posting
- //System.out.println(" init skipper freqOffset=" + freqOffset + " skipOffset=" + skipOffset + " vs len=" + freqIn.length());
- skipper.init(freqOffset+skipOffset,
- freqOffset, proxOffset,
- limit, storePayloads, storeOffsets);
-
- skipped = true;
- }
-
- final int newOrd = skipper.skipTo(target);
-
- if (newOrd > ord) {
- // Skipper moved
- ord = newOrd;
- doc = accum = skipper.getDoc();
- freqIn.seek(skipper.getFreqPointer());
- lazyProxPointer = skipper.getProxPointer();
- posPendingCount = 0;
- position = 0;
- startOffset = 0;
- payloadPending = false;
- payloadLength = skipper.getPayloadLength();
- offsetLength = skipper.getOffsetLength();
- }
- }
-
- // Now, linear scan for the rest:
- do {
- nextDoc();
- } while (target > doc);
-
- return doc;
- }
-
- @Override
- public int nextPosition() throws IOException {
-
- if (lazyProxPointer != -1) {
- proxIn.seek(lazyProxPointer);
- lazyProxPointer = -1;
- }
-
- if (payloadPending && payloadLength > 0) {
- // payload of last position was never retrieved -- skip it
- proxIn.seek(proxIn.getFilePointer() + payloadLength);
- payloadPending = false;
- }
-
- // scan over any docs that were iterated without their positions
- while(posPendingCount > freq) {
- final int code = proxIn.readVInt();
-
- if (storePayloads) {
- if ((code & 1) != 0) {
- // new payload length
- payloadLength = proxIn.readVInt();
- assert payloadLength >= 0;
- }
- assert payloadLength != -1;
- }
-
- if (storeOffsets) {
- if ((proxIn.readVInt() & 1) != 0) {
- // new offset length
- offsetLength = proxIn.readVInt();
- }
- }
-
- if (storePayloads) {
- proxIn.seek(proxIn.getFilePointer() + payloadLength);
- }
-
- posPendingCount--;
- position = 0;
- startOffset = 0;
- payloadPending = false;
- //System.out.println("StandardR.D&PE skipPos");
- }
-
- // read next position
- if (payloadPending && payloadLength > 0) {
- // payload wasn't retrieved for last position
- proxIn.seek(proxIn.getFilePointer()+payloadLength);
- }
-
- int code = proxIn.readVInt();
- if (storePayloads) {
- if ((code & 1) != 0) {
- // new payload length
- payloadLength = proxIn.readVInt();
- assert payloadLength >= 0;
- }
- assert payloadLength != -1;
-
- payloadPending = true;
- code >>>= 1;
- }
- position += code;
-
- if (storeOffsets) {
- int offsetCode = proxIn.readVInt();
- if ((offsetCode & 1) != 0) {
- // new offset length
- offsetLength = proxIn.readVInt();
- }
- startOffset += offsetCode >>> 1;
- }
-
- posPendingCount--;
-
- assert posPendingCount >= 0: "nextPosition() was called too many times (more than freq() times) posPendingCount=" + posPendingCount;
-
- //System.out.println("StandardR.D&PE nextPos return pos=" + position);
- return position;
- }
-
- @Override
- public int startOffset() throws IOException {
- return storeOffsets ? startOffset : -1;
- }
-
- @Override
- public int endOffset() throws IOException {
- return storeOffsets ? startOffset + offsetLength : -1;
- }
-
- /** Returns the payload at this position, or null if no
- * payload was indexed. */
- @Override
- public BytesRef getPayload() throws IOException {
- if (storePayloads) {
- if (payloadLength <= 0) {
- return null;
- }
- assert lazyProxPointer == -1;
- assert posPendingCount < freq;
-
- if (payloadPending) {
- if (payloadLength > payload.bytes.length) {
- payload.grow(payloadLength);
- }
-
- proxIn.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
- payloadPending = false;
- }
-
- return payload;
- } else {
- return null;
- }
- }
-
- @Override
- public long cost() {
- return limit;
- }
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsWriter.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsWriter.java
deleted file mode 100644
index 707d5b38f0d..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40PostingsWriter.java
+++ /dev/null
@@ -1,333 +0,0 @@
-package org.apache.lucene.codecs.lucene40;
-
-/*
- * 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.
- */
-
-/** Consumes doc & freq, writing them using the current
- * index file format */
-
-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.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.DocsEnum;
-import org.apache.lucene.index.FieldInfo.IndexOptions;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.store.RAMOutputStream;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-/**
- * Concrete class that writes the 4.0 frq/prx postings format.
- *
- * @see Temp40RWPostingsFormat
- * @lucene.experimental
- */
-public final class Temp40PostingsWriter extends TempPostingsWriterBase {
-
- final IndexOutput freqOut;
- final IndexOutput proxOut;
- final Lucene40SkipListWriter skipListWriter;
- /** Expert: The fraction of TermDocs entries stored in skip tables,
- * used to accelerate {@link DocsEnum#advance(int)}. Larger values result in
- * smaller indexes, greater acceleration, but fewer accelerable cases, while
- * smaller values result in bigger indexes, less acceleration and more
- * accelerable cases. More detailed experiments would be useful here. */
- static final int DEFAULT_SKIP_INTERVAL = 16;
- final int skipInterval;
-
- /**
- * Expert: minimum docFreq to write any skip data at all
- */
- final int skipMinimum;
-
- /** Expert: The maximum number of skip levels. Smaller values result in
- * slightly smaller indexes, but slower skipping in big posting lists.
- */
- final int maxSkipLevels = 10;
- final int totalNumDocs;
-
- IndexOptions indexOptions;
- boolean storePayloads;
- boolean storeOffsets;
- // Starts a new term
- long freqStart;
- long proxStart;
- FieldInfo fieldInfo;
- int lastPayloadLength;
- int lastOffsetLength;
- int lastPosition;
- int lastOffset;
-
- final static StandardTermState emptyState = new StandardTermState();
- StandardTermState lastState;
-
- // private String segment;
-
- /** Creates a {@link Temp40PostingsWriter}, with the
- * {@link #DEFAULT_SKIP_INTERVAL}. */
- public Temp40PostingsWriter(SegmentWriteState state) throws IOException {
- this(state, DEFAULT_SKIP_INTERVAL);
- }
-
- /** Creates a {@link Temp40PostingsWriter}, with the
- * specified {@code skipInterval}. */
- public Temp40PostingsWriter(SegmentWriteState state, int skipInterval) throws IOException {
- super();
- this.skipInterval = skipInterval;
- this.skipMinimum = skipInterval; /* set to the same for now */
- // this.segment = state.segmentName;
- String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Temp40RWPostingsFormat.FREQ_EXTENSION);
- freqOut = state.directory.createOutput(fileName, state.context);
- boolean success = false;
- IndexOutput proxOut = null;
- try {
- CodecUtil.writeHeader(freqOut, Temp40PostingsReader.FRQ_CODEC, Temp40PostingsReader.VERSION_CURRENT);
- // TODO: this is a best effort, if one of these fields has no postings
- // then we make an empty prx file, same as if we are wrapped in
- // per-field postingsformat. maybe... we shouldn't
- // bother w/ this opto? just create empty prx file...?
- if (state.fieldInfos.hasProx()) {
- // At least one field does not omit TF, so create the
- // prox file
- fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Temp40RWPostingsFormat.PROX_EXTENSION);
- proxOut = state.directory.createOutput(fileName, state.context);
- CodecUtil.writeHeader(proxOut, Temp40PostingsReader.PRX_CODEC, Temp40PostingsReader.VERSION_CURRENT);
- } else {
- // Every field omits TF so we will write no prox file
- proxOut = null;
- }
- this.proxOut = proxOut;
- success = true;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(freqOut, proxOut);
- }
- }
-
- totalNumDocs = state.segmentInfo.getDocCount();
-
- skipListWriter = new Lucene40SkipListWriter(skipInterval,
- maxSkipLevels,
- totalNumDocs,
- freqOut,
- proxOut);
- }
-
- @Override
- public void init(IndexOutput termsOut) throws IOException {
- CodecUtil.writeHeader(termsOut, Temp40PostingsReader.TERMS_CODEC, Temp40PostingsReader.VERSION_CURRENT);
- termsOut.writeInt(skipInterval); // write skipInterval
- termsOut.writeInt(maxSkipLevels); // write maxSkipLevels
- termsOut.writeInt(skipMinimum); // write skipMinimum
- }
-
- @Override
- public BlockTermState newTermState() {
- return new StandardTermState();
- }
-
-
- @Override
- public void startTerm() {
- freqStart = freqOut.getFilePointer();
- //if (DEBUG) System.out.println("SPW: startTerm freqOut.fp=" + freqStart);
- if (proxOut != null) {
- proxStart = proxOut.getFilePointer();
- }
- // force first payload to write its length
- lastPayloadLength = -1;
- // force first offset to write its length
- lastOffsetLength = -1;
- skipListWriter.resetSkip();
- }
-
- // Currently, this instance is re-used across fields, so
- // our parent calls setField whenever the field changes
- @Override
- public int setField(FieldInfo fieldInfo) {
- //System.out.println("SPW: setField");
- /*
- if (BlockTreeTermsWriter.DEBUG && fieldInfo.name.equals("id")) {
- DEBUG = true;
- } else {
- DEBUG = false;
- }
- */
- this.fieldInfo = fieldInfo;
- indexOptions = fieldInfo.getIndexOptions();
-
- storeOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
- storePayloads = fieldInfo.hasPayloads();
- lastState = emptyState;
- //System.out.println(" set init blockFreqStart=" + freqStart);
- //System.out.println(" set init blockProxStart=" + proxStart);
- return 0;
- }
-
- int lastDocID;
- int df;
-
- @Override
- public void startDoc(int docID, int termDocFreq) throws IOException {
- // if (DEBUG) System.out.println("SPW: startDoc seg=" + segment + " docID=" + docID + " tf=" + termDocFreq + " freqOut.fp=" + freqOut.getFilePointer());
-
- final int delta = docID - lastDocID;
-
- if (docID < 0 || (df > 0 && delta <= 0)) {
- throw new CorruptIndexException("docs out of order (" + docID + " <= " + lastDocID + " ) (freqOut: " + freqOut + ")");
- }
-
- if ((++df % skipInterval) == 0) {
- skipListWriter.setSkipData(lastDocID, storePayloads, lastPayloadLength, storeOffsets, lastOffsetLength);
- skipListWriter.bufferSkip(df);
- }
-
- assert docID < totalNumDocs: "docID=" + docID + " totalNumDocs=" + totalNumDocs;
-
- lastDocID = docID;
- if (indexOptions == IndexOptions.DOCS_ONLY) {
- freqOut.writeVInt(delta);
- } else if (1 == termDocFreq) {
- freqOut.writeVInt((delta<<1) | 1);
- } else {
- freqOut.writeVInt(delta<<1);
- freqOut.writeVInt(termDocFreq);
- }
-
- lastPosition = 0;
- lastOffset = 0;
- }
-
- /** Add a new position & payload */
- @Override
- public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {
- //if (DEBUG) System.out.println("SPW: addPos pos=" + position + " payload=" + (payload == null ? "null" : (payload.length + " bytes")) + " proxFP=" + proxOut.getFilePointer());
- assert indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 : "invalid indexOptions: " + indexOptions;
- assert proxOut != null;
-
- final int delta = position - lastPosition;
-
- assert delta >= 0: "position=" + position + " lastPosition=" + lastPosition; // not quite right (if pos=0 is repeated twice we don't catch it)
-
- lastPosition = position;
-
- int payloadLength = 0;
-
- if (storePayloads) {
- payloadLength = payload == null ? 0 : payload.length;
-
- if (payloadLength != lastPayloadLength) {
- lastPayloadLength = payloadLength;
- proxOut.writeVInt((delta<<1)|1);
- proxOut.writeVInt(payloadLength);
- } else {
- proxOut.writeVInt(delta << 1);
- }
- } else {
- proxOut.writeVInt(delta);
- }
-
- if (storeOffsets) {
- // don't use startOffset - lastEndOffset, because this creates lots of negative vints for synonyms,
- // and the numbers aren't that much smaller anyways.
- int offsetDelta = startOffset - lastOffset;
- int offsetLength = endOffset - startOffset;
- assert offsetDelta >= 0 && offsetLength >= 0 : "startOffset=" + startOffset + ",lastOffset=" + lastOffset + ",endOffset=" + endOffset;
- if (offsetLength != lastOffsetLength) {
- proxOut.writeVInt(offsetDelta << 1 | 1);
- proxOut.writeVInt(offsetLength);
- } else {
- proxOut.writeVInt(offsetDelta << 1);
- }
- lastOffset = startOffset;
- lastOffsetLength = offsetLength;
- }
-
- if (payloadLength > 0) {
- proxOut.writeBytes(payload.bytes, payload.offset, payloadLength);
- }
- }
-
- @Override
- public void finishDoc() {
- }
-
- private static class StandardTermState extends BlockTermState {
- public long freqStart;
- public long proxStart;
- public long skipOffset;
- }
-
- /** Called when we are done adding docs to this term */
- @Override
- public void finishTerm(BlockTermState _state) throws IOException {
- StandardTermState state = (StandardTermState)_state;
- // if (DEBUG) System.out.println("SPW: finishTerm seg=" + segment + " freqStart=" + freqStart);
- assert state.docFreq > 0;
-
- // TODO: wasteful we are counting this (counting # docs
- // for this term) in two places?
- assert state.docFreq == df;
- state.freqStart = freqStart;
- state.proxStart = proxStart;
- if (df >= skipMinimum) {
- state.skipOffset = skipListWriter.writeSkip(freqOut)-freqStart;
- } else {
- state.skipOffset = -1;
- }
- lastDocID = 0;
- df = 0;
- }
-
- @Override
- public void encodeTerm(long[] empty, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
- StandardTermState state = (StandardTermState)_state;
- if (absolute) {
- lastState = emptyState;
- }
- out.writeVLong(state.freqStart - lastState.freqStart);
- if (state.skipOffset != -1) {
- assert state.skipOffset > 0;
- out.writeVLong(state.skipOffset);
- }
- if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {
- out.writeVLong(state.proxStart - lastState.proxStart);
- }
- lastState = state;
- }
-
- @Override
- public void close() throws IOException {
- try {
- freqOut.close();
- } finally {
- if (proxOut != null) {
- proxOut.close();
- }
- }
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40RWPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40RWPostingsFormat.java
deleted file mode 100644
index 0ceb800d9ea..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Temp40RWPostingsFormat.java
+++ /dev/null
@@ -1,118 +0,0 @@
-package org.apache.lucene.codecs.lucene40;
-
-import java.io.IOException;
-
-import org.apache.lucene.codecs.temp.*;
-import org.apache.lucene.codecs.BlockTreeTermsReader;
-import org.apache.lucene.codecs.BlockTreeTermsWriter;
-import org.apache.lucene.codecs.CodecUtil;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.index.DocsEnum; // javadocs
-import org.apache.lucene.index.FieldInfo.IndexOptions; // javadocs
-import org.apache.lucene.index.FieldInfos; // javadocs
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.DataOutput; // javadocs
-import org.apache.lucene.util.fst.FST; // javadocs
-
-
-/*
- * 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.
- */
-
-/**
- * Read-write version of {@link Lucene40PostingsFormat} for testing.
- */
-public class Temp40RWPostingsFormat extends PostingsFormat {
- /** minimum items (terms or sub-blocks) per block for BlockTree */
- protected final int minBlockSize;
- /** maximum items (terms or sub-blocks) per block for BlockTree */
- protected final int maxBlockSize;
-
- /** Creates {@code Lucene40PostingsFormat} with default
- * settings. */
- public Temp40RWPostingsFormat() {
- this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
- }
-
- /** Creates {@code Lucene40PostingsFormat} with custom
- * values for {@code minBlockSize} and {@code
- * maxBlockSize} passed to block terms dictionary.
- * @see BlockTreeTermsWriter#BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int) */
- private Temp40RWPostingsFormat(int minBlockSize, int maxBlockSize) {
- super("Temp40RW");
- this.minBlockSize = minBlockSize;
- assert minBlockSize > 1;
- this.maxBlockSize = maxBlockSize;
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postings = new Temp40PostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
-
- boolean success = false;
- try {
- FieldsProducer ret = new TempBlockTreeTermsReader(
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postings,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- postings.close();
- }
- }
- }
-
- /** Extension of freq postings file */
- static final String FREQ_EXTENSION = "frq";
-
- /** Extension of prox postings file */
- static final String PROX_EXTENSION = "prx";
-
- @Override
- public String toString() {
- return getName() + "(minBlockSize=" + minBlockSize + " maxBlockSize=" + maxBlockSize + ")";
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase docs = new Temp40PostingsWriter(state);
-
- // TODO: should we make the terms index more easily
- // pluggable? Ie so that this codec would record which
- // index impl was used, and switch on loading?
- // Or... you must make a new Codec for this?
- boolean success = false;
- try {
- FieldsConsumer ret = new TempBlockTreeTermsWriter(state, docs, minBlockSize, maxBlockSize);
- success = true;
- return ret;
- } finally {
- if (!success) {
- docs.close();
- }
- }
- }
-}
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.java
index 405e18b776e..e8ec71562e8 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
@@ -50,6 +50,10 @@ import org.apache.lucene.codecs.sep.IntIndexOutput;
import org.apache.lucene.codecs.sep.IntStreamFactory;
import org.apache.lucene.codecs.sep.SepPostingsReader;
import org.apache.lucene.codecs.sep.SepPostingsWriter;
+import org.apache.lucene.codecs.temp.TempFSTTermsWriter;
+import org.apache.lucene.codecs.temp.TempFSTTermsReader;
+import org.apache.lucene.codecs.temp.TempFSTOrdTermsWriter;
+import org.apache.lucene.codecs.temp.TempFSTOrdTermsReader;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentReadState;
@@ -187,10 +191,8 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
}
final FieldsConsumer fields;
- final int t1 = random.nextInt(2);
-
- /*
final int t1 = random.nextInt(4);
+
if (t1 == 0) {
boolean success = false;
try {
@@ -212,8 +214,6 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
}
}
} else if (t1 == 2) {
- */
- if (t1 == 0) {
// Use BlockTree terms dict
if (LuceneTestCase.VERBOSE) {
@@ -351,8 +351,6 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
}
final FieldsProducer fields;
- final int t1 = random.nextInt(2);
- /*
final int t1 = random.nextInt(4);
if (t1 == 0) {
boolean success = false;
@@ -375,8 +373,6 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
}
}
} else if (t1 == 2) {
- */
- if (t1 == 0) {
// Use BlockTree terms dict
if (LuceneTestCase.VERBOSE) {
System.out.println("MockRandomCodec: reading BlockTree terms dict");
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempFixedIntBlockPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempFixedIntBlockPostingsFormat.java
deleted file mode 100644
index 34d9f7cabf9..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempFixedIntBlockPostingsFormat.java
+++ /dev/null
@@ -1,198 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.blockterms.BlockTermsReader;
-import org.apache.lucene.codecs.blockterms.BlockTermsWriter;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
-import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
-import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
-import org.apache.lucene.codecs.intblock.FixedIntBlockIndexInput;
-import org.apache.lucene.codecs.intblock.FixedIntBlockIndexOutput;
-import org.apache.lucene.codecs.sep.*;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.store.*;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-/**
- * A silly test codec to verify core support for fixed
- * sized int block encoders is working. The int encoder
- * used here just writes each block as a series of vInt.
- */
-
-public final class TempFixedIntBlockPostingsFormat extends PostingsFormat {
-
- private final int blockSize;
-
- public TempFixedIntBlockPostingsFormat() {
- this(1);
- }
-
- public TempFixedIntBlockPostingsFormat(int blockSize) {
- super("TempFixedIntBlock");
- this.blockSize = blockSize;
- }
-
- @Override
- public String toString() {
- return getName() + "(blockSize=" + blockSize + ")";
- }
-
- // only for testing
- public IntStreamFactory getIntFactory() {
- return new MockIntFactory(blockSize);
- }
-
- /**
- * Encodes blocks as vInts of a fixed block size.
- */
- public static class MockIntFactory extends IntStreamFactory {
- private final int blockSize;
-
- public MockIntFactory(int blockSize) {
- this.blockSize = blockSize;
- }
-
- @Override
- public IntIndexInput openInput(Directory dir, String fileName, IOContext context) throws IOException {
- return new FixedIntBlockIndexInput(dir.openInput(fileName, context)) {
-
- @Override
- protected BlockReader getBlockReader(final IndexInput in, final int[] buffer) {
- return new BlockReader() {
- public void seek(long pos) {}
- @Override
- public void readBlock() throws IOException {
- for(int i=0;i<buffer.length;i++) {
- buffer[i] = in.readVInt();
- }
- }
- };
- }
- };
- }
-
- @Override
- public IntIndexOutput createOutput(Directory dir, String fileName, IOContext context) throws IOException {
- IndexOutput out = dir.createOutput(fileName, context);
- boolean success = false;
- try {
- FixedIntBlockIndexOutput ret = new FixedIntBlockIndexOutput(out, blockSize) {
- @Override
- protected void flushBlock() throws IOException {
- for(int i=0;i<buffer.length;i++) {
- out.writeVInt(buffer[i]);
- }
- }
- };
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(out);
- }
- }
- }
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase postingsWriter = new TempSepPostingsWriter(state, new MockIntFactory(blockSize));
-
- boolean success = false;
- TermsIndexWriterBase indexWriter;
- try {
- indexWriter = new FixedGapTermsIndexWriter(state);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
-
- success = false;
- try {
- FieldsConsumer ret = new TempBlockTermsWriter(indexWriter, state, postingsWriter);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsWriter.close();
- } finally {
- indexWriter.close();
- }
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postingsReader = new TempSepPostingsReader(state.directory,
- state.fieldInfos,
- state.segmentInfo,
- state.context,
- new MockIntFactory(blockSize), state.segmentSuffix);
-
- TermsIndexReaderBase indexReader;
- boolean success = false;
- try {
- indexReader = new FixedGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- BytesRef.getUTF8SortedAsUnicodeComparator(), state.segmentSuffix,
- IOContext.DEFAULT);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
-
- success = false;
- try {
- FieldsProducer ret = new TempBlockTermsReader(indexReader,
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postingsReader,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsReader.close();
- } finally {
- indexReader.close();
- }
- }
- }
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempRandomPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempRandomPostingsFormat.java
deleted file mode 100644
index 16afc37c1b3..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempRandomPostingsFormat.java
+++ /dev/null
@@ -1,459 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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 java.util.Random;
-
-import org.apache.lucene.codecs.BlockTreeTermsReader;
-import org.apache.lucene.codecs.BlockTreeTermsWriter;
-import org.apache.lucene.codecs.FieldsConsumer;
-import org.apache.lucene.codecs.FieldsProducer;
-import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.TermStats;
-import org.apache.lucene.codecs.blockterms.BlockTermsReader;
-import org.apache.lucene.codecs.blockterms.BlockTermsWriter;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
-import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
-import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
-import org.apache.lucene.codecs.blockterms.VariableGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.VariableGapTermsIndexWriter;
-import org.apache.lucene.codecs.lucene41.Lucene41PostingsReader;
-import org.apache.lucene.codecs.lucene41.Lucene41PostingsWriter;
-import org.apache.lucene.codecs.mockintblock.MockFixedIntBlockPostingsFormat;
-import org.apache.lucene.codecs.mockintblock.MockVariableIntBlockPostingsFormat;
-import org.apache.lucene.codecs.mocksep.MockSingleIntFactory;
-import org.apache.lucene.codecs.pulsing.PulsingPostingsReader;
-import org.apache.lucene.codecs.pulsing.PulsingPostingsWriter;
-import org.apache.lucene.codecs.sep.IntIndexInput;
-import org.apache.lucene.codecs.sep.IntIndexOutput;
-import org.apache.lucene.codecs.sep.IntStreamFactory;
-import org.apache.lucene.codecs.sep.TempSepPostingsReader;
-import org.apache.lucene.codecs.sep.TempSepPostingsWriter;
-import org.apache.lucene.index.FieldInfo;
-import org.apache.lucene.index.IndexFileNames;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.LuceneTestCase;
-import org.apache.lucene.util._TestUtil;
-
-/**
- * Randomly combines terms index impl w/ postings impls.
- */
-
-public final class TempRandomPostingsFormat extends PostingsFormat {
- private final Random seedRandom;
- private final String SEED_EXT = "sd";
-
- public TempRandomPostingsFormat() {
- // This ctor should *only* be used at read-time: get NPE if you use it!
- this(null);
- }
-
- public TempRandomPostingsFormat(Random random) {
- super("TempRandom");
- if (random == null) {
- this.seedRandom = new Random(0L) {
- @Override
- protected int next(int arg0) {
- throw new IllegalStateException("Please use MockRandomPostingsFormat(Random)");
- }
- };
- } else {
- this.seedRandom = new Random(random.nextLong());
- }
- }
-
- // Chooses random IntStreamFactory depending on file's extension
- private static class MockIntStreamFactory extends IntStreamFactory {
- private final int salt;
- private final List<IntStreamFactory> delegates = new ArrayList<IntStreamFactory>();
-
- public MockIntStreamFactory(Random random) {
- salt = random.nextInt();
- delegates.add(new MockSingleIntFactory());
- final int blockSize = _TestUtil.nextInt(random, 1, 2000);
- delegates.add(new MockFixedIntBlockPostingsFormat.MockIntFactory(blockSize));
- final int baseBlockSize = _TestUtil.nextInt(random, 1, 127);
- delegates.add(new MockVariableIntBlockPostingsFormat.MockIntFactory(baseBlockSize));
- // TODO: others
- }
-
- private static String getExtension(String fileName) {
- final int idx = fileName.indexOf('.');
- assert idx != -1;
- return fileName.substring(idx);
- }
-
- @Override
- public IntIndexInput openInput(Directory dir, String fileName, IOContext context) throws IOException {
- // Must only use extension, because IW.addIndexes can
- // rename segment!
- final IntStreamFactory f = delegates.get((Math.abs(salt ^ getExtension(fileName).hashCode())) % delegates.size());
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: read using int factory " + f + " from fileName=" + fileName);
- }
- return f.openInput(dir, fileName, context);
- }
-
- @Override
- public IntIndexOutput createOutput(Directory dir, String fileName, IOContext context) throws IOException {
- final IntStreamFactory f = delegates.get((Math.abs(salt ^ getExtension(fileName).hashCode())) % delegates.size());
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: write using int factory " + f + " to fileName=" + fileName);
- }
- return f.createOutput(dir, fileName, context);
- }
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- int minSkipInterval;
- if (state.segmentInfo.getDocCount() > 1000000) {
- // Test2BPostings can OOME otherwise:
- minSkipInterval = 3;
- } else {
- minSkipInterval = 2;
- }
-
- // we pull this before the seed intentionally: because its not consumed at runtime
- // (the skipInterval is written into postings header)
- int skipInterval = _TestUtil.nextInt(seedRandom, minSkipInterval, 10);
-
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: skipInterval=" + skipInterval);
- }
-
- final long seed = seedRandom.nextLong();
-
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: writing to seg=" + state.segmentInfo.name + " formatID=" + state.segmentSuffix + " seed=" + seed);
- }
-
- final String seedFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, SEED_EXT);
- final IndexOutput out = state.directory.createOutput(seedFileName, state.context);
- try {
- out.writeLong(seed);
- } finally {
- out.close();
- }
-
- final Random random = new Random(seed);
-
- random.nextInt(); // consume a random for buffersize
-
- TempPostingsWriterBase postingsWriter;
- if (random.nextBoolean()) {
- postingsWriter = new TempSepPostingsWriter(state, new MockIntStreamFactory(random), skipInterval);
- } else {
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: writing Standard postings");
- }
- // TODO: randomize variables like acceptibleOverHead?!
- postingsWriter = new TempPostingsWriter(state, skipInterval);
- }
-
- if (random.nextBoolean()) {
- final int totTFCutoff = _TestUtil.nextInt(random, 1, 20);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: writing pulsing postings with totTFCutoff=" + totTFCutoff);
- }
- postingsWriter = new TempPulsingPostingsWriter(state, totTFCutoff, postingsWriter);
- }
-
- final FieldsConsumer fields;
- final int t1 = random.nextInt(4);
-
- if (t1 == 0) {
- boolean success = false;
- try {
- fields = new TempFSTTermsWriter(state, postingsWriter);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
- } else if (t1 == 1) {
- boolean success = false;
- try {
- fields = new TempFSTOrdTermsWriter(state, postingsWriter);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
- } else if (t1 == 2) {
- // Use BlockTree terms dict
-
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: writing BlockTree terms dict");
- }
-
- // 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 TempBlockTreeTermsWriter(state, postingsWriter, minTermsInBlock, maxTermsInBlock);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
- } else {
-
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: writing Block terms dict");
- }
-
- boolean success = false;
-
- final TermsIndexWriterBase indexWriter;
- try {
- if (random.nextBoolean()) {
- int termIndexInterval = _TestUtil.nextInt(random, 1, 100);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: fixed-gap terms index (tii=" + termIndexInterval + ")");
- }
- indexWriter = new FixedGapTermsIndexWriter(state, termIndexInterval);
- } else {
- final VariableGapTermsIndexWriter.IndexTermSelector selector;
- final int n2 = random.nextInt(3);
- if (n2 == 0) {
- final int tii = _TestUtil.nextInt(random, 1, 100);
- selector = new VariableGapTermsIndexWriter.EveryNTermSelector(tii);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: variable-gap terms index (tii=" + tii + ")");
- }
- } else if (n2 == 1) {
- final int docFreqThresh = _TestUtil.nextInt(random, 2, 100);
- final int tii = _TestUtil.nextInt(random, 1, 100);
- selector = new VariableGapTermsIndexWriter.EveryNOrDocFreqTermSelector(docFreqThresh, tii);
- } else {
- final long seed2 = random.nextLong();
- final int gap = _TestUtil.nextInt(random, 2, 40);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: random-gap terms index (max gap=" + gap + ")");
- }
- selector = new VariableGapTermsIndexWriter.IndexTermSelector() {
- final Random rand = new Random(seed2);
-
- @Override
- public boolean isIndexTerm(BytesRef term, TermStats stats) {
- return rand.nextInt(gap) == gap/2;
- }
-
- @Override
- public void newField(FieldInfo fieldInfo) {
- }
- };
- }
- indexWriter = new VariableGapTermsIndexWriter(state, selector);
- }
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
-
- success = false;
- try {
- fields = new TempBlockTermsWriter(indexWriter, state, postingsWriter);
- success = true;
- } finally {
- if (!success) {
- try {
- postingsWriter.close();
- } finally {
- indexWriter.close();
- }
- }
- }
- }
-
- return fields;
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
-
- final String seedFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, SEED_EXT);
- final IndexInput in = state.directory.openInput(seedFileName, state.context);
- final long seed = in.readLong();
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading from seg=" + state.segmentInfo.name + " formatID=" + state.segmentSuffix + " seed=" + seed);
- }
- in.close();
-
- final Random random = new Random(seed);
-
- int readBufferSize = _TestUtil.nextInt(random, 1, 4096);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: readBufferSize=" + readBufferSize);
- }
-
- TempPostingsReaderBase postingsReader;
-
- if (random.nextBoolean()) {
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading Sep postings");
- }
- postingsReader = new TempSepPostingsReader(state.directory, state.fieldInfos, state.segmentInfo,
- state.context, new MockIntStreamFactory(random), state.segmentSuffix);
- } else {
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading Standard postings");
- }
- postingsReader = new TempPostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
- }
-
- if (random.nextBoolean()) {
- final int totTFCutoff = _TestUtil.nextInt(random, 1, 20);
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading pulsing postings with totTFCutoff=" + totTFCutoff);
- }
- postingsReader = new TempPulsingPostingsReader(state, postingsReader);
- }
-
- final FieldsProducer fields;
- final int t1 = random.nextInt(4);
- if (t1 == 0) {
- boolean success = false;
- try {
- fields = new TempFSTTermsReader(state, postingsReader);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
- } else if (t1 == 1) {
- boolean success = false;
- try {
- fields = new TempFSTOrdTermsReader(state, postingsReader);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
- } else if (t1 == 2) {
- // Use BlockTree terms dict
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading BlockTree terms dict");
- }
-
- boolean success = false;
- try {
- fields = new TempBlockTreeTermsReader(state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postingsReader,
- state.context,
- state.segmentSuffix);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
- } else {
-
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: reading Block terms dict");
- }
- final TermsIndexReaderBase indexReader;
- boolean success = false;
- try {
- final boolean doFixedGap = random.nextBoolean();
-
- // randomness diverges from writer, here:
-
- if (doFixedGap) {
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: fixed-gap terms index");
- }
- indexReader = new FixedGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- BytesRef.getUTF8SortedAsUnicodeComparator(),
- state.segmentSuffix, state.context);
- } else {
- final int n2 = random.nextInt(3);
- if (n2 == 1) {
- random.nextInt();
- } else if (n2 == 2) {
- random.nextLong();
- }
- if (LuceneTestCase.VERBOSE) {
- System.out.println("MockRandomCodec: variable-gap terms index");
- }
- indexReader = new VariableGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- state.segmentSuffix, state.context);
-
- }
-
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
-
- success = false;
- try {
- fields = new TempBlockTermsReader(indexReader,
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postingsReader,
- state.context,
- state.segmentSuffix);
- success = true;
- } finally {
- if (!success) {
- try {
- postingsReader.close();
- } finally {
- indexReader.close();
- }
- }
- }
- }
-
- return fields;
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempSepPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempSepPostingsFormat.java
deleted file mode 100644
index ecb51678caf..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempSepPostingsFormat.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
-import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
-import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
-import org.apache.lucene.codecs.sep.*;
-import org.apache.lucene.codecs.mocksep.*;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.util.BytesRef;
-
-/**
- * A silly codec that simply writes each file separately as
- * single vInts. Don't use this (performance will be poor)!
- * This is here just to test the core sep codec
- * classes.
- */
-public final class TempSepPostingsFormat extends PostingsFormat {
-
- public TempSepPostingsFormat() {
- super("TempSep");
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
-
- TempPostingsWriterBase postingsWriter = new TempSepPostingsWriter(state, new MockSingleIntFactory());
-
- boolean success = false;
- TermsIndexWriterBase indexWriter;
- try {
- indexWriter = new FixedGapTermsIndexWriter(state);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
-
- success = false;
- try {
- FieldsConsumer ret = new TempBlockTermsWriter(indexWriter, state, postingsWriter);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsWriter.close();
- } finally {
- indexWriter.close();
- }
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
-
- TempPostingsReaderBase postingsReader = new TempSepPostingsReader(state.directory, state.fieldInfos, state.segmentInfo,
- state.context, new MockSingleIntFactory(), state.segmentSuffix);
-
- TermsIndexReaderBase indexReader;
- boolean success = false;
- try {
- indexReader = new FixedGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- BytesRef.getUTF8SortedAsUnicodeComparator(),
- state.segmentSuffix, state.context);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
-
- success = false;
- try {
- FieldsProducer ret = new TempBlockTermsReader(indexReader,
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postingsReader,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsReader.close();
- } finally {
- indexReader.close();
- }
- }
- }
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempVariableIntBlockPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempVariableIntBlockPostingsFormat.java
deleted file mode 100644
index 5c9986ef6f9..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/temp/TempVariableIntBlockPostingsFormat.java
+++ /dev/null
@@ -1,223 +0,0 @@
-package org.apache.lucene.codecs.temp;
-
-/*
- * 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.TempPostingsReaderBase;
-import org.apache.lucene.codecs.TempPostingsWriterBase;
-import org.apache.lucene.codecs.blockterms.BlockTermsReader;
-import org.apache.lucene.codecs.blockterms.BlockTermsWriter;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
-import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
-import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
-import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
-import org.apache.lucene.codecs.intblock.VariableIntBlockIndexInput;
-import org.apache.lucene.codecs.intblock.VariableIntBlockIndexOutput;
-import org.apache.lucene.codecs.sep.*;
-import org.apache.lucene.index.SegmentWriteState;
-import org.apache.lucene.index.SegmentReadState;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.IOContext;
-import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-
-/**
- * A silly test codec to verify core support for variable
- * sized int block encoders is working. The int encoder
- * used here writes baseBlockSize ints at once, if the first
- * int is <= 3, else 2*baseBlockSize.
- */
-
-public final class TempVariableIntBlockPostingsFormat extends PostingsFormat {
- private final int baseBlockSize;
-
- public TempVariableIntBlockPostingsFormat() {
- this(1);
- }
-
- public TempVariableIntBlockPostingsFormat(int baseBlockSize) {
- super("TempVariableIntBlock");
- this.baseBlockSize = baseBlockSize;
- }
-
- @Override
- public String toString() {
- return getName() + "(baseBlockSize="+ baseBlockSize + ")";
- }
-
- /**
- * If the first value is <= 3, writes baseBlockSize vInts at once,
- * otherwise writes 2*baseBlockSize vInts.
- */
- public static class MockIntFactory extends IntStreamFactory {
-
- private final int baseBlockSize;
-
- public MockIntFactory(int baseBlockSize) {
- this.baseBlockSize = baseBlockSize;
- }
-
- @Override
- public IntIndexInput openInput(Directory dir, String fileName, IOContext context) throws IOException {
- final IndexInput in = dir.openInput(fileName, context);
- final int baseBlockSize = in.readInt();
- return new VariableIntBlockIndexInput(in) {
-
- @Override
- protected BlockReader getBlockReader(final IndexInput in, final int[] buffer) {
- return new BlockReader() {
- @Override
- public void seek(long pos) {}
- @Override
- public int readBlock() throws IOException {
- buffer[0] = in.readVInt();
- final int count = buffer[0] <= 3 ? baseBlockSize-1 : 2*baseBlockSize-1;
- assert buffer.length >= count: "buffer.length=" + buffer.length + " count=" + count;
- for(int i=0;i<count;i++) {
- buffer[i+1] = in.readVInt();
- }
- return 1+count;
- }
- };
- }
- };
- }
-
- @Override
- public IntIndexOutput createOutput(Directory dir, String fileName, IOContext context) throws IOException {
- final IndexOutput out = dir.createOutput(fileName, context);
- boolean success = false;
- try {
- out.writeInt(baseBlockSize);
- VariableIntBlockIndexOutput ret = new VariableIntBlockIndexOutput(out, 2*baseBlockSize) {
- int pendingCount;
- final int[] buffer = new int[2+2*baseBlockSize];
-
- @Override
- protected int add(int value) throws IOException {
- buffer[pendingCount++] = value;
- // silly variable block length int encoder: if
- // first value <= 3, we write N vints at once;
- // else, 2*N
- final int flushAt = buffer[0] <= 3 ? baseBlockSize : 2*baseBlockSize;
-
- // intentionally be non-causal here:
- if (pendingCount == flushAt+1) {
- for(int i=0;i<flushAt;i++) {
- out.writeVInt(buffer[i]);
- }
- buffer[0] = buffer[flushAt];
- pendingCount = 1;
- return flushAt;
- } else {
- return 0;
- }
- }
- };
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(out);
- }
- }
- }
- }
-
- @Override
- public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- TempPostingsWriterBase postingsWriter = new TempSepPostingsWriter(state, new MockIntFactory(baseBlockSize));
-
- boolean success = false;
- TermsIndexWriterBase indexWriter;
- try {
- indexWriter = new FixedGapTermsIndexWriter(state);
- success = true;
- } finally {
- if (!success) {
- postingsWriter.close();
- }
- }
-
- success = false;
- try {
- FieldsConsumer ret = new TempBlockTermsWriter(indexWriter, state, postingsWriter);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsWriter.close();
- } finally {
- indexWriter.close();
- }
- }
- }
- }
-
- @Override
- public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- TempPostingsReaderBase postingsReader = new TempSepPostingsReader(state.directory,
- state.fieldInfos,
- state.segmentInfo,
- state.context,
- new MockIntFactory(baseBlockSize), state.segmentSuffix);
-
- TermsIndexReaderBase indexReader;
- boolean success = false;
- try {
- indexReader = new FixedGapTermsIndexReader(state.directory,
- state.fieldInfos,
- state.segmentInfo.name,
- BytesRef.getUTF8SortedAsUnicodeComparator(),
- state.segmentSuffix, state.context);
- success = true;
- } finally {
- if (!success) {
- postingsReader.close();
- }
- }
-
- success = false;
- try {
- FieldsProducer ret = new TempBlockTermsReader(indexReader,
- state.directory,
- state.fieldInfos,
- state.segmentInfo,
- postingsReader,
- state.context,
- state.segmentSuffix);
- success = true;
- return ret;
- } finally {
- if (!success) {
- try {
- postingsReader.close();
- } finally {
- indexReader.close();
- }
- }
- }
- }
-}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/RandomCodec.java b/lucene/test-framework/src/java/org/apache/lucene/index/RandomCodec.java
index 36e05121426..8a9e9717110 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/RandomCodec.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/RandomCodec.java
@@ -50,7 +50,10 @@ import org.apache.lucene.codecs.nestedpulsing.NestedPulsingPostingsFormat;
import org.apache.lucene.codecs.pulsing.Pulsing41PostingsFormat;
import org.apache.lucene.codecs.simpletext.SimpleTextPostingsFormat;
import org.apache.lucene.codecs.simpletext.SimpleTextDocValuesFormat;
-import org.apache.lucene.codecs.temp.*;
+import org.apache.lucene.codecs.temp.TempFSTOrdPostingsFormat;
+import org.apache.lucene.codecs.temp.TempFSTOrdPulsing41PostingsFormat;
+import org.apache.lucene.codecs.temp.TempFSTPostingsFormat;
+import org.apache.lucene.codecs.temp.TempFSTPulsing41PostingsFormat;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
@@ -124,10 +127,12 @@ public class RandomCodec extends Lucene45Codec {
int maxItemsPerBlock = 2*(Math.max(2, minItemsPerBlock-1)) + random.nextInt(100);
int lowFreqCutoff = _TestUtil.nextInt(random, 2, 100);
- // nocommit: temporary disable other format tests
- /*
add(avoidCodecs,
new Lucene41PostingsFormat(minItemsPerBlock, maxItemsPerBlock),
+ new TempFSTPostingsFormat(),
+ new TempFSTOrdPostingsFormat(),
+ new TempFSTPulsing41PostingsFormat(1 + random.nextInt(20)),
+ new TempFSTOrdPulsing41PostingsFormat(1 + random.nextInt(20)),
new DirectPostingsFormat(LuceneTestCase.rarely(random) ? 1 : (LuceneTestCase.rarely(random) ? Integer.MAX_VALUE : maxItemsPerBlock),
LuceneTestCase.rarely(random) ? 1 : (LuceneTestCase.rarely(random) ? Integer.MAX_VALUE : lowFreqCutoff)),
new Pulsing41PostingsFormat(1 + random.nextInt(20), minItemsPerBlock, maxItemsPerBlock),
@@ -149,14 +154,7 @@ public class RandomCodec extends Lucene45Codec {
new AssertingPostingsFormat(),
new MemoryPostingsFormat(true, random.nextFloat()),
new MemoryPostingsFormat(false, random.nextFloat()));
- */
- add(avoidCodecs,
- new TempBlockPostingsFormat(_TestUtil.nextInt(random, 1, 1000)),
- new TempBlockTreePostingsFormat(minItemsPerBlock, maxItemsPerBlock),
- new TempRandomPostingsFormat(random),
- new TempNestedPulsingPostingsFormat(),
- new TempPulsing41PostingsFormat(1 + random.nextInt(20), minItemsPerBlock, maxItemsPerBlock));
-
+
addDocValues(avoidCodecs,
new Lucene45DocValuesFormat(),
new DiskDocValuesFormat(),
diff --git a/lucene/test-framework/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/test-framework/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
index fe4b4e58d80..59d0dd3f33f 100644
--- a/lucene/test-framework/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
+++ b/lucene/test-framework/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
@@ -25,8 +25,3 @@ org.apache.lucene.codecs.lucene41vargap.Lucene41VarGapDocFreqInterval
org.apache.lucene.codecs.bloom.TestBloomFilteredLucene41Postings
org.apache.lucene.codecs.asserting.AssertingPostingsFormat
org.apache.lucene.codecs.lucene40.Lucene40RWPostingsFormat
-org.apache.lucene.codecs.temp.TempSepPostingsFormat
-org.apache.lucene.codecs.temp.TempFixedIntBlockPostingsFormat
-org.apache.lucene.codecs.temp.TempVariableIntBlockPostingsFormat
-org.apache.lucene.codecs.temp.TempRandomPostingsFormat
-org.apache.lucene.codecs.lucene40.Temp40RWPostingsFormat