You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by so...@apache.org on 2019/05/27 00:07:32 UTC
[lucene-solr] branch branch_8x updated: LUCENE-8781: FST lookup
performance has been improved in many cases by encoding Arcs using
full-sized arrays with gaps. The new encoding is enabled for postings in
the default codec and for suggesters. (Mike Sokolov)
This is an automated email from the ASF dual-hosted git repository.
sokolov pushed a commit to branch branch_8x
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git
The following commit(s) were added to refs/heads/branch_8x by this push:
new d046e67 LUCENE-8781: FST lookup performance has been improved in many cases by encoding Arcs using full-sized arrays with gaps. The new encoding is enabled for postings in the default codec and for suggesters. (Mike Sokolov)
d046e67 is described below
commit d046e67f9620caed65746bad03443d9b9e8f99b6
Author: Dawid Weiss <dw...@apache.org>
AuthorDate: Mon May 6 11:19:35 2019 +0200
LUCENE-8781: FST lookup performance has been improved in many cases by encoding Arcs using full-sized arrays with gaps. The new encoding is enabled for postings in the default codec and for suggesters. (Mike Sokolov)
---
.../ja/util/TokenInfoDictionaryBuilder.java | 2 +-
.../ko/util/TokenInfoDictionaryBuilder.java | 2 +-
.../blocktreeords/OrdsBlockTreeTermsWriter.java | 2 +-
.../codecs/blocktreeords/OrdsSegmentTermsEnum.java | 2 -
.../codecs/blocktree/BlockTreeTermsWriter.java | 2 +-
.../java/org/apache/lucene/util/fst/Builder.java | 17 +-
.../org/apache/lucene/util/fst/BytesStore.java | 6 +-
.../src/java/org/apache/lucene/util/fst/FST.java | 262 ++++++---
.../java/org/apache/lucene/util/fst/FSTEnum.java | 588 +++++++++++++--------
.../java/org/apache/lucene/util/fst/NodeHash.java | 4 +-
.../src/java/org/apache/lucene/util/fst/Util.java | 6 +-
.../test/org/apache/lucene/util/fst/Test2BFST.java | 32 +-
.../test/org/apache/lucene/util/fst/TestFSTs.java | 8 +-
.../org/apache/lucene/util/fst/TestFstDirect.java | 217 ++++++++
.../idversion/VersionBlockTreeTermsWriter.java | 2 +-
.../search/suggest/fst/FSTCompletionBuilder.java | 2 +-
.../lucene/search/suggest/LookupBenchmarkTest.java | 31 +-
.../java/org/apache/lucene/util/fst/FSTTester.java | 5 +-
18 files changed, 852 insertions(+), 338 deletions(-)
diff --git a/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java b/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
index 1b8abbb..7175308 100644
--- a/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
+++ b/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
@@ -131,7 +131,7 @@ public class TokenInfoDictionaryBuilder {
System.out.println(" encode...");
PositiveIntOutputs fstOutput = PositiveIntOutputs.getSingleton();
- Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, 0, 0, true, true, Integer.MAX_VALUE, fstOutput, true, 15);
+ Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, 0, 0, true, true, Integer.MAX_VALUE, fstOutput, true, 15, false);
IntsRefBuilder scratch = new IntsRefBuilder();
long ord = -1; // first ord will be 0
String lastValue = null;
diff --git a/lucene/analysis/nori/src/tools/java/org/apache/lucene/analysis/ko/util/TokenInfoDictionaryBuilder.java b/lucene/analysis/nori/src/tools/java/org/apache/lucene/analysis/ko/util/TokenInfoDictionaryBuilder.java
index d5fb73f..f46d967 100644
--- a/lucene/analysis/nori/src/tools/java/org/apache/lucene/analysis/ko/util/TokenInfoDictionaryBuilder.java
+++ b/lucene/analysis/nori/src/tools/java/org/apache/lucene/analysis/ko/util/TokenInfoDictionaryBuilder.java
@@ -109,7 +109,7 @@ public class TokenInfoDictionaryBuilder {
System.out.println(" encode...");
PositiveIntOutputs fstOutput = PositiveIntOutputs.getSingleton();
- Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, 0, 0, true, true, Integer.MAX_VALUE, fstOutput, true, 15);
+ Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, 0, 0, true, true, Integer.MAX_VALUE, fstOutput, true, 15, false);
IntsRefBuilder scratch = new IntsRefBuilder();
long ord = -1; // first ord will be 0
String lastValue = null;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
index bdc0738..a0dd5fb 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
@@ -363,7 +363,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
final Builder<Output> indexBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1,
0, 0, true, false, Integer.MAX_VALUE,
- FST_OUTPUTS, true, 15);
+ FST_OUTPUTS, true, 15, false);
//if (DEBUG) {
// System.out.println(" compile index for prefix=" + prefix);
//}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
index f1d930e..756cda8 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
@@ -1082,12 +1082,10 @@ public final class OrdsSegmentTermsEnum extends BaseTermsEnum {
if (FST.targetHasArcs(arc)) {
// System.out.println(" targetHasArcs");
result.grow(1+upto);
-
fr.index.readFirstRealTargetArc(arc.target, arc, fstReader);
if (arc.bytesPerArc != 0) {
// System.out.println(" array arcs");
-
int low = 0;
int high = arc.numArcs-1;
int mid = 0;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
index ec3f6e6..caa4aef 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
@@ -456,7 +456,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
final ByteSequenceOutputs outputs = ByteSequenceOutputs.getSingleton();
final Builder<BytesRef> indexBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1,
0, 0, true, false, Integer.MAX_VALUE,
- outputs, true, 15);
+ outputs, true, 15, true);
//if (DEBUG) {
// System.out.println(" compile index for prefix=" + prefix);
//}
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java b/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
index 5662cbe..cf3a433 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
@@ -49,6 +49,10 @@ import org.apache.lucene.util.fst.FST.INPUT_TYPE; // javadoc
*/
public class Builder<T> {
+
+ // The amount of Arc array oversizing used to enable direct addressing of Arcs by their labels
+ static final int DIRECT_ARC_LOAD_FACTOR = 4;
+
private final NodeHash<T> dedupHash;
final FST<T> fst;
private final T NO_OUTPUT;
@@ -69,6 +73,8 @@ public class Builder<T> {
private final IntsRefBuilder lastInput = new IntsRefBuilder();
+ final boolean useDirectArcAddressing;
+
// NOTE: cutting this over to ArrayList instead loses ~6%
// in build performance on 9.8M Wikipedia terms; so we
// left this as an array:
@@ -92,12 +98,12 @@ public class Builder<T> {
BytesStore bytes;
/**
- * Instantiates an FST/FSA builder without any pruning. A shortcut
- * to {@link #Builder(FST.INPUT_TYPE, int, int, boolean,
- * boolean, int, Outputs, boolean, int)} with pruning options turned off.
+ * Instantiates an FST/FSA builder without any pruning. A shortcut to {@link
+ * #Builder(FST.INPUT_TYPE, int, int, boolean, boolean, int, Outputs, boolean, int, boolean)} with
+ * pruning options turned off.
*/
public Builder(FST.INPUT_TYPE inputType, Outputs<T> outputs) {
- this(inputType, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15);
+ this(inputType, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15, false);
}
/**
@@ -148,12 +154,13 @@ public class Builder<T> {
*/
public Builder(FST.INPUT_TYPE inputType, int minSuffixCount1, int minSuffixCount2, boolean doShareSuffix,
boolean doShareNonSingletonNodes, int shareMaxTailLength, Outputs<T> outputs,
- boolean allowArrayArcs, int bytesPageBits) {
+ boolean allowArrayArcs, int bytesPageBits, boolean useDirectArcAddressing) {
this.minSuffixCount1 = minSuffixCount1;
this.minSuffixCount2 = minSuffixCount2;
this.doShareNonSingletonNodes = doShareNonSingletonNodes;
this.shareMaxTailLength = shareMaxTailLength;
this.allowArrayArcs = allowArrayArcs;
+ this.useDirectArcAddressing = useDirectArcAddressing;
fst = new FST<>(inputType, outputs, bytesPageBits);
bytes = fst.bytes;
assert bytes != null;
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java b/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java
index 96f5732..37b2baa 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java
@@ -77,10 +77,10 @@ class BytesStore extends DataOutput implements Accountable {
/** Absolute write byte; you must ensure dest is < max
* position written so far. */
- public void writeByte(int dest, byte b) {
- int blockIndex = dest >> blockBits;
+ public void writeByte(long dest, byte b) {
+ int blockIndex = (int) (dest >> blockBits);
byte[] block = blocks.get(blockIndex);
- block[dest & blockMask] = b;
+ block[(int) (dest & blockMask)] = b;
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java b/lucene/core/src/java/org/apache/lucene/util/fst/FST.java
index 5a5169b..afc9a3f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/FST.java
@@ -83,7 +83,13 @@ public final class FST<T> implements Accountable {
// We use this as a marker (because this one flag is
// illegal by itself ...):
- private static final byte ARCS_AS_FIXED_ARRAY = BIT_ARC_HAS_FINAL_OUTPUT;
+ private static final byte ARCS_AS_ARRAY_PACKED = BIT_ARC_HAS_FINAL_OUTPUT;
+
+ // this means either of these things in different contexts
+ // in the midst of a direct array:
+ private static final byte BIT_MISSING_ARC = 1 << 6;
+ // at the start of a direct array:
+ private static final byte ARCS_AS_ARRAY_WITH_GAPS = BIT_MISSING_ARC;
/**
* @see #shouldExpand(Builder, Builder.UnCompiledNode)
@@ -160,10 +166,14 @@ public final class FST<T> implements Accountable {
* lookups. */
public int bytesPerArc;
- /** Where we are in the array; only valid if bytesPerArc != 0. */
+ /** Where we are in the array; only valid if bytesPerArc != 0, and the array has no holes.
+ * arcIdx = Integer.MIN_VALUE indicates that the arc is part of a direct array, addressed by
+ * label.
+ */
public int arcIdx;
- /** How many arcs in the array; only valid if bytesPerArc != 0. */
+ /** How many arc, if bytesPerArc == 0. Otherwise, the size of the arc array. If the array is
+ * direct, this may include holes. Otherwise it is also how many arcs are in the array */
public int numArcs;
/** Returns this */
@@ -496,10 +506,10 @@ public final class FST<T> implements Accountable {
final int v;
if (inputType == INPUT_TYPE.BYTE1) {
// Unsigned byte:
- v = in.readByte()&0xFF;
+ v = in.readByte() & 0xFF;
} else if (inputType == INPUT_TYPE.BYTE2) {
// Unsigned short:
- v = in.readShort()&0xFFFF;
+ v = in.readShort() & 0xFFFF;
} else {
v = in.readVInt();
}
@@ -543,7 +553,7 @@ public final class FST<T> implements Accountable {
long lastArcStart = builder.bytes.getPosition();
int maxBytesPerArc = 0;
- for(int arcIdx=0;arcIdx<nodeIn.numArcs;arcIdx++) {
+ for(int arcIdx=0; arcIdx < nodeIn.numArcs; arcIdx++) {
final Builder.Arc<T> arc = nodeIn.arcs[arcIdx];
final Builder.CompiledNode target = (Builder.CompiledNode) arc.target;
int flags = 0;
@@ -600,9 +610,8 @@ public final class FST<T> implements Accountable {
builder.bytes.writeVLong(target.node);
}
- // just write the arcs "like normal" on first pass,
- // but record how many bytes each one took, and max
- // byte size:
+ // just write the arcs "like normal" on first pass, but record how many bytes each one took
+ // and max byte size:
if (doFixedArray) {
builder.reusedBytesPerArc[arcIdx] = (int) (builder.bytes.getPosition() - lastArcStart);
lastArcStart = builder.bytes.getPosition();
@@ -610,7 +619,7 @@ public final class FST<T> implements Accountable {
//System.out.println(" bytes=" + builder.reusedBytesPerArc[arcIdx]);
}
}
-
+
// TODO: try to avoid wasteful cases: disable doFixedArray in that case
/*
*
@@ -634,8 +643,14 @@ public final class FST<T> implements Accountable {
if (doFixedArray) {
final int MAX_HEADER_SIZE = 11; // header(byte) + numArcs(vint) + numBytes(vint)
assert maxBytesPerArc > 0;
- // 2nd pass just "expands" all arcs to take up a fixed
- // byte size
+ // 2nd pass just "expands" all arcs to take up a fixed byte size
+
+ // If more than (1 / DIRECT_ARC_LOAD_FACTOR) of the "slots" would be occupied, write an arc
+ // array that may have holes in it so that we can address the arcs directly by label without
+ // binary search
+ int labelRange = nodeIn.arcs[nodeIn.numArcs - 1].label - nodeIn.arcs[0].label + 1;
+ boolean writeDirectly = builder.useDirectArcAddressing && labelRange > 0
+ && labelRange < Builder.DIRECT_ARC_LOAD_FACTOR * nodeIn.numArcs;
//System.out.println("write int @pos=" + (fixedArrayStart-4) + " numArcs=" + nodeIn.numArcs);
// create the header
@@ -643,29 +658,22 @@ public final class FST<T> implements Accountable {
byte header[] = new byte[MAX_HEADER_SIZE];
ByteArrayDataOutput bad = new ByteArrayDataOutput(header);
// write a "false" first arc:
- bad.writeByte(ARCS_AS_FIXED_ARRAY);
- bad.writeVInt(nodeIn.numArcs);
+ if (writeDirectly) {
+ bad.writeByte(ARCS_AS_ARRAY_WITH_GAPS);
+ bad.writeVInt(labelRange);
+ } else {
+ bad.writeByte(ARCS_AS_ARRAY_PACKED);
+ bad.writeVInt(nodeIn.numArcs);
+ }
bad.writeVInt(maxBytesPerArc);
int headerLen = bad.getPosition();
final long fixedArrayStart = startAddress + headerLen;
- // expand the arcs in place, backwards
- long srcPos = builder.bytes.getPosition();
- long destPos = fixedArrayStart + nodeIn.numArcs*maxBytesPerArc;
- assert destPos >= srcPos;
- if (destPos > srcPos) {
- builder.bytes.skipBytes((int) (destPos - srcPos));
- for(int arcIdx=nodeIn.numArcs-1;arcIdx>=0;arcIdx--) {
- destPos -= maxBytesPerArc;
- srcPos -= builder.reusedBytesPerArc[arcIdx];
- //System.out.println(" repack arcIdx=" + arcIdx + " srcPos=" + srcPos + " destPos=" + destPos);
- if (srcPos != destPos) {
- //System.out.println(" copy len=" + builder.reusedBytesPerArc[arcIdx]);
- assert destPos > srcPos: "destPos=" + destPos + " srcPos=" + srcPos + " arcIdx=" + arcIdx + " maxBytesPerArc=" + maxBytesPerArc + " reusedBytesPerArc[arcIdx]=" + builder.reusedBytesPerArc[arcIdx] + " nodeIn.numArcs=" + nodeIn.numArcs;
- builder.bytes.copyBytes(srcPos, destPos, builder.reusedBytesPerArc[arcIdx]);
- }
- }
+ if (writeDirectly) {
+ writeArrayWithGaps(builder, nodeIn, fixedArrayStart, maxBytesPerArc, labelRange);
+ } else {
+ writeArrayPacked(builder, nodeIn, fixedArrayStart, maxBytesPerArc);
}
// now write the header
@@ -680,6 +688,63 @@ public final class FST<T> implements Accountable {
return thisNodeAddress;
}
+ private void writeArrayPacked(Builder<T> builder, Builder.UnCompiledNode<T> nodeIn, long fixedArrayStart, int maxBytesPerArc) {
+ // expand the arcs in place, backwards
+ long srcPos = builder.bytes.getPosition();
+ long destPos = fixedArrayStart + nodeIn.numArcs * maxBytesPerArc;
+ assert destPos >= srcPos;
+ if (destPos > srcPos) {
+ builder.bytes.skipBytes((int) (destPos - srcPos));
+ for(int arcIdx = nodeIn.numArcs - 1; arcIdx >= 0; arcIdx--) {
+ destPos -= maxBytesPerArc;
+ srcPos -= builder.reusedBytesPerArc[arcIdx];
+ //System.out.println(" repack arcIdx=" + arcIdx + " srcPos=" + srcPos + " destPos=" + destPos);
+ if (srcPos != destPos) {
+ //System.out.println(" copy len=" + builder.reusedBytesPerArc[arcIdx]);
+ assert destPos > srcPos: "destPos=" + destPos + " srcPos=" + srcPos + " arcIdx=" + arcIdx + " maxBytesPerArc=" + maxBytesPerArc + " reusedBytesPerArc[arcIdx]=" + builder.reusedBytesPerArc[arcIdx] + " nodeIn.numArcs=" + nodeIn.numArcs;
+ builder.bytes.copyBytes(srcPos, destPos, builder.reusedBytesPerArc[arcIdx]);
+ }
+ }
+ }
+ }
+
+ private void writeArrayWithGaps(Builder<T> builder, Builder.UnCompiledNode<T> nodeIn, long fixedArrayStart, int maxBytesPerArc, int labelRange) {
+ // expand the arcs in place, backwards
+ long srcPos = builder.bytes.getPosition();
+ long destPos = fixedArrayStart + labelRange * maxBytesPerArc;
+ // if destPos == srcPos it means all the arcs were the same length, and the array of them is *already* direct
+ assert destPos >= srcPos;
+ if (destPos > srcPos) {
+ builder.bytes.skipBytes((int) (destPos - srcPos));
+ int arcIdx = nodeIn.numArcs - 1;
+ int firstLabel = nodeIn.arcs[0].label;
+ int nextLabel = nodeIn.arcs[arcIdx].label;
+ for (int directArcIdx = labelRange - 1; directArcIdx >= 0; directArcIdx--) {
+ destPos -= maxBytesPerArc;
+ if (directArcIdx == nextLabel - firstLabel) {
+ int arcLen = builder.reusedBytesPerArc[arcIdx];
+ srcPos -= arcLen;
+ //System.out.println(" direct pack idx=" + directArcIdx + " arcIdx=" + arcIdx + " srcPos=" + srcPos + " destPos=" + destPos + " label=" + nextLabel);
+ if (srcPos != destPos) {
+ //System.out.println(" copy len=" + builder.reusedBytesPerArc[arcIdx]);
+ assert destPos > srcPos: "destPos=" + destPos + " srcPos=" + srcPos + " arcIdx=" + arcIdx + " maxBytesPerArc=" + maxBytesPerArc + " reusedBytesPerArc[arcIdx]=" + builder.reusedBytesPerArc[arcIdx] + " nodeIn.numArcs=" + nodeIn.numArcs;
+ builder.bytes.copyBytes(srcPos, destPos, arcLen);
+ if (arcIdx == 0) {
+ break;
+ }
+ }
+ --arcIdx;
+ nextLabel = nodeIn.arcs[arcIdx].label;
+ } else {
+ assert directArcIdx > arcIdx;
+ // mark this as a missing arc
+ //System.out.println(" direct pack idx=" + directArcIdx + " no arc");
+ builder.bytes.writeByte(destPos, BIT_MISSING_ARC);
+ }
+ }
+ }
+ }
+
/** Fills virtual 'start' arc, ie, an empty incoming arc to
* the FST's start node */
public Arc<T> getFirstArc(Arc<T> arc) {
@@ -722,13 +787,18 @@ public final class FST<T> implements Accountable {
} else {
in.setPosition(follow.target);
final byte b = in.readByte();
- if (b == ARCS_AS_FIXED_ARRAY) {
+ if (b == ARCS_AS_ARRAY_PACKED || b == ARCS_AS_ARRAY_WITH_GAPS) {
// array: jump straight to end
arc.numArcs = in.readVInt();
arc.bytesPerArc = in.readVInt();
//System.out.println(" array numArcs=" + arc.numArcs + " bpa=" + arc.bytesPerArc);
arc.posArcsStart = in.getPosition();
- arc.arcIdx = arc.numArcs - 2;
+ if (b == ARCS_AS_ARRAY_WITH_GAPS) {
+ arc.arcIdx = Integer.MIN_VALUE;
+ arc.nextArc = arc.posArcsStart - (arc.numArcs - 1) * arc.bytesPerArc;
+ } else {
+ arc.arcIdx = arc.numArcs - 2;
+ }
} else {
arc.flags = b;
// non-array: linear scan
@@ -796,16 +866,19 @@ public final class FST<T> implements Accountable {
public Arc<T> readFirstRealTargetArc(long node, Arc<T> arc, final BytesReader in) throws IOException {
final long address = node;
in.setPosition(address);
- //System.out.println(" readFirstRealTargtArc address="
- //+ address);
//System.out.println(" flags=" + arc.flags);
- if (in.readByte() == ARCS_AS_FIXED_ARRAY) {
+ byte flags = in.readByte();
+ if (flags == ARCS_AS_ARRAY_PACKED || flags == ARCS_AS_ARRAY_WITH_GAPS) {
//System.out.println(" fixedArray");
// this is first arc in a fixed-array
arc.numArcs = in.readVInt();
arc.bytesPerArc = in.readVInt();
- arc.arcIdx = -1;
+ if (flags == ARCS_AS_ARRAY_PACKED) {
+ arc.arcIdx = -1;
+ } else {
+ arc.arcIdx = Integer.MIN_VALUE;
+ }
arc.nextArc = arc.posArcsStart = in.getPosition();
//System.out.println(" bytesPer=" + arc.bytesPerArc + " numArcs=" + arc.numArcs + " arcsStart=" + pos);
} else {
@@ -828,7 +901,8 @@ public final class FST<T> implements Accountable {
return false;
} else {
in.setPosition(follow.target);
- return in.readByte() == ARCS_AS_FIXED_ARRAY;
+ byte flags = in.readByte();
+ return flags == ARCS_AS_ARRAY_PACKED || flags == ARCS_AS_ARRAY_WITH_GAPS;
}
}
@@ -857,8 +931,8 @@ public final class FST<T> implements Accountable {
long pos = arc.nextArc;
in.setPosition(pos);
- final byte b = in.readByte();
- if (b == ARCS_AS_FIXED_ARRAY) {
+ final byte flags = in.readByte();
+ if (flags == ARCS_AS_ARRAY_PACKED || flags == ARCS_AS_ARRAY_WITH_GAPS) {
//System.out.println(" nextArc fixed array");
in.readVInt();
@@ -867,20 +941,32 @@ public final class FST<T> implements Accountable {
} else {
in.setPosition(pos);
}
+ // skip flags
+ in.readByte();
} else {
if (arc.bytesPerArc != 0) {
//System.out.println(" nextArc real array");
- // arcs are at fixed entries
- in.setPosition(arc.posArcsStart);
- in.skipBytes((1+arc.arcIdx)*arc.bytesPerArc);
+ // arcs are in an array
+ if (arc.arcIdx >= 0) {
+ in.setPosition(arc.posArcsStart);
+ // point at next arc, -1 to skip flags
+ in.skipBytes((1 + arc.arcIdx) * arc.bytesPerArc + 1);
+ } else {
+ in.setPosition(arc.nextArc);
+ byte flags = in.readByte();
+ // skip missing arcs
+ while (flag(flags, BIT_MISSING_ARC)) {
+ in.skipBytes(arc.bytesPerArc - 1);
+ flags = in.readByte();
+ }
+ }
} else {
// arcs are packed
//System.out.println(" nextArc real packed");
- in.setPosition(arc.nextArc);
+ // -1 to skip flags
+ in.setPosition(arc.nextArc - 1);
}
}
- // skip flags
- in.readByte();
return readLabel(in);
}
@@ -893,16 +979,28 @@ public final class FST<T> implements Accountable {
// this is a continuing arc in a fixed array
if (arc.bytesPerArc != 0) {
- // arcs are at fixed entries
- arc.arcIdx++;
- assert arc.arcIdx < arc.numArcs;
- in.setPosition(arc.posArcsStart);
- in.skipBytes(arc.arcIdx*arc.bytesPerArc);
+ // arcs are in an array
+ if (arc.arcIdx > Integer.MIN_VALUE) {
+ arc.arcIdx++;
+ assert arc.arcIdx < arc.numArcs;
+ in.setPosition(arc.posArcsStart - arc.arcIdx * arc.bytesPerArc);
+ arc.flags = in.readByte();
+ } else {
+ assert arc.nextArc <= arc.posArcsStart && arc.nextArc > arc.posArcsStart - arc.numArcs * arc.bytesPerArc;
+ in.setPosition(arc.nextArc);
+ arc.flags = in.readByte();
+ while (flag(arc.flags, BIT_MISSING_ARC)) {
+ // skip empty arcs
+ arc.nextArc -= arc.bytesPerArc;
+ in.skipBytes(arc.bytesPerArc - 1);
+ arc.flags = in.readByte();
+ }
+ }
} else {
// arcs are packed
in.setPosition(arc.nextArc);
+ arc.flags = in.readByte();
}
- arc.flags = in.readByte();
arc.label = readLabel(in);
if (arc.flag(BIT_ARC_HAS_OUTPUT)) {
@@ -923,7 +1021,11 @@ public final class FST<T> implements Accountable {
} else {
arc.target = NON_FINAL_END_NODE;
}
- arc.nextArc = in.getPosition();
+ if (arc.bytesPerArc == 0) {
+ arc.nextArc = in.getPosition();
+ } else {
+ arc.nextArc -= arc.bytesPerArc;
+ }
} else if (arc.flag(BIT_TARGET_NEXT)) {
arc.nextArc = in.getPosition();
// TODO: would be nice to make this lazy -- maybe
@@ -940,7 +1042,14 @@ public final class FST<T> implements Accountable {
arc.target = in.getPosition();
} else {
arc.target = readUnpackedNodeTarget(in);
- arc.nextArc = in.getPosition();
+ if (arc.bytesPerArc > 0 && arc.arcIdx == Integer.MIN_VALUE) {
+ // nextArc was pointing to *this* arc when we entered; advance to the next
+ // if it is a missing arc, we will skip it later
+ arc.nextArc -= arc.bytesPerArc;
+ } else {
+ // in list and fixed table encodings, the next arc always follows this one
+ arc.nextArc = in.getPosition();
+ }
}
return arc;
}
@@ -963,7 +1072,10 @@ public final class FST<T> implements Accountable {
assert cachedArc.bytesPerArc == result.bytesPerArc;
assert cachedArc.flags == result.flags;
assert cachedArc.label == result.label;
- assert cachedArc.nextArc == result.nextArc;
+ if (cachedArc.bytesPerArc == 0 || cachedArc.arcIdx == Integer.MIN_VALUE) {
+ // in the sparse array case, this value is not valid, so don't assert it
+ assert cachedArc.nextArc == result.nextArc;
+ }
assert cachedArc.nextFinalOutput.equals(result.nextFinalOutput);
assert cachedArc.numArcs == result.numArcs;
assert cachedArc.output.equals(result.output);
@@ -1028,18 +1140,47 @@ public final class FST<T> implements Accountable {
// System.out.println("fta label=" + (char) labelToMatch);
- if (in.readByte() == ARCS_AS_FIXED_ARRAY) {
- // Arcs are full array; do binary search:
+ byte flags = in.readByte();
+ if (flags == ARCS_AS_ARRAY_WITH_GAPS) {
+ arc.numArcs = in.readVInt();
+ arc.bytesPerArc = in.readVInt();
+ arc.posArcsStart = in.getPosition();
+
+ // Array is direct; address by label
+ in.skipBytes(1);
+ int firstLabel = readLabel(in);
+ int arcPos = labelToMatch - firstLabel;
+ if (arcPos == 0) {
+ arc.nextArc = arc.posArcsStart;
+ } else if (arcPos > 0) {
+ if (arcPos >= arc.numArcs) {
+ return null;
+ }
+ in.setPosition(arc.posArcsStart - arc.bytesPerArc * arcPos);
+ flags = in.readByte();
+ if (flag(flags, BIT_MISSING_ARC)) {
+ return null;
+ }
+ // point to flags that we just read
+ arc.nextArc = in.getPosition() + 1;
+ } else {
+ return null;
+ }
+ arc.arcIdx = Integer.MIN_VALUE;
+ return readNextRealArc(arc, in);
+ } else if (flags == ARCS_AS_ARRAY_PACKED) {
arc.numArcs = in.readVInt();
arc.bytesPerArc = in.readVInt();
arc.posArcsStart = in.getPosition();
+
+ // Array is sparse; do binary search:
int low = 0;
- int high = arc.numArcs-1;
+ int high = arc.numArcs - 1;
while (low <= high) {
//System.out.println(" cycle");
int mid = (low + high) >>> 1;
- in.setPosition(arc.posArcsStart);
- in.skipBytes(arc.bytesPerArc*mid + 1);
+ // +1 to skip over flags
+ in.setPosition(arc.posArcsStart - (arc.bytesPerArc * mid + 1));
int midLabel = readLabel(in);
final int cmp = midLabel - labelToMatch;
if (cmp < 0) {
@@ -1047,12 +1188,11 @@ public final class FST<T> implements Accountable {
} else if (cmp > 0) {
high = mid - 1;
} else {
- arc.arcIdx = mid-1;
+ arc.arcIdx = mid - 1;
//System.out.println(" found!");
return readNextRealArc(arc, in);
}
}
-
return null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/FSTEnum.java b/lucene/core/src/java/org/apache/lucene/util/fst/FSTEnum.java
index 676d6ed..c7819a1 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/FSTEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/FSTEnum.java
@@ -132,129 +132,189 @@ abstract class FSTEnum<T> {
//System.out.println(" after rewind upto=" + upto);
FST.Arc<T> arc = getArc(upto);
- int targetLabel = getTargetLabel();
//System.out.println(" init targetLabel=" + targetLabel);
// Now scan forward, matching the new suffix of the target
- while(true) {
-
+ while(arc != null) {
+ int targetLabel = getTargetLabel();
//System.out.println(" cycle upto=" + upto + " arc.label=" + arc.label + " (" + (char) arc.label + ") vs targetLabel=" + targetLabel);
-
if (arc.bytesPerArc != 0 && arc.label != -1) {
-
- // Arcs are fixed array -- use binary search to find
- // the target.
-
+ // Arcs are in an array
final FST.BytesReader in = fst.getBytesReader();
- int low = arc.arcIdx;
- int high = arc.numArcs-1;
- int mid = 0;
- //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel);
- boolean found = false;
- while (low <= high) {
- mid = (low + high) >>> 1;
- in.setPosition(arc.posArcsStart);
- in.skipBytes(arc.bytesPerArc*mid+1);
- final int midLabel = fst.readLabel(in);
- final int cmp = midLabel - targetLabel;
- //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp);
- if (cmp < 0)
- low = mid + 1;
- else if (cmp > 0)
- high = mid - 1;
- else {
- found = true;
- break;
- }
+ if (arc.arcIdx == Integer.MIN_VALUE) {
+ arc = doSeekCeilArrayWithGaps(arc, targetLabel, in);
+ } else {
+ arc = doSeekCeilArrayPacked(arc, targetLabel, in);
}
+ } else {
+ arc = doSeekCeilList(arc, targetLabel);
+ }
+ }
+ }
- // NOTE: this code is dup'd w/ the code below (in
- // the outer else clause):
- if (found) {
- // Match
- arc.arcIdx = mid-1;
- fst.readNextRealArc(arc, in);
- assert arc.arcIdx == mid;
- assert arc.label == targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel + " mid=" + mid;
- output[upto] = fst.outputs.add(output[upto-1], arc.output);
- if (targetLabel == FST.END_LABEL) {
- return;
- }
- setCurrentLabel(arc.label);
- incr();
- arc = fst.readFirstTargetArc(arc, getArc(upto), fstReader);
- targetLabel = getTargetLabel();
- continue;
- } else if (low == arc.numArcs) {
- // Dead end
- arc.arcIdx = arc.numArcs-2;
- fst.readNextRealArc(arc, in);
- assert arc.isLast();
- // Dead end (target is after the last arc);
- // rollback to last fork then push
- upto--;
- while(true) {
- if (upto == 0) {
- return;
- }
- final FST.Arc<T> prevArc = getArc(upto);
- //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast());
- if (!prevArc.isLast()) {
- fst.readNextArc(prevArc, fstReader);
- pushFirst();
- return;
- }
- upto--;
- }
- } else {
- arc.arcIdx = (low > high ? low : high)-1;
- fst.readNextRealArc(arc, in);
- assert arc.label > targetLabel;
+ private FST.Arc<T> doSeekCeilArrayWithGaps(final FST.Arc<T> arc, final int targetLabel, final FST.BytesReader in) throws IOException {
+ // The array is addressed directly by label and may contain holes.
+
+ in.setPosition(arc.posArcsStart);
+ in.skipBytes(1);
+ int firstLabel = fst.readLabel(in);
+ int arcOffset = targetLabel - firstLabel;
+ if (arcOffset >= arc.numArcs) {
+ // target is beyond the last arc
+ arc.nextArc = arc.posArcsStart - (arc.numArcs - 1) * arc.bytesPerArc;
+ fst.readNextRealArc(arc, in);
+ assert arc.isLast();
+ // Dead end (target is after the last arc);
+ // rollback to last fork then push
+ upto--;
+ while(true) {
+ if (upto == 0) {
+ return null;
+ }
+ final FST.Arc<T> prevArc = getArc(upto);
+ //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast());
+ if (!prevArc.isLast()) {
+ fst.readNextArc(prevArc, fstReader);
pushFirst();
- return;
+ return null;
}
+ upto--;
+ }
+ } else {
+ // TODO: if firstLabel == targetLabel
+ if (arcOffset >= 0) {
+ arc.nextArc = arc.posArcsStart - (arc.bytesPerArc * arcOffset);
} else {
- // Arcs are not array'd -- must do linear scan:
- if (arc.label == targetLabel) {
- // recurse
- output[upto] = fst.outputs.add(output[upto-1], arc.output);
- if (targetLabel == FST.END_LABEL) {
- return;
- }
- setCurrentLabel(arc.label);
- incr();
- arc = fst.readFirstTargetArc(arc, getArc(upto), fstReader);
- targetLabel = getTargetLabel();
- } else if (arc.label > targetLabel) {
+ arc.nextArc = arc.posArcsStart;
+ }
+ fst.readNextRealArc(arc, in);
+ if (arc.label == targetLabel) {
+ // found -- copy pasta from below
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ }
+ // not found, return the next highest
+ assert arc.label > targetLabel;
+ pushFirst();
+ return null;
+ }
+ }
+
+ private FST.Arc<T> doSeekCeilArrayPacked(final FST.Arc<T> arc, final int targetLabel, final FST.BytesReader in) throws IOException {
+ // The array is packed -- use binary search to find the target.
+
+ int low = arc.arcIdx;
+ int high = arc.numArcs-1;
+ int mid = 0;
+ //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel);
+ boolean found = false;
+ while (low <= high) {
+ mid = (low + high) >>> 1;
+ in.setPosition(arc.posArcsStart);
+ in.skipBytes(arc.bytesPerArc * mid + 1);
+ final int midLabel = fst.readLabel(in);
+ final int cmp = midLabel - targetLabel;
+ //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp);
+ if (cmp < 0)
+ low = mid + 1;
+ else if (cmp > 0)
+ high = mid - 1;
+ else {
+ found = true;
+ break;
+ }
+ }
+
+ // NOTE: this code is dup'd w/ the code below (in
+ // the outer else clause):
+ if (found) {
+ // Match
+ arc.arcIdx = mid-1;
+ fst.readNextRealArc(arc, in);
+ assert arc.arcIdx == mid;
+ assert arc.label == targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel + " mid=" + mid;
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ } else if (low == arc.numArcs) {
+ // Dead end
+ arc.arcIdx = arc.numArcs-2;
+ fst.readNextRealArc(arc, in);
+ assert arc.isLast();
+ // Dead end (target is after the last arc);
+ // rollback to last fork then push
+ upto--;
+ while(true) {
+ if (upto == 0) {
+ return null;
+ }
+ final FST.Arc<T> prevArc = getArc(upto);
+ //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast());
+ if (!prevArc.isLast()) {
+ fst.readNextArc(prevArc, fstReader);
pushFirst();
- return;
- } else if (arc.isLast()) {
- // Dead end (target is after the last arc);
- // rollback to last fork then push
- upto--;
- while(true) {
- if (upto == 0) {
- return;
- }
- final FST.Arc<T> prevArc = getArc(upto);
- //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast());
- if (!prevArc.isLast()) {
- fst.readNextArc(prevArc, fstReader);
- pushFirst();
- return;
- }
- upto--;
- }
- } else {
- // keep scanning
- //System.out.println(" next scan");
- fst.readNextArc(arc, fstReader);
+ return null;
}
+ upto--;
}
+ } else {
+ arc.arcIdx = (low > high ? low : high)-1;
+ fst.readNextRealArc(arc, in);
+ assert arc.label > targetLabel;
+ pushFirst();
+ return null;
}
}
- // TODO: should we return a status here (SEEK_FOUND / SEEK_NOT_FOUND /
+ private FST.Arc<T> doSeekCeilList(final FST.Arc<T> arc, final int targetLabel) throws IOException {
+ // Arcs are not array'd -- must do linear scan:
+ if (arc.label == targetLabel) {
+ // recurse
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ } else if (arc.label > targetLabel) {
+ pushFirst();
+ return null;
+ } else if (arc.isLast()) {
+ // Dead end (target is after the last arc);
+ // rollback to last fork then push
+ upto--;
+ while(true) {
+ if (upto == 0) {
+ return null;
+ }
+ final FST.Arc<T> prevArc = getArc(upto);
+ //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast());
+ if (!prevArc.isLast()) {
+ fst.readNextArc(prevArc, fstReader);
+ pushFirst();
+ return null;
+ }
+ upto--;
+ }
+ } else {
+ // keep scanning
+ //System.out.println(" next scan");
+ fst.readNextArc(arc, fstReader);
+ }
+ return arc;
+ }
+
+ // Todo: should we return a status here (SEEK_FOUND / SEEK_NOT_FOUND /
// SEEK_END)? saves the eq check above?
/** Seeks to largest term that's <= target. */
protected void doSeekFloor() throws IOException {
@@ -272,147 +332,223 @@ abstract class FSTEnum<T> {
//System.out.println("FE: after rewind upto=" + upto);
FST.Arc<T> arc = getArc(upto);
- int targetLabel = getTargetLabel();
//System.out.println("FE: init targetLabel=" + targetLabel);
// Now scan forward, matching the new suffix of the target
- while(true) {
+ while (arc != null) {
//System.out.println(" cycle upto=" + upto + " arc.label=" + arc.label + " (" + (char) arc.label + ") targetLabel=" + targetLabel + " isLast?=" + arc.isLast() + " bba=" + arc.bytesPerArc);
+ int targetLabel = getTargetLabel();
if (arc.bytesPerArc != 0 && arc.label != FST.END_LABEL) {
- // Arcs are fixed array -- use binary search to find
- // the target.
-
+ // Arcs are in an array
final FST.BytesReader in = fst.getBytesReader();
- int low = arc.arcIdx;
- int high = arc.numArcs-1;
- int mid = 0;
- //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel);
- boolean found = false;
- while (low <= high) {
- mid = (low + high) >>> 1;
- in.setPosition(arc.posArcsStart);
- in.skipBytes(arc.bytesPerArc*mid+1);
- final int midLabel = fst.readLabel(in);
- final int cmp = midLabel - targetLabel;
- //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp);
- if (cmp < 0) {
- low = mid + 1;
- } else if (cmp > 0) {
- high = mid - 1;
- } else {
- found = true;
- break;
- }
+ if (arc.arcIdx == Integer.MIN_VALUE) {
+ arc = doSeekFloorArrayWithGaps(arc, targetLabel, in);
+ } else {
+ arc = doSeekFloorArrayPacked(arc, targetLabel, in);
}
+ } else {
+ arc = doSeekFloorList(arc, targetLabel);
+ }
+ }
+ }
- // NOTE: this code is dup'd w/ the code below (in
- // the outer else clause):
- if (found) {
- // Match -- recurse
- //System.out.println(" match! arcIdx=" + mid);
- arc.arcIdx = mid-1;
- fst.readNextRealArc(arc, in);
- assert arc.arcIdx == mid;
- assert arc.label == targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel + " mid=" + mid;
- output[upto] = fst.outputs.add(output[upto-1], arc.output);
- if (targetLabel == FST.END_LABEL) {
- return;
- }
- setCurrentLabel(arc.label);
- incr();
- arc = fst.readFirstTargetArc(arc, getArc(upto), fstReader);
- targetLabel = getTargetLabel();
- continue;
- } else if (high == -1) {
- //System.out.println(" before first");
- // Very first arc is after our target
- // TODO: if each arc could somehow read the arc just
- // before, we can save this re-scan. The ceil case
- // doesn't need this because it reads the next arc
- // instead:
- while(true) {
- // First, walk backwards until we find a first arc
- // that's before our target label:
- fst.readFirstTargetArc(getArc(upto-1), arc, fstReader);
- if (arc.label < targetLabel) {
- // Then, scan forwards to the arc just before
- // the targetLabel:
- while(!arc.isLast() && fst.readNextArcLabel(arc, in) < targetLabel) {
- fst.readNextArc(arc, fstReader);
- }
- pushLast();
- return;
- }
- upto--;
- if (upto == 0) {
- return;
- }
- targetLabel = getTargetLabel();
- arc = getArc(upto);
+ private FST.Arc<T> doSeekFloorArrayWithGaps(FST.Arc<T> arc, int targetLabel, final FST.BytesReader in) throws IOException {
+ // The array is addressed directly by label and may contain holes.
+ in.setPosition(arc.posArcsStart);
+ in.skipBytes(1);
+ int firstLabel = fst.readLabel(in);
+ int targetOffset = targetLabel - firstLabel;
+ if (targetOffset < 0) {
+ //System.out.println(" before first"); Very first arc is after our target TODO: if each
+ // arc could somehow read the arc just before, we can save this re-scan. The ceil case
+ // doesn't need this because it reads the next arc instead:
+ while(true) {
+ // First, walk backwards until we find a first arc
+ // that's before our target label:
+ fst.readFirstTargetArc(getArc(upto-1), arc, fstReader);
+ if (arc.label < targetLabel) {
+ // Then, scan forwards to the arc just before
+ // the targetLabel:
+ while(!arc.isLast() && fst.readNextArcLabel(arc, in) < targetLabel) {
+ fst.readNextArc(arc, fstReader);
}
- } else {
- // There is a floor arc:
- arc.arcIdx = (low > high ? high : low)-1;
- //System.out.println(" hasFloor arcIdx=" + (arc.arcIdx+1));
- fst.readNextRealArc(arc, in);
+ pushLast();
+ return null;
+ }
+ upto--;
+ if (upto == 0) {
+ return null;
+ }
+ targetLabel = getTargetLabel();
+ arc = getArc(upto);
+ }
+ } else {
+ if (targetOffset >= arc.numArcs) {
+ arc.nextArc = arc.posArcsStart - arc.bytesPerArc * (arc.numArcs - 1);
+ fst.readNextRealArc(arc, in);
+ assert arc.isLast();
+ assert arc.label < targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel;
+ pushLast();
+ return null;
+ }
+ arc.nextArc = arc.posArcsStart - arc.bytesPerArc * targetOffset;
+ fst.readNextRealArc(arc, in);
+ if (arc.label == targetLabel) {
+ // found -- copy pasta from below
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ }
+ // Scan backwards to find a floor arc that is not missing
+ for (long arcOffset = arc.posArcsStart - targetOffset * arc.bytesPerArc; arcOffset <= arc.posArcsStart; arcOffset += arc.bytesPerArc) {
+ // TODO: we can do better here by skipping missing arcs
+ arc.nextArc = arcOffset;
+ //System.out.println(" hasFloor arcIdx=" + (arc.arcIdx+1));
+ fst.readNextRealArc(arc, in);
+ if (arc.label < targetLabel) {
assert arc.isLast() || fst.readNextArcLabel(arc, in) > targetLabel;
- assert arc.label < targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel;
pushLast();
- return;
- }
+ return null;
+ }
+ }
+ assert false: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel;
+ return arc; // unreachable
+ }
+ }
+
+ private FST.Arc<T> doSeekFloorArrayPacked(FST.Arc<T> arc, int targetLabel, final FST.BytesReader in) throws IOException {
+ // Arcs are fixed array -- use binary search to find the target.
+
+ int low = arc.arcIdx;
+ int high = arc.numArcs-1;
+ int mid = 0;
+ //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel);
+ boolean found = false;
+ while (low <= high) {
+ mid = (low + high) >>> 1;
+ in.setPosition(arc.posArcsStart);
+ in.skipBytes(arc.bytesPerArc*mid+1);
+ final int midLabel = fst.readLabel(in);
+ final int cmp = midLabel - targetLabel;
+ //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp);
+ if (cmp < 0) {
+ low = mid + 1;
+ } else if (cmp > 0) {
+ high = mid - 1;
} else {
+ found = true;
+ break;
+ }
+ }
- if (arc.label == targetLabel) {
- // Match -- recurse
- output[upto] = fst.outputs.add(output[upto-1], arc.output);
- if (targetLabel == FST.END_LABEL) {
- return;
- }
- setCurrentLabel(arc.label);
- incr();
- arc = fst.readFirstTargetArc(arc, getArc(upto), fstReader);
- targetLabel = getTargetLabel();
- } else if (arc.label > targetLabel) {
- // TODO: if each arc could somehow read the arc just
- // before, we can save this re-scan. The ceil case
- // doesn't need this because it reads the next arc
- // instead:
- while(true) {
- // First, walk backwards until we find a first arc
- // that's before our target label:
- fst.readFirstTargetArc(getArc(upto-1), arc, fstReader);
- if (arc.label < targetLabel) {
- // Then, scan forwards to the arc just before
- // the targetLabel:
- while(!arc.isLast() && fst.readNextArcLabel(arc, fstReader) < targetLabel) {
- fst.readNextArc(arc, fstReader);
- }
- pushLast();
- return;
- }
- upto--;
- if (upto == 0) {
- return;
- }
- targetLabel = getTargetLabel();
- arc = getArc(upto);
+ // NOTE: this code is dup'd w/ the code below (in
+ // the outer else clause):
+ if (found) {
+ // Match -- recurse
+ //System.out.println(" match! arcIdx=" + mid);
+ arc.arcIdx = mid-1;
+ fst.readNextRealArc(arc, in);
+ assert arc.arcIdx == mid;
+ assert arc.label == targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel + " mid=" + mid;
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ } else if (high == -1) {
+ //System.out.println(" before first");
+ // Very first arc is after our target
+ // TODO: if each arc could somehow read the arc just
+ // before, we can save this re-scan. The ceil case
+ // doesn't need this because it reads the next arc
+ // instead:
+ while(true) {
+ // First, walk backwards until we find a first arc
+ // that's before our target label:
+ fst.readFirstTargetArc(getArc(upto-1), arc, fstReader);
+ if (arc.label < targetLabel) {
+ // Then, scan forwards to the arc just before
+ // the targetLabel:
+ while(!arc.isLast() && fst.readNextArcLabel(arc, in) < targetLabel) {
+ fst.readNextArc(arc, fstReader);
}
- } else if (!arc.isLast()) {
- //System.out.println(" check next label=" + fst.readNextArcLabel(arc) + " (" + (char) fst.readNextArcLabel(arc) + ")");
- if (fst.readNextArcLabel(arc, fstReader) > targetLabel) {
- pushLast();
- return;
- } else {
- // keep scanning
+ pushLast();
+ return null;
+ }
+ upto--;
+ if (upto == 0) {
+ return null;
+ }
+ targetLabel = getTargetLabel();
+ arc = getArc(upto);
+ }
+ } else {
+ // There is a floor arc:
+ arc.arcIdx = (low > high ? high : low)-1;
+ //System.out.println(" hasFloor arcIdx=" + (arc.arcIdx+1));
+ fst.readNextRealArc(arc, in);
+ assert arc.isLast() || fst.readNextArcLabel(arc, in) > targetLabel;
+ assert arc.label < targetLabel: "arc.label=" + arc.label + " vs targetLabel=" + targetLabel;
+ pushLast();
+ return null;
+ }
+ }
+
+ private FST.Arc<T> doSeekFloorList(FST.Arc<T> arc, int targetLabel) throws IOException {
+ if (arc.label == targetLabel) {
+ // Match -- recurse
+ output[upto] = fst.outputs.add(output[upto-1], arc.output);
+ if (targetLabel == FST.END_LABEL) {
+ return null;
+ }
+ setCurrentLabel(arc.label);
+ incr();
+ return fst.readFirstTargetArc(arc, getArc(upto), fstReader);
+ } else if (arc.label > targetLabel) {
+ // TODO: if each arc could somehow read the arc just
+ // before, we can save this re-scan. The ceil case
+ // doesn't need this because it reads the next arc
+ // instead:
+ while(true) {
+ // First, walk backwards until we find a first arc
+ // that's before our target label:
+ fst.readFirstTargetArc(getArc(upto-1), arc, fstReader);
+ if (arc.label < targetLabel) {
+ // Then, scan forwards to the arc just before
+ // the targetLabel:
+ while(!arc.isLast() && fst.readNextArcLabel(arc, fstReader) < targetLabel) {
fst.readNextArc(arc, fstReader);
}
- } else {
pushLast();
- return;
+ return null;
+ }
+ upto--;
+ if (upto == 0) {
+ return null;
}
+ targetLabel = getTargetLabel();
+ arc = getArc(upto);
}
+ } else if (!arc.isLast()) {
+ //System.out.println(" check next label=" + fst.readNextArcLabel(arc) + " (" + (char) fst.readNextArcLabel(arc) + ")");
+ if (fst.readNextArcLabel(arc, fstReader) > targetLabel) {
+ pushLast();
+ return null;
+ } else {
+ // keep scanning
+ return fst.readNextArc(arc, fstReader);
+ }
+ } else {
+ pushLast();
+ return null;
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java b/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java
index 6704cf6..c7023c1 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java
@@ -74,7 +74,7 @@ final class NodeHash<T> {
//System.out.println("hash unfrozen");
long h = 0;
// TODO: maybe if number of arcs is high we can safely subsample?
- for(int arcIdx=0;arcIdx<node.numArcs;arcIdx++) {
+ for (int arcIdx=0; arcIdx < node.numArcs; arcIdx++) {
final Builder.Arc<T> arc = node.arcs[arcIdx];
//System.out.println(" label=" + arc.label + " target=" + ((Builder.CompiledNode) arc.target).node + " h=" + h + " output=" + fst.outputs.outputToString(arc.output) + " isFinal?=" + arc.isFinal);
h = PRIME * h + arc.label;
@@ -97,7 +97,7 @@ final class NodeHash<T> {
long h = 0;
fst.readFirstRealTargetArc(node, scratchArc, in);
while(true) {
- //System.out.println(" label=" + scratchArc.label + " target=" + scratchArc.target + " h=" + h + " output=" + fst.outputs.outputToString(scratchArc.output) + " next?=" + scratchArc.flag(4) + " final?=" + scratchArc.isFinal() + " pos=" + in.getPosition());
+ // System.out.println(" label=" + scratchArc.label + " target=" + scratchArc.target + " h=" + h + " output=" + fst.outputs.outputToString(scratchArc.output) + " next?=" + scratchArc.flag(4) + " final?=" + scratchArc.isFinal() + " pos=" + in.getPosition());
h = PRIME * h + scratchArc.label;
h = PRIME * h + (int) (scratchArc.target^(scratchArc.target>>32));
h = PRIME * h + scratchArc.output.hashCode();
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java b/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
index 8ab3aed..04cd182 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
@@ -149,7 +149,7 @@ public final class Util {
fst.readFirstRealTargetArc(arc.target, arc, in);
- if (arc.bytesPerArc != 0) {
+ if (arc.bytesPerArc != 0 && arc.arcIdx > Integer.MIN_VALUE) {
int low = 0;
int high = arc.numArcs-1;
@@ -169,7 +169,7 @@ public final class Util {
} else {
minArcOutput = output;
}
- //System.out.println(" cycle mid=" + mid + " label=" + (char) label + " output=" + minArcOutput);
+ //System.out.println(" cycle mid=" + mid + " output=" + minArcOutput);
if (minArcOutput == targetOutput) {
exact = true;
break;
@@ -987,7 +987,7 @@ public final class Util {
// DEAD END!
return null;
}
-
+
arc.arcIdx = (low > high ? high : low);
return fst.readNextRealArc(arc, in);
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java
index 828dcbe..48898bc 100644
--- a/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java
+++ b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java
@@ -55,7 +55,7 @@ public class Test2BFST extends LuceneTestCase {
Outputs<Object> outputs = NoOutputs.getSingleton();
Object NO_OUTPUT = outputs.getNoOutput();
final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
- true, 15);
+ true, 15, true);
int count = 0;
Random r = new Random(seed);
@@ -137,7 +137,7 @@ public class Test2BFST extends LuceneTestCase {
System.out.println("\nTEST: 3 GB size; outputs=bytes");
Outputs<BytesRef> outputs = ByteSequenceOutputs.getSingleton();
final Builder<BytesRef> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
- true, 15);
+ true, 15, true);
byte[] outputBytes = new byte[20];
BytesRef output = new BytesRef(outputBytes);
@@ -149,11 +149,14 @@ public class Test2BFST extends LuceneTestCase {
//System.out.println("add: " + input + " -> " + output);
b.add(input, BytesRef.deepCopyOf(output));
count++;
- if (count % 1000000 == 0) {
- System.out.println(count + "...: " + b.fstRamBytesUsed() + " bytes");
- }
- if (b.fstRamBytesUsed() > LIMIT) {
- break;
+ if (count % 10000 == 0) {
+ long size = b.fstRamBytesUsed();
+ if (count % 1000000 == 0) {
+ System.out.println(count + "...: " + size + " bytes");
+ }
+ if (size > LIMIT) {
+ break;
+ }
}
nextInput(r, ints);
}
@@ -214,7 +217,7 @@ public class Test2BFST extends LuceneTestCase {
System.out.println("\nTEST: 3 GB size; outputs=long");
Outputs<Long> outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
- true, 15);
+ true, 15, true);
long output = 1;
@@ -226,11 +229,14 @@ public class Test2BFST extends LuceneTestCase {
b.add(input, output);
output += 1+r.nextInt(10);
count++;
- if (count % 1000000 == 0) {
- System.out.println(count + "...: " + b.fstRamBytesUsed() + " bytes");
- }
- if (b.fstRamBytesUsed() > LIMIT) {
- break;
+ if (count % 10000 == 0) {
+ long size = b.fstRamBytesUsed();
+ if (count % 1000000 == 0) {
+ System.out.println(count + "...: " + size + " bytes");
+ }
+ if (size > LIMIT) {
+ break;
+ }
}
nextInput(r, ints);
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
index d882fae..f728854 100644
--- a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
@@ -327,7 +327,7 @@ public class TestFSTs extends LuceneTestCase {
writer.close();
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
- Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15);
+ Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15, true);
boolean storeOrd = random().nextBoolean();
if (VERBOSE) {
@@ -468,7 +468,7 @@ public class TestFSTs extends LuceneTestCase {
this.inputMode = inputMode;
this.outputs = outputs;
- builder = new Builder<>(inputMode == 0 ? FST.INPUT_TYPE.BYTE1 : FST.INPUT_TYPE.BYTE4, 0, prune, prune == 0, true, Integer.MAX_VALUE, outputs, !noArcArrays, 15);
+ builder = new Builder<>(inputMode == 0 ? FST.INPUT_TYPE.BYTE1 : FST.INPUT_TYPE.BYTE4, 0, prune, prune == 0, true, Integer.MAX_VALUE, outputs, !noArcArrays, 15, true);
}
protected abstract T getOutput(IntsRef input, int ord) throws IOException;
@@ -1110,7 +1110,7 @@ public class TestFSTs extends LuceneTestCase {
public void testFinalOutputOnEndState() throws Exception {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
- final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE4, 2, 0, true, true, Integer.MAX_VALUE, outputs, true, 15);
+ final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE4, 2, 0, true, true, Integer.MAX_VALUE, outputs, true, 15, true);
builder.add(Util.toUTF32("stat", new IntsRefBuilder()), 17L);
builder.add(Util.toUTF32("station", new IntsRefBuilder()), 10L);
final FST<Long> fst = builder.finish();
@@ -1124,7 +1124,7 @@ public class TestFSTs extends LuceneTestCase {
public void testInternalFinalState() throws Exception {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
- final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15);
+ final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15, true);
builder.add(Util.toIntsRef(new BytesRef("stat"), new IntsRefBuilder()), outputs.getNoOutput());
builder.add(Util.toIntsRef(new BytesRef("station"), new IntsRefBuilder()), outputs.getNoOutput());
final FST<Long> fst = builder.finish();
diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestFstDirect.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestFstDirect.java
new file mode 100644
index 0000000..0d353d1
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestFstDirect.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.util.fst;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+import java.util.Set;
+
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IntsRefBuilder;
+import org.apache.lucene.util.LuceneTestCase;
+
+import org.junit.Before;
+import org.junit.Ignore;
+
+public class TestFstDirect extends LuceneTestCase {
+
+ private static final int COUNT = 10_000_000;
+ private List<String> words;
+ private Set<String> dict;
+ private Random random;
+
+ @Before
+ public void before() {
+ words = new ArrayList<>();
+ random = new Random(random().nextLong());
+ }
+
+ public void testDenseWithGap() throws Exception {
+ //words.addAll(Arrays.asList("apple", "berry", "cherry", "damson", "fig", "grape"));
+ words.addAll(Arrays.asList("ah", "bi", "cj", "dk", "fl", "gm"));
+ final BytesRefFSTEnum<Object> fstEnum = new BytesRefFSTEnum<>(buildFST(words, true));
+ for (String word : words) {
+ assertNotNull(word + " not found", fstEnum.seekExact(new BytesRef(word)));
+ }
+ }
+
+ @Ignore("for performance testing")
+ public void testLookupIDs() throws Exception {
+ for (int i = 0; i < 10000000; i++) {
+ words.add(String.format(Locale.ROOT, "%09d", i));
+ }
+ FST<Object> baselineFST = buildFST(words, false);
+ FST<Object> optoFST = buildFST(words,true);
+ for (int i = 0; i < 10; i++) {
+ long seed = random().nextLong();
+ random.setSeed(seed);
+ long timeOpto = timeLookups(optoFST);
+ random.setSeed(seed);
+ long timeBase = timeLookups(baselineFST);
+ printf("Sought %d present terms in %d ms (baseline) vs %d ms (opto), a %d%% difference", COUNT, nsToMs(timeBase), nsToMs(timeOpto),
+ -100 * (timeBase - timeOpto) / timeBase);
+ }
+ }
+
+ @Ignore("for performance testing")
+ public void testRandomTerms() throws Exception {
+ for (int i = 0; i < 100000; i++) {
+ words.add(randomString());
+ }
+ Collections.sort(words);
+ FST<Object> baselineFST = buildFST(words, false);
+ FST<Object> optoFST = buildFST(words,true);
+ for (int i = 0; i < 10; i++) {
+ long seed = random().nextLong();
+ random.setSeed(seed);
+ long timeOpto = timeLookups(optoFST);
+ random.setSeed(seed);
+ long timeBase = timeLookups(baselineFST);
+ printf("Sought %d present terms in %d ms (baseline) vs %d ms (opto), a %d%% difference", COUNT, nsToMs(timeBase), nsToMs(timeOpto),
+ -100 * (timeBase - timeOpto) / timeBase);
+ }
+ }
+
+ @Ignore("requires english dictionary")
+ public void testLookupEnglishTerms() throws Exception {
+ FST<Object> baselineFST = buildEnglishFST(false);
+ FST<Object> optoFST = buildFST(words,true);
+ for (int i = 0; i < 10; i++) {
+ long seed = random().nextLong();
+ random.setSeed(seed);
+ long timeOpto = timeLookups(optoFST);
+ random.setSeed(seed);
+ long timeBase = timeLookups(baselineFST);
+ printf("Sought %d present terms in %d ms (baseline) vs %d ms (opto), a %d%% difference", COUNT, nsToMs(timeBase), nsToMs(timeOpto),
+ -100 * (timeBase - timeOpto) / timeBase);
+ }
+ }
+
+ private long timeLookups(FST<Object> fst) throws Exception {
+ final BytesRefFSTEnum<Object> fstEnumOpto = new BytesRefFSTEnum<>(fst);
+ long start = System.nanoTime();
+ for (int i = 0; i < COUNT; i++) {
+ assertNotNull(fstEnumOpto.seekExact(new BytesRef(words.get(random.nextInt(words.size())))));
+ }
+ return System.nanoTime() - start;
+ }
+
+ @Ignore("requires english dictionary")
+ public void testLookupRandomStrings() throws Exception {
+ dict = new HashSet<>(words);
+ List<String> tokens = new ArrayList<>();
+ for (int i = 0; i < 1_000_000; i++) {
+ String s;
+ do {
+ s = randomString();
+ } while (dict.contains(s));
+ tokens.add(s);
+ }
+ final FST<Object> fstBase = buildEnglishFST(false);
+ final FST<Object> fstOpto = buildFST(words, true);
+ long seed = random().nextLong();
+ for (int i = 0; i < 10; i++) {
+ random.setSeed(seed);
+ long timeBase = timeLookupRandomStrings(fstBase, tokens);
+ random.setSeed(seed);
+ long timeOpto = timeLookupRandomStrings(fstOpto, tokens);
+ printf("Sought %d absent terms in %d ms (base) / %d ms (opto), a %d%% change", COUNT, nsToMs(timeBase), nsToMs(timeOpto),
+ -100 * (timeBase - timeOpto) / timeBase);
+ }
+ }
+
+ private long timeLookupRandomStrings(FST<Object> fst, List<String> tokens) throws Exception {
+ final BytesRefFSTEnum<Object> fstEnum = new BytesRefFSTEnum<>(fst);
+ long start = System.nanoTime();
+ for (int i = 0; i < COUNT; i++) {
+ fstEnum.seekExact(new BytesRef(tokens.get(random.nextInt(tokens.size()))));
+ }
+ return System.nanoTime() - start;
+ }
+
+ private String randomString() {
+ int len = random().nextInt(7) + 3;
+ StringBuilder buf = new StringBuilder();
+ for (int i = 0; i < len; i++) {
+ buf.append(random().nextInt(26) + 'a');
+ }
+ return buf.toString();
+ }
+
+ private FST<Object> buildEnglishFST(boolean useDirectAddressing) throws Exception {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("WORDS"), "ASCII"))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ words.add(line);
+ }
+ }
+ return buildFST(words, useDirectAddressing);
+ }
+
+ private FST<Object> buildFST(List<String> words, boolean useDirectAddressing) throws Exception {
+ long start = System.nanoTime();
+ final Outputs<Object> outputs = NoOutputs.getSingleton();
+ final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, true, 15, useDirectAddressing);
+
+ for (String word : words) {
+ b.add(Util.toIntsRef(new BytesRef(word), new IntsRefBuilder()), outputs.getNoOutput());
+ }
+ FST<Object> fst = b.finish();
+ long t = System.nanoTime();
+ printf("Built FST of %d bytes in %d ms", fst.ramBytesUsed(), nsToMs(t - start));
+ return fst;
+ }
+
+ static void printf(String format, Object ... values) {
+ System.out.println(String.format(Locale.ROOT, format, values));
+ }
+
+ static long nsToMs(long ns) {
+ return ns / 1_000_000;
+ }
+
+ public static void main(String... args) throws Exception {
+ byte[] buf = Files.readAllBytes(Paths.get(args[0]));
+ DataInput in = new ByteArrayDataInput(buf);
+ FST<BytesRef> fst = new FST<>(in, ByteSequenceOutputs.getSingleton());
+ BytesRefFSTEnum<BytesRef> fstEnum = new BytesRefFSTEnum<>(fst);
+ int sparseArrayArcCount = 0, directArrayArcCount = 0, listArcCount = 0;
+ while(fstEnum.next() != null) {
+ if (fstEnum.arcs[fstEnum.upto].bytesPerArc == 0) {
+ listArcCount ++;
+ } else if (fstEnum.arcs[fstEnum.upto].arcIdx == Integer.MIN_VALUE) {
+ directArrayArcCount ++;
+ } else {
+ sparseArrayArcCount ++;
+ }
+ }
+ System.out.println("direct arcs = " + directArrayArcCount + ", sparse arcs = " + sparseArrayArcCount +
+ " list arcs = " + listArcCount);
+ }
+
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
index 078ca8b..fb85951 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
@@ -355,7 +355,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
final Builder<Pair<BytesRef,Long>> indexBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1,
0, 0, true, false, Integer.MAX_VALUE,
- FST_OUTPUTS, true, 15);
+ FST_OUTPUTS, true, 15, false);
//if (DEBUG) {
// System.out.println(" compile index for prefix=" + prefix);
//}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
index 3d20412..7fbf237 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
@@ -236,7 +236,7 @@ public class FSTCompletionBuilder {
final Object empty = outputs.getNoOutput();
final Builder<Object> builder = new Builder<>(
FST.INPUT_TYPE.BYTE1, 0, 0, true, true,
- shareMaxTailLength, outputs, true, 15);
+ shareMaxTailLength, outputs, true, 15, true);
BytesRefBuilder scratch = new BytesRefBuilder();
BytesRef entry;
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/LookupBenchmarkTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/LookupBenchmarkTest.java
index 12c6416..9f9190a 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/LookupBenchmarkTest.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/LookupBenchmarkTest.java
@@ -162,16 +162,25 @@ public class LookupBenchmarkTest extends LuceneTestCase {
*/
private Lookup buildLookup(Class<? extends Lookup> cls, Input[] input) throws Exception {
Lookup lookup = null;
- try {
- lookup = cls.newInstance();
- } catch (InstantiationException e) {
- Analyzer a = new MockAnalyzer(random, MockTokenizer.KEYWORD, false);
- if (cls == AnalyzingInfixSuggester.class || cls == BlendedInfixSuggester.class) {
- Constructor<? extends Lookup> ctor = cls.getConstructor(Directory.class, Analyzer.class);
- lookup = ctor.newInstance(FSDirectory.open(createTempDir("LookupBenchmarkTest")), a);
- } else {
- Constructor<? extends Lookup> ctor = cls.getConstructor(Analyzer.class);
- lookup = ctor.newInstance(a);
+ if (cls == TSTLookup.class || cls == FSTCompletionLookup.class || cls == WFSTCompletionLookup.class) {
+ Constructor<? extends Lookup> ctor = cls.getConstructor(Directory.class, String.class);
+ lookup = ctor.newInstance(FSDirectory.open(createTempDir("LookupBenchmarkTest")), "test");
+ } else {
+ try {
+ lookup = cls.getConstructor().newInstance();
+ } catch (InstantiationException | NoSuchMethodException e) {
+ Analyzer a = new MockAnalyzer(random, MockTokenizer.KEYWORD, false);
+ if (cls == AnalyzingInfixSuggester.class || cls == BlendedInfixSuggester.class) {
+ Constructor<? extends Lookup> ctor = cls.getConstructor(Directory.class, Analyzer.class);
+ lookup = ctor.newInstance(FSDirectory.open(createTempDir("LookupBenchmarkTest")), a);
+ } else if (cls == AnalyzingSuggester.class) {
+ lookup = new AnalyzingSuggester(FSDirectory.open(createTempDir("LookupBenchmarkTest")), "test", a);
+ } else if (cls == FuzzySuggester.class) {
+ lookup = new FuzzySuggester(FSDirectory.open(createTempDir("LookupBenchmarkTest")), "test", a);
+ } else {
+ Constructor<? extends Lookup> ctor = cls.getConstructor(Analyzer.class);
+ lookup = ctor.newInstance(a);
+ }
}
}
lookup.build(new InputArrayIterator(input));
@@ -278,4 +287,4 @@ public class LookupBenchmarkTest extends LuceneTestCase {
this.average = Average.from(times.subList(warmup, times.size()));
}
}
-}
\ No newline at end of file
+}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java b/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
index 8e6a4ea..79c4c3f 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
@@ -279,7 +279,7 @@ public class FSTTester<T> {
allowRandomSuffixSharing ? TestUtil.nextInt(random, 1, 10) : Integer.MAX_VALUE,
outputs,
true,
- 15);
+ 15, true);
for(InputOutput<T> pair : pairs) {
if (pair.output instanceof List) {
@@ -301,7 +301,7 @@ public class FSTTester<T> {
out.close();
IndexInput in = dir.openInput("fst.bin", context);
try {
- fst = new FST<>(in, outputs);
+ fst = new FST<T>(in, outputs);
} finally {
in.close();
dir.deleteFile("fst.bin");
@@ -812,3 +812,4 @@ public class FSTTester<T> {
}
}
}
+