Skip to content

Apache Lucene open-source search software

Add DictionaryColumn for SORTED / SORTED_SET dvs (#16101)

Tim Brookse79c6780627f
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 2d3e50c6354..7257fdeb344 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -299,6 +299,8 @@ API Changes
* GITHUB#16062: Add FlatFieldVectorsWriter.asKnnVectorValues to return directly a KnnVectorValues "view" over
vectors to be written. (Lorenzo Dematte)
+* GITHUB#16101 Add DictionaryColumn for SORTED / SORTED_SET docvalues using experimental column api (Tim Brooks)
+
New Features
---------------------
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/ColumnFieldAdapter.java b/lucene/core/src/java/org/apache/lucene/document/column/ColumnFieldAdapter.java
index bf2610aeda6..09be21ce819 100644
--- a/lucene/core/src/java/org/apache/lucene/document/column/ColumnFieldAdapter.java
+++ b/lucene/core/src/java/org/apache/lucene/document/column/ColumnFieldAdapter.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document.column;
import java.nio.charset.StandardCharsets;
+import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Field;
@@ -45,13 +46,38 @@ public abstract sealed class ColumnFieldAdapter extends Field
/** Returns an adapter for the given column, dispatching on its concrete type. */
public static ColumnFieldAdapter create(Column column) {
- if (column instanceof LongColumn lc) {
- return new LongColumnAdapter(lc);
- } else if (column instanceof BinaryColumn bc) {
- return new BinaryColumnAdapter(bc);
- } else {
- throw new IllegalArgumentException("Unknown column type: " + column.getClass().getName());
- }
+ return switch (column) {
+ case LongColumn lc -> new LongColumnAdapter(lc);
+ case BinaryColumn bc ->
+ new BinaryColumnAdapter(
+ bc.name(),
+ bc.fieldType(),
+ bc.fieldType().stored() ? bc.storedType() : null,
+ bc.tuples());
+ case DictionaryColumn dc ->
+ new BinaryColumnAdapter(
+ dc.name(),
+ dc.fieldType(),
+ dc.fieldType().stored() ? dc.storedType() : null,
+ dictionaryCursor(dc.tuples(), dc.dictionary()));
+ default ->
+ throw new IllegalArgumentException("Unknown column type: " + column.getClass().getName());
+ };
+ }
+
+ private static ObjectTupleCursor<BytesRef> dictionaryCursor(
+ OrdinalsTupleCursor ordinals, List<BytesRef> dictionary) {
+ return new ObjectTupleCursor<>() {
+ @Override
+ public int nextDoc() {
+ return ordinals.nextDoc();
+ }
+
+ @Override
+ public BytesRef value() {
+ return dictionary.get(ordinals.ordValue());
+ }
+ };
}
/** Advances to the next batch-local doc-id with a value. */
@@ -128,18 +154,17 @@ final class BinaryColumnAdapter extends ColumnFieldAdapter {
// Cached UTF-8 decode of the cursor's current value. Invalidated on nextDoc()
private String cachedString;
- BinaryColumnAdapter(BinaryColumn column) {
- super(column.name(), column.fieldType());
- this.cursor = column.tuples();
- this.tokenized = column.fieldType().tokenized();
- this.indexed = column.fieldType().indexOptions() != IndexOptions.NONE;
- if (column.fieldType().stored()) {
- this.storedType = column.storedType();
- this.reusableStoredValue = newReusableStoredValue(storedType);
- } else {
- this.storedType = null;
- this.reusableStoredValue = null;
- }
+ BinaryColumnAdapter(
+ String name,
+ IndexableFieldType fieldType,
+ StoredValue.Type storedType,
+ ObjectTupleCursor<BytesRef> cursor) {
+ super(name, fieldType);
+ this.cursor = cursor;
+ this.tokenized = fieldType.tokenized();
+ this.indexed = fieldType.indexOptions() != IndexOptions.NONE;
+ this.storedType = storedType;
+ this.reusableStoredValue = storedType != null ? newReusableStoredValue(storedType) : null;
}
private static StoredValue newReusableStoredValue(StoredValue.Type type) {
@@ -147,7 +172,7 @@ final class BinaryColumnAdapter extends ColumnFieldAdapter {
case STRING -> new StoredValue("");
case BINARY -> new StoredValue(new BytesRef());
case INTEGER, LONG, FLOAT, DOUBLE, DATA_INPUT ->
- throw new IllegalArgumentException("rejected by ColumnValidation.validateBinaryColumn");
+ throw new IllegalArgumentException("rejected by ColumnValidation");
};
}
@@ -184,7 +209,7 @@ final class BinaryColumnAdapter extends ColumnFieldAdapter {
case STRING -> reusableStoredValue.setStringValue(decodedString());
case BINARY -> reusableStoredValue.setBinaryValue(cursor.value());
case INTEGER, LONG, FLOAT, DOUBLE, DATA_INPUT ->
- throw new IllegalArgumentException("rejected by ColumnValidation.validateBinaryColumn");
+ throw new IllegalArgumentException("rejected by ColumnValidation");
}
return reusableStoredValue;
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java b/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
index 6c1584f87ce..6c8666cfe65 100644
--- a/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
+++ b/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
@@ -134,6 +134,53 @@ public final class ColumnValidation {
}
}
+ /** Validates a {@link DictionaryColumn} against the field type it will feed. */
+ public static void validateDictionaryColumn(
+ DictionaryColumn column, IndexableFieldType fieldType) {
+ final DocValuesType dv = fieldType.docValuesType();
+ if (dv == DocValuesType.NUMERIC || dv == DocValuesType.SORTED_NUMERIC) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" cannot feed docValuesType="
+ + dv
+ + "; use a LongColumn");
+ }
+ if (dv == DocValuesType.BINARY) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" cannot feed docValuesType=BINARY (the writer does not dedup terms, so the"
+ + " dictionary provides no benefit); use a BinaryColumn");
+ }
+ if (fieldType.pointDimensionCount() != 0) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" does not support points (pointDimensionCount must be 0)");
+ }
+ if (fieldType.stored()) {
+ final StoredValue.Type storedType = column.storedType();
+ switch (storedType) {
+ case BINARY, STRING -> {
+ // OK.
+ }
+ case INTEGER, LONG, FLOAT, DOUBLE ->
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" storedType="
+ + storedType
+ + " is not supported; use a LongColumn for numeric stored data");
+ case DATA_INPUT ->
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" storedType DATA_INPUT is not supported for columns");
+ }
+ }
+ }
+
/** Validates a {@link VectorColumn} against the field type it will feed. */
public static void validateVectorColumn(VectorColumn<?> column, IndexableFieldType fieldType) {
if (fieldType.vectorDimension() <= 0) {
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/DictionaryColumn.java b/lucene/core/src/java/org/apache/lucene/document/column/DictionaryColumn.java
new file mode 100644
index 00000000000..e607eb62fd6
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/document/column/DictionaryColumn.java
@@ -0,0 +1,126 @@
+/*
+ * 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.document.column;
+
+import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
+
+import java.util.List;
+import java.util.Objects;
+import org.apache.lucene.document.StoredValue;
+import org.apache.lucene.index.IndexableFieldType;
+import org.apache.lucene.util.BytesRef;
+
+/**
+ * A {@link Column} that provides string or binary values via a pre-defined term dictionary plus
+ * per-doc ordinals into that dictionary. Used for {@link
+ * org.apache.lucene.index.DocValuesType#SORTED SORTED} and {@link
+ * org.apache.lucene.index.DocValuesType#SORTED_SET SORTED_SET} doc values, for stored binary or
+ * string fields, and for term inversion (tokenized or untokenized).
+ *
+ * <p>Iteration is performed via cursors. {@link #tuples()} is always available and yields {@code
+ * (docID, ordinal)} pairs. {@link #values()} is a bulk cursor over consecutive doc-ids; it must be
+ * overridden when {@link #density()} is {@link Column.Density#DENSE DENSE} and is only consulted in
+ * that case.
+ *
+ * <p>The caller supplies a fixed {@code List<BytesRef> dictionary} at construction. Per-doc
+ * ordinals returned by cursors index into this dictionary.
+ *
+ * <p>Duplicate dictionary entries are permitted; two slots with the same bytes will both resolve to
+ * the same Lucene-level ordinal. The dictionary may be in any order.
+ *
+ * <p>The dictionary list and the backing byte arrays of its entries must not be mutated after the
+ * column is constructed.
+ *
+ * @lucene.experimental
+ */
+public abstract class DictionaryColumn extends Column {
+
+ private final List<BytesRef> dictionary;
+
+ /**
+ * Creates a DictionaryColumn.
+ *
+ * @param name the field name
+ * @param fieldType describes how this field should be indexed
+ * @param density whether every batch-local doc-id has a value
+ * @param dictionary the term universe; entries must be non-null and no longer than {@code
+ * ByteBlockPool.BYTE_BLOCK_SIZE - 2}. Must contain at least one entry. Duplicate entries are
+ * allowed but incur a minor per-batch cost.
+ */
+ protected DictionaryColumn(
+ String name, IndexableFieldType fieldType, Density density, List<BytesRef> dictionary) {
+ super(name, fieldType, density);
+ Objects.requireNonNull(dictionary, "dictionary must not be null");
+ if (dictionary.isEmpty()) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \"" + name + "\": dictionary must not be empty");
+ }
+ for (int i = 0; i < dictionary.size(); i++) {
+ BytesRef entry = dictionary.get(i);
+ if (entry == null) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \"" + name + "\": dictionary entry at index " + i + " is null");
+ }
+ if (entry.length > (BYTE_BLOCK_SIZE - 2)) {
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + name
+ + "\": dictionary entry at index "
+ + i
+ + " is too large, must be <= "
+ + (BYTE_BLOCK_SIZE - 2));
+ }
+ }
+ this.dictionary = dictionary;
+ }
+
+ /**
+ * Returns the term dictionary. The list is indexed by ordinal; cursors must produce values in
+ * {@code [0, dictionary().size())}.
+ */
+ public final List<BytesRef> dictionary() {
+ return dictionary;
+ }
+
+ /**
+ * Returns a fresh tuple cursor starting at the beginning of the batch. Always available,
+ * regardless of {@link #density()}.
+ */
+ public abstract OrdinalsTupleCursor tuples();
+
+ /**
+ * Returns a fresh dense cursor for doc-ids {@code [0, numDocs)}, producing exactly one ordinal
+ * per doc. Must be overridden when {@link #density()} is {@link Column.Density#DENSE DENSE}; the
+ * default implementation throws {@link UnsupportedOperationException} and is never called for
+ * {@link Column.Density#SPARSE SPARSE} columns.
+ */
+ public OrdinalsCursor values() {
+ throw new UnsupportedOperationException(
+ "values() requires density() == DENSE for column \"" + name() + "\"");
+ }
+
+ /**
+ * The stored-field type emitted for this column. The default is {@link
+ * org.apache.lucene.document.StoredValue.Type#BINARY}. Only {@link
+ * org.apache.lucene.document.StoredValue.Type#BINARY} and {@link
+ * org.apache.lucene.document.StoredValue.Type#STRING} are supported; subclasses may override to
+ * emit string stored values.
+ */
+ public StoredValue.Type storedType() {
+ return StoredValue.Type.BINARY;
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsCursor.java b/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsCursor.java
new file mode 100644
index 00000000000..ce67dc96357
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsCursor.java
@@ -0,0 +1,55 @@
+/*
+ * 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.document.column;
+
+/**
+ * A dense values cursor over a {@link DictionaryColumn}. Produces exactly {@link #size()} ordinals
+ * for consecutive batch-local doc-ids starting at 0, one per call to {@link #nextOrd()}.
+ *
+ * <p>Each ordinal must be in {@code [0, column.dictionary().length)}.
+ *
+ * <p>Implementations must throw an exception if {@link #nextOrd()} is called more than {@link
+ * #size()} times.
+ *
+ * @lucene.experimental
+ */
+public abstract class OrdinalsCursor {
+
+ private final int size;
+
+ /**
+ * Creates a cursor that will produce exactly {@code size} ordinals, one per batch-local doc-id in
+ * {@code [0, size)}.
+ */
+ protected OrdinalsCursor(int size) {
+ this.size = size;
+ }
+
+ /** Total number of ordinals this cursor will produce. */
+ public final int size() {
+ return size;
+ }
+
+ /**
+ * Returns the next ordinal. Must not be called more than {@link #size()} times.
+ *
+ * <p>The returned value must be in {@code [0, dictionary.length)} where {@code dictionary} is the
+ * enclosing column's dictionary. The indexing path validates this on every call and throws {@link
+ * IllegalArgumentException} on violation.
+ */
+ public abstract int nextOrd();
+}
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsTupleCursor.java b/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsTupleCursor.java
new file mode 100644
index 00000000000..ef1c49a0084
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/document/column/OrdinalsTupleCursor.java
@@ -0,0 +1,50 @@
+/*
+ * 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.document.column;
+
+import org.apache.lucene.search.DocIdSetIterator;
+
+/**
+ * A tuple cursor over a {@link DictionaryColumn}. Yields {@code (docID, ordinal)} pairs.
+ * Batch-local doc-ids are returned in non-decreasing order; the same doc-id may repeat for
+ * multi-valued fields (e.g. {@link org.apache.lucene.index.DocValuesType#SORTED_SET SORTED_SET}).
+ *
+ * <p>Each ordinal must be in {@code [0, column.dictionary().length)}.
+ *
+ * @lucene.experimental
+ */
+public abstract class OrdinalsTupleCursor {
+
+ /**
+ * Advances to the next tuple and returns its batch-local doc-id, or {@link
+ * DocIdSetIterator#NO_MORE_DOCS} if exhausted.
+ *
+ * <p>Returned doc-ids are batch-local ({@code 0} to {@code numDocs - 1}) and are emitted in
+ * non-decreasing order. The same doc-id may be returned multiple times when a document has
+ * multiple values.
+ */
+ public abstract int nextDoc();
+
+ /**
+ * Returns the ordinal at the current cursor position. Only valid after a successful {@link
+ * #nextDoc()} call that returned a value other than {@link DocIdSetIterator#NO_MORE_DOCS}.
+ *
+ * <p>The returned value must be in {@code [0, dictionary.length)} where {@code dictionary} is the
+ * enclosing column's dictionary.
+ */
+ public abstract int ordValue();
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
index 7f22b2bd857..396ee24e33b 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
@@ -48,10 +48,13 @@ import org.apache.lucene.document.column.Column;
import org.apache.lucene.document.column.ColumnBatch;
import org.apache.lucene.document.column.ColumnFieldAdapter;
import org.apache.lucene.document.column.ColumnValidation;
+import org.apache.lucene.document.column.DictionaryColumn;
import org.apache.lucene.document.column.LongColumn;
import org.apache.lucene.document.column.LongTupleCursor;
import org.apache.lucene.document.column.LongValuesCursor;
import org.apache.lucene.document.column.ObjectTupleCursor;
+import org.apache.lucene.document.column.OrdinalsCursor;
+import org.apache.lucene.document.column.OrdinalsTupleCursor;
import org.apache.lucene.document.column.VectorColumn;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Sort;
@@ -717,6 +720,8 @@ final class IndexingChain implements Accountable {
ColumnValidation.validateBinaryColumn(bc, fieldType);
} else if (column instanceof LongColumn lc) {
ColumnValidation.validateLongColumn(lc, fieldType);
+ } else if (column instanceof DictionaryColumn dc) {
+ ColumnValidation.validateDictionaryColumn(dc, fieldType);
} else if (column instanceof VectorColumn<?> vc) {
ColumnValidation.validateVectorColumn(vc, fieldType);
}
@@ -781,6 +786,8 @@ final class IndexingChain implements Accountable {
case LongColumn longCol -> processLongColumn(baseDocID, numDocs, longCol, pf, fieldType);
case BinaryColumn binaryCol ->
processBinaryColumn(baseDocID, numDocs, binaryCol, pf, fieldType);
+ case DictionaryColumn dictCol ->
+ processDictionaryColumn(baseDocID, numDocs, dictCol, pf, fieldType);
case VectorColumn<?> vectorCol ->
processVectorColumn(baseDocID, numDocs, vectorCol, pf, fieldType);
default ->
@@ -1135,6 +1142,42 @@ final class IndexingChain implements Accountable {
}
}
+ private static void processDictionaryColumn(
+ int baseDocID,
+ int numDocs,
+ DictionaryColumn column,
+ PerField pf,
+ IndexableFieldType fieldType)
+ throws IOException {
+ final DocValuesType dvType = fieldType.docValuesType();
+ final List<BytesRef> dict = column.dictionary();
+
+ switch (dvType) {
+ case SORTED -> {
+ SortedDocValuesWriter writer = (SortedDocValuesWriter) pf.docValuesWriter;
+ if (column.density() == Column.Density.DENSE) {
+ OrdinalsCursor cursor = column.values();
+ ColumnValidation.checkDenseCount(column, cursor.size(), numDocs);
+ writer.addDenseOrdinalValues(baseDocID, dict, cursor);
+ } else {
+ writer.addOrdinalTuples(baseDocID, dict, column.tuples());
+ }
+ }
+ case SORTED_SET -> {
+ SortedSetDocValuesWriter writer = (SortedSetDocValuesWriter) pf.docValuesWriter;
+ OrdinalsTupleCursor cursor = column.tuples();
+ writer.addOrdinalTuples(baseDocID, dict, cursor);
+ }
+ // $CASES-OMITTED$
+ default ->
+ throw new IllegalArgumentException(
+ "DictionaryColumn \""
+ + column.name()
+ + "\" has incompatible docValuesType: "
+ + dvType);
+ }
+ }
+
@SuppressWarnings("unchecked")
private static void processVectorColumn(
int baseDocID, int numDocs, VectorColumn<?> column, PerField pf, IndexableFieldType fieldType)
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesWriter.java b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesWriter.java
index 14805858eef..5a5d37ebb51 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesWriter.java
@@ -21,8 +21,11 @@ import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
import java.io.IOException;
import java.util.Arrays;
+import java.util.List;
import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.codecs.DocValuesProducer;
+import org.apache.lucene.document.column.OrdinalsCursor;
+import org.apache.lucene.document.column.OrdinalsTupleCursor;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.ByteBlockPool;
import org.apache.lucene.util.BytesRef;
@@ -104,6 +107,93 @@ class SortedDocValuesWriter extends DocValuesWriter<SortedDocValues> {
updateBytesUsed();
}
+ /**
+ * Bulk-adds dictionary-encoded values from a tuple cursor. Each {@code (docID, ordinal)} pair is
+ * translated to the writer's internal hash term ID on first sight per distinct ordinal;
+ * subsequent docs that use the same ordinal pay only an array lookup. Doc-ids from the cursor are
+ * batch-local and are offset by {@code baseDocID} to produce segment-level ids; they must be
+ * strictly increasing (at most one value per doc).
+ *
+ * <p>All ordinals must be in {@code [0, dictionary.length)}.
+ */
+ void addOrdinalTuples(int baseDocID, List<BytesRef> dictionary, OrdinalsTupleCursor cursor) {
+ int[] ordToHash = new int[dictionary.size()];
+ Arrays.fill(ordToHash, -1);
+ int batchDocID;
+ while ((batchDocID = cursor.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ int docID = baseDocID + batchDocID;
+ if (docID <= lastDocID) {
+ throw new IllegalArgumentException(
+ "DocValuesField \""
+ + fieldInfo.name
+ + "\" appears more than once in this document (only one value is allowed per field)");
+ }
+ int ord = cursor.ordValue();
+ int id = lookupOrTranslate(ord, dictionary, ordToHash);
+ pending.add(id);
+ docsWithField.add(docID);
+ lastDocID = docID;
+ }
+ updateBytesUsed();
+ }
+
+ /**
+ * Bulk-adds one dictionary-encoded value per consecutive doc-id starting at {@code firstDocID}.
+ * The cursor provides exactly one ordinal per doc; all ordinals must be in {@code [0,
+ * dictionary.length)}.
+ *
+ * <p>This path performs one {@code BytesRefHash} lookup per distinct used dictionary entry rather
+ * than one per document.
+ */
+ void addDenseOrdinalValues(int firstDocID, List<BytesRef> dictionary, OrdinalsCursor cursor) {
+ int n = cursor.size();
+ if (n == 0) {
+ return;
+ }
+ assert firstDocID > lastDocID;
+ int[] ordToHash = new int[dictionary.size()];
+ Arrays.fill(ordToHash, -1);
+ int processed = 0;
+ try {
+ while (processed < n) {
+ int ord = cursor.nextOrd();
+ int id = lookupOrTranslate(ord, dictionary, ordToHash);
+ pending.add(id);
+ processed++;
+ }
+ } finally {
+ if (processed > 0) {
+ docsWithField.addRange(firstDocID, firstDocID + processed);
+ lastDocID = firstDocID + processed - 1;
+ }
+ updateBytesUsed();
+ }
+ }
+
+ private int lookupOrTranslate(int ord, List<BytesRef> dictionary, int[] ordToHash) {
+ if (ord < 0 || ord >= dictionary.size()) {
+ throw new IllegalArgumentException(
+ "DocValuesField \""
+ + fieldInfo.name
+ + "\": ordinal "
+ + ord
+ + " is out of range [0, "
+ + dictionary.size()
+ + ")");
+ }
+ int id = ordToHash[ord];
+ if (id < 0) {
+ id = hash.add(dictionary.get(ord));
+ if (id < 0) {
+ id = -id - 1;
+ } else {
+ iwBytesUsed.addAndGet(2 * Integer.BYTES);
+ }
+ ordToHash[ord] = id;
+ }
+ return id;
+ }
+
private void updateBytesUsed() {
final long newBytesUsed = pending.ramBytesUsed() + docsWithField.ramBytesUsed();
iwBytesUsed.addAndGet(newBytesUsed - bytesUsed);
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesWriter.java b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesWriter.java
index 033f694ba1e..e04a8d03199 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesWriter.java
@@ -21,8 +21,10 @@ import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
import java.io.IOException;
import java.util.Arrays;
+import java.util.List;
import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.codecs.DocValuesProducer;
+import org.apache.lucene.document.column.OrdinalsTupleCursor;
import org.apache.lucene.index.SortedDocValuesWriter.BufferedSortedDocValues;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.ArrayUtil;
@@ -98,6 +100,56 @@ class SortedSetDocValuesWriter extends DocValuesWriter<SortedSetDocValues> {
updateBytesUsed();
}
+ /**
+ * Bulk-adds dictionary-encoded values from a tuple cursor. Each {@code (docID, ordinal)} pair is
+ * translated to the writer's internal hash term ID on first sight per distinct ordinal;
+ * subsequent docs that use the same ordinal pay only an array lookup.
+ *
+ * <p>All ordinals must be in {@code [0, dictionary.length)}. Doc-ids from the cursor are
+ * batch-local and are offset by {@code baseDocID} to produce segment-level ids.
+ */
+ void addOrdinalTuples(int baseDocID, List<BytesRef> dictionary, OrdinalsTupleCursor cursor) {
+ int[] ordToHash = new int[dictionary.size()];
+ Arrays.fill(ordToHash, -1);
+ int batchDocID;
+ while ((batchDocID = cursor.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ int docID = baseDocID + batchDocID;
+ assert docID >= currentDoc;
+ if (docID != currentDoc) {
+ finishCurrentDoc();
+ currentDoc = docID;
+ }
+ int ord = cursor.ordValue();
+ if (ord < 0 || ord >= dictionary.size()) {
+ throw new IllegalArgumentException(
+ "DocValuesField \""
+ + fieldInfo.name
+ + "\": ordinal "
+ + ord
+ + " is out of range [0, "
+ + dictionary.size()
+ + ")");
+ }
+ int hashID = ordToHash[ord];
+ if (hashID < 0) {
+ hashID = hash.add(dictionary.get(ord));
+ if (hashID < 0) {
+ hashID = -hashID - 1;
+ } else {
+ iwBytesUsed.addAndGet(2 * Integer.BYTES);
+ }
+ ordToHash[ord] = hashID;
+ }
+ if (currentUpto == currentValues.length) {
+ currentValues = ArrayUtil.grow(currentValues, currentValues.length + 1);
+ iwBytesUsed.addAndGet((currentValues.length - currentUpto) * (long) Integer.BYTES);
+ }
+ currentValues[currentUpto] = hashID;
+ currentUpto++;
+ }
+ updateBytesUsed();
+ }
+
// finalize currentDoc: this deduplicates the current term ids
private void finishCurrentDoc() {
if (currentDoc == -1) {
diff --git a/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java b/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
index 0e99496bb1c..e496603e90f 100644
--- a/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
+++ b/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
@@ -524,4 +524,101 @@ public class ColumnBatchTestUtil {
};
}
}
+
+ /** Sparse {@link DictionaryColumn} backed by parallel docId/ordinal arrays. */
+ public static class ArrayDictionaryColumn extends DictionaryColumn {
+ private final int[] docIds;
+ private final int[] ords;
+ private final StoredValue.Type storedType;
+
+ public ArrayDictionaryColumn(
+ String name,
+ IndexableFieldType fieldType,
+ List<BytesRef> dictionary,
+ int[] docIds,
+ int[] ords) {
+ this(name, fieldType, dictionary, docIds, ords, StoredValue.Type.BINARY);
+ }
+
+ public ArrayDictionaryColumn(
+ String name,
+ IndexableFieldType fieldType,
+ List<BytesRef> dictionary,
+ int[] docIds,
+ int[] ords,
+ StoredValue.Type storedType) {
+ super(name, fieldType, Density.SPARSE, dictionary);
+ assert docIds.length == ords.length;
+ this.docIds = docIds;
+ this.ords = ords;
+ this.storedType = storedType;
+ }
+
+ @Override
+ public StoredValue.Type storedType() {
+ return storedType;
+ }
+
+ @Override
+ public OrdinalsTupleCursor tuples() {
+ return new OrdinalsTupleCursor() {
+ int pos = -1;
+
+ @Override
+ public int nextDoc() {
+ pos++;
+ return pos < docIds.length ? docIds[pos] : DocIdSetIterator.NO_MORE_DOCS;
+ }
+
+ @Override
+ public int ordValue() {
+ return ords[pos];
+ }
+ };
+ }
+ }
+
+ /** Dense {@link DictionaryColumn} backed by a contiguous ordinal array. */
+ public static class ArrayDenseDictionaryColumn extends DictionaryColumn {
+ private final int[] ords;
+
+ public ArrayDenseDictionaryColumn(
+ String name, IndexableFieldType fieldType, List<BytesRef> dictionary, int[] ords) {
+ super(name, fieldType, Density.DENSE, dictionary);
+ this.ords = ords;
+ }
+
+ @Override
+ public OrdinalsTupleCursor tuples() {
+ return new OrdinalsTupleCursor() {
+ int pos = -1;
+
+ @Override
+ public int nextDoc() {
+ pos++;
+ return pos < ords.length ? pos : DocIdSetIterator.NO_MORE_DOCS;
+ }
+
+ @Override
+ public int ordValue() {
+ return ords[pos];
+ }
+ };
+ }
+
+ @Override
+ public OrdinalsCursor values() {
+ return new OrdinalsCursor(ords.length) {
+ int pos = 0;
+
+ @Override
+ public int nextOrd() {
+ if (pos >= ords.length) {
+ throw new IllegalStateException("OrdinalsCursor exhausted: size=" + ords.length);
+ }
+ return ords[pos++];
+ }
+ };
+ }
+ }
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDictionaryColumn.java b/lucene/core/src/test/org/apache/lucene/index/TestDictionaryColumn.java
new file mode 100644
index 00000000000..72f6764f97d
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDictionaryColumn.java
@@ -0,0 +1,947 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.index;
+
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDenseDictionaryColumn;
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDenseLongColumn;
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDictionaryColumn;
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.simpleBatch;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.FieldType;
+import org.apache.lucene.document.NumericDocValuesField;
+import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedSetDocValuesField;
+import org.apache.lucene.document.StoredValue;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.tests.analysis.MockAnalyzer;
+import org.apache.lucene.tests.util.LuceneTestCase;
+import org.apache.lucene.tests.util.TestUtil;
+import org.apache.lucene.util.BytesRef;
+
+/** Tests for {@link org.apache.lucene.document.column.DictionaryColumn} end-to-end indexing. */
+public class TestDictionaryColumn extends LuceneTestCase {
+
+ private static final List<BytesRef> COLORS =
+ List.of(new BytesRef("blue"), new BytesRef("green"), new BytesRef("red"));
+
+ // -------------------------------------------------------------------------
+ // SORTED doc values — sparse path
+ // -------------------------------------------------------------------------
+
+ public void testSortedSparse() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ // docIds 0,1,2 with ords 2,0,1 → "red","blue","green"
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "color",
+ SortedDocValuesField.TYPE,
+ COLORS,
+ new int[] {0, 1, 2},
+ new int[] {2, 0, 1})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+ assertNotNull(sdv);
+
+ assertEquals(0, sdv.nextDoc());
+ assertEquals(new BytesRef("red"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(1, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(2, sdv.nextDoc());
+ assertEquals(new BytesRef("green"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, sdv.nextDoc());
+ assertEquals(3, sdv.getValueCount()); // 3 distinct terms used
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ /**
+ * Many sparse docs reusing a small dictionary: exercises the sparse SORTED bulk path's ord→hash
+ * translation table. The dictionary contains an unused entry which must not be materialized in
+ * the segment's term universe.
+ */
+ public void testSortedSparseLargeBatchReusesDictionary() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ int n = 1000;
+ int[] docIds = new int[n];
+ int[] ords = new int[n];
+ for (int i = 0; i < n; i++) {
+ docIds[i] = i;
+ ords[i] = i % 2; // only ords 0 and 1 used; ord 2 ("red") is in the dictionary but unused
+ }
+
+ w.addBatch(
+ simpleBatch(
+ n,
+ new ArrayDictionaryColumn("color", SortedDocValuesField.TYPE, COLORS, docIds, ords)));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+ assertNotNull(sdv);
+
+ // Only two distinct terms ("blue", "green") were used.
+ assertEquals(2, sdv.getValueCount());
+ for (int i = 0; i < n; i++) {
+ assertEquals(i, sdv.nextDoc());
+ BytesRef expected = i % 2 == 0 ? new BytesRef("blue") : new BytesRef("green");
+ assertEquals(expected, sdv.lookupOrd(sdv.ordValue()));
+ }
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, sdv.nextDoc());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testSortedDense() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ // ords: blue, blue, red
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDenseDictionaryColumn(
+ "color", SortedDocValuesField.TYPE, COLORS, new int[] {0, 0, 2})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+ assertNotNull(sdv);
+
+ assertEquals(0, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(1, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(2, sdv.nextDoc());
+ assertEquals(new BytesRef("red"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, sdv.nextDoc());
+
+ // green was in the dictionary but never used; getValueCount must reflect only used terms
+ assertEquals(2, sdv.getValueCount());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testSortedSet() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ // doc 0: blue, green doc 1: red doc 2: blue, red
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "color",
+ SortedSetDocValuesField.TYPE,
+ COLORS,
+ new int[] {0, 0, 1, 2, 2},
+ new int[] {0, 1, 2, 0, 2})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedSetDocValues ssdv = leaf.getSortedSetDocValues("color");
+ assertNotNull(ssdv);
+
+ // doc 0: blue=0, green=1 (sorted ords)
+ assertEquals(0, ssdv.nextDoc());
+ assertEquals(2, ssdv.docValueCount());
+ assertEquals(new BytesRef("blue"), ssdv.lookupOrd(ssdv.nextOrd()));
+ assertEquals(new BytesRef("green"), ssdv.lookupOrd(ssdv.nextOrd()));
+
+ // doc 1: red
+ assertEquals(1, ssdv.nextDoc());
+ assertEquals(1, ssdv.docValueCount());
+ assertEquals(new BytesRef("red"), ssdv.lookupOrd(ssdv.nextOrd()));
+
+ // doc 2: blue, red
+ assertEquals(2, ssdv.nextDoc());
+ assertEquals(2, ssdv.docValueCount());
+ assertEquals(new BytesRef("blue"), ssdv.lookupOrd(ssdv.nextOrd()));
+ assertEquals(new BytesRef("red"), ssdv.lookupOrd(ssdv.nextOrd()));
+
+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, ssdv.nextDoc());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testSortedSetDeduplicatesWithinDoc() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ // doc 0: blue, blue, red — "blue" should appear only once
+ w.addBatch(
+ simpleBatch(
+ 1,
+ new ArrayDictionaryColumn(
+ "color",
+ SortedSetDocValuesField.TYPE,
+ COLORS,
+ new int[] {0, 0, 0},
+ new int[] {0, 0, 2})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedSetDocValues ssdv = leaf.getSortedSetDocValues("color");
+
+ assertEquals(0, ssdv.nextDoc());
+ assertEquals(2, ssdv.docValueCount()); // blue + red, not blue + blue + red
+ assertEquals(new BytesRef("blue"), ssdv.lookupOrd(ssdv.nextOrd()));
+ assertEquals(new BytesRef("red"), ssdv.lookupOrd(ssdv.nextOrd()));
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testStoredField() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ FieldType storedSorted = new FieldType(SortedDocValuesField.TYPE);
+ storedSorted.setStored(true);
+ storedSorted.freeze();
+
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "color", storedSorted, COLORS, new int[] {0, 1}, new int[] {2, 0})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+
+ StoredFields sf = leaf.storedFields();
+ Document doc0 = sf.document(0);
+ Document doc1 = sf.document(1);
+
+ assertEquals("red", doc0.getBinaryValue("color").utf8ToString());
+ assertEquals("blue", doc1.getBinaryValue("color").utf8ToString());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testDictionaryWithDuplicateEntries() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ // Dictionary: ["blue", "blue", "red"] — two slots for blue
+ List<BytesRef> dict = List.of(new BytesRef("blue"), new BytesRef("blue"), new BytesRef("red"));
+ // ords 0 and 1 both mean "blue"; ord 2 means "red"
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "color",
+ SortedDocValuesField.TYPE,
+ dict,
+ new int[] {0, 1},
+ new int[] {0, 1}))); // doc 0 → ord 0 (blue), doc 1 → ord 1 (also blue)
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+
+ // Both docs have "blue"; getValueCount should be 1 (not 2)
+ assertEquals(0, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(1, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(1, sdv.getValueCount());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testMultipleBatchesDifferentDictionaries() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ List<BytesRef> dict1 = List.of(new BytesRef("blue"), new BytesRef("green"));
+ List<BytesRef> dict2 =
+ List.of(new BytesRef("green"), new BytesRef("purple"), new BytesRef("red"));
+
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "color", SortedDocValuesField.TYPE, dict1, new int[] {0, 1}, new int[] {0, 1})));
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "color",
+ SortedDocValuesField.TYPE,
+ dict2,
+ new int[] {0, 1},
+ new int[] {1, 2}))); // purple, red
+
+ w.forceMerge(1); // merge to one segment; ordinals remapped globally
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+ assertNotNull(sdv);
+
+ // After merge, all 4 docs present with correct values
+ for (int i = 0; i < 4; i++) {
+ assertEquals(i, sdv.nextDoc());
+ }
+ // Verify total distinct values = 4
+ assertEquals(4, sdv.getValueCount());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testMixedWithPlainDocument() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w =
+ new IndexWriter(dir, newIndexWriterConfig().setMergePolicy(new TieredMergePolicy()));
+
+ // Batch adds doc 0 (blue) and doc 1 (red)
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "color", SortedDocValuesField.TYPE, COLORS, new int[] {0, 1}, new int[] {0, 2})));
+
+ // Plain document adds "green" for doc 2
+ Document doc = new Document();
+ doc.add(new SortedDocValuesField("color", new BytesRef("green")));
+ w.addDocument(doc);
+
+ w.forceMerge(1);
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues sdv = leaf.getSortedDocValues("color");
+
+ assertEquals(3, sdv.getValueCount()); // blue, green, red
+
+ // Verify each doc
+ assertEquals(0, sdv.nextDoc());
+ assertEquals(new BytesRef("blue"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(1, sdv.nextDoc());
+ assertEquals(new BytesRef("red"), sdv.lookupOrd(sdv.ordValue()));
+ assertEquals(2, sdv.nextDoc());
+ assertEquals(new BytesRef("green"), sdv.lookupOrd(sdv.ordValue()));
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testOutOfRangeOrdSparseThrows() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ ArrayDictionaryColumn col =
+ new ArrayDictionaryColumn(
+ "color",
+ SortedDocValuesField.TYPE,
+ COLORS, // length 3
+ new int[] {0},
+ new int[] {5}); // ord 5 is out of range
+
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(1, col)));
+
+ w.close();
+ dir.close();
+ }
+
+ public void testOutOfRangeOrdDenseThrows() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ ArrayDenseDictionaryColumn col =
+ new ArrayDenseDictionaryColumn(
+ "color",
+ SortedDocValuesField.TYPE,
+ COLORS, // length 3
+ new int[] {0, 99}); // ord 99 out of range
+
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(2, col)));
+
+ w.close();
+ dir.close();
+ }
+
+ public void testEmptyDictionaryThrows() {
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ new ArrayDictionaryColumn(
+ "f", SortedDocValuesField.TYPE, List.of(), new int[0], new int[0]));
+ }
+
+ public void testNullDictionaryEntryThrows() {
+ List<BytesRef> dict = Arrays.asList(new BytesRef("a"), null);
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ new ArrayDictionaryColumn(
+ "f", SortedDocValuesField.TYPE, dict, new int[0], new int[0]));
+ }
+
+ public void testIncompatibleDocValuesTypeThrows() throws IOException {
+ // NUMERIC is not allowed for DictionaryColumn
+ FieldType numericType = new FieldType();
+ numericType.setDocValuesType(DocValuesType.NUMERIC);
+ numericType.freeze();
+ Directory dir = newDirectory();
+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {
+ ArrayDictionaryColumn col =
+ new ArrayDictionaryColumn("f", numericType, COLORS, new int[] {0}, new int[] {0});
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(1, col)));
+ }
+ dir.close();
+ }
+
+ public void testRejectsBinaryDocValues() throws IOException {
+ // BINARY DV writer doesn't dedup terms, so DictionaryColumn buys nothing there;
+ // validation should redirect to BinaryColumn.
+ FieldType binaryType = new FieldType();
+ binaryType.setDocValuesType(DocValuesType.BINARY);
+ binaryType.freeze();
+ Directory dir = newDirectory();
+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {
+ ArrayDictionaryColumn col =
+ new ArrayDictionaryColumn("f", binaryType, COLORS, new int[] {0}, new int[] {0});
+ IllegalArgumentException e =
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(1, col)));
+ assertTrue(e.getMessage(), e.getMessage().contains("BinaryColumn"));
+ }
+ dir.close();
+ }
+
+ public void testRejectsPoints() throws IOException {
+ FieldType pointType = new FieldType(SortedDocValuesField.TYPE);
+ pointType.setDimensions(1, Integer.BYTES);
+ pointType.freeze();
+ Directory dir = newDirectory();
+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {
+ ArrayDictionaryColumn col =
+ new ArrayDictionaryColumn("f", pointType, COLORS, new int[] {0}, new int[] {0});
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(1, col)));
+ }
+ dir.close();
+ }
+
+ public void testRejectsNumericStoredType() throws IOException {
+ // storedType() returning a numeric type should be rejected during validation
+ FieldType storedSorted = new FieldType(SortedDocValuesField.TYPE);
+ storedSorted.setStored(true);
+ storedSorted.freeze();
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ // Override storedType() to return INTEGER — rejected by validateDictionaryColumn
+ ArrayDictionaryColumn col =
+ new ArrayDictionaryColumn(
+ "f", storedSorted, COLORS, new int[] {0}, new int[] {0}, StoredValue.Type.INTEGER);
+ expectThrows(IllegalArgumentException.class, () -> w.addBatch(simpleBatch(1, col)));
+ w.close();
+ dir.close();
+ }
+
+ public void testInvertedDictionaryColumn() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ FieldType stringType = new FieldType();
+ stringType.setIndexOptions(IndexOptions.DOCS);
+ stringType.setOmitNorms(true);
+ stringType.setTokenized(false);
+ stringType.freeze();
+
+ // ords 0,2,0 → "blue","red","blue"
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "tag", stringType, COLORS, new int[] {0, 1, 2}, new int[] {0, 2, 0})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ IndexSearcher searcher = new IndexSearcher(r);
+ assertEquals(2, searcher.count(new TermQuery(new Term("tag", "blue"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("tag", "red"))));
+ assertEquals(0, searcher.count(new TermQuery(new Term("tag", "green"))));
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testInvertedWithSortedDocValues() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ FieldType invertedDvType = new FieldType();
+ invertedDvType.setIndexOptions(IndexOptions.DOCS);
+ invertedDvType.setOmitNorms(true);
+ invertedDvType.setTokenized(false);
+ invertedDvType.setDocValuesType(DocValuesType.SORTED);
+ invertedDvType.freeze();
+
+ // ords 0,2,0 → "blue","red","blue"
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "color", invertedDvType, COLORS, new int[] {0, 1, 2}, new int[] {0, 2, 0})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ IndexSearcher searcher = new IndexSearcher(r);
+
+ // Verify inverted index
+ assertEquals(2, searcher.count(new TermQuery(new Term("color", "blue"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("color", "red"))));
+
+ // Verify doc values
+ LeafReader leaf = getOnlyLeafReader(r);
+ SortedDocValues dv = leaf.getSortedDocValues("color");
+ assertEquals(0, dv.nextDoc());
+ assertEquals(new BytesRef("blue"), dv.lookupOrd(dv.ordValue()));
+ assertEquals(1, dv.nextDoc());
+ assertEquals(new BytesRef("red"), dv.lookupOrd(dv.ordValue()));
+ assertEquals(2, dv.nextDoc());
+ assertEquals(new BytesRef("blue"), dv.lookupOrd(dv.ordValue()));
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testInvertedWithStoredBinary() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ FieldType invertedStoredType = new FieldType();
+ invertedStoredType.setIndexOptions(IndexOptions.DOCS);
+ invertedStoredType.setOmitNorms(true);
+ invertedStoredType.setTokenized(false);
+ invertedStoredType.setStored(true);
+ invertedStoredType.freeze();
+
+ // ords 0,1,2 → "blue","green","red"
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "color", invertedStoredType, COLORS, new int[] {0, 1, 2}, new int[] {0, 1, 2})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ IndexSearcher searcher = new IndexSearcher(r);
+
+ assertEquals(1, searcher.count(new TermQuery(new Term("color", "blue"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("color", "green"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("color", "red"))));
+
+ LeafReader leaf = getOnlyLeafReader(r);
+ StoredFields storedFields = leaf.storedFields();
+ assertEquals(new BytesRef("blue"), storedFields.document(0).getField("color").binaryValue());
+ assertEquals(new BytesRef("green"), storedFields.document(1).getField("color").binaryValue());
+ assertEquals(new BytesRef("red"), storedFields.document(2).getField("color").binaryValue());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testInvertedWithStoredString() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+
+ FieldType invertedStoredType = new FieldType();
+ invertedStoredType.setIndexOptions(IndexOptions.DOCS);
+ invertedStoredType.setOmitNorms(true);
+ invertedStoredType.setTokenized(false);
+ invertedStoredType.setStored(true);
+ invertedStoredType.freeze();
+
+ // ords 0,1,2 → "blue","green","red"; storedType overridden to STRING
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "color",
+ invertedStoredType,
+ COLORS,
+ new int[] {0, 1, 2},
+ new int[] {0, 1, 2},
+ StoredValue.Type.STRING)));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ IndexSearcher searcher = new IndexSearcher(r);
+
+ assertEquals(1, searcher.count(new TermQuery(new Term("color", "blue"))));
+
+ LeafReader leaf = getOnlyLeafReader(r);
+ StoredFields storedFields = leaf.storedFields();
+ assertEquals("blue", storedFields.document(0).getField("color").stringValue());
+ assertEquals("green", storedFields.document(1).getField("color").stringValue());
+ assertEquals("red", storedFields.document(2).getField("color").stringValue());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testTokenizedDictionaryColumn() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriterConfig config = newIndexWriterConfig(new MockAnalyzer(random()));
+ IndexWriter w = new IndexWriter(dir, config);
+
+ List<BytesRef> phrases =
+ List.of(
+ new BytesRef("quick brown fox"),
+ new BytesRef("lazy brown dog"),
+ new BytesRef("quick fox jumps"));
+
+ // ords 0,1,2 → each phrase goes to a separate doc
+ w.addBatch(
+ simpleBatch(
+ 3,
+ new ArrayDictionaryColumn(
+ "text",
+ TextField.TYPE_NOT_STORED,
+ phrases,
+ new int[] {0, 1, 2},
+ new int[] {0, 1, 2})));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ IndexSearcher searcher = new IndexSearcher(r);
+
+ assertEquals(2, searcher.count(new TermQuery(new Term("text", "quick"))));
+ assertEquals(2, searcher.count(new TermQuery(new Term("text", "brown"))));
+ assertEquals(2, searcher.count(new TermQuery(new Term("text", "fox"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("text", "lazy"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("text", "dog"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("text", "jumps"))));
+ assertEquals(0, searcher.count(new TermQuery(new Term("text", "missing"))));
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testTokenizedWithStoredString() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriterConfig config = newIndexWriterConfig(new MockAnalyzer(random()));
+ IndexWriter w = new IndexWriter(dir, config);
+
+ List<BytesRef> phrases = List.of(new BytesRef("hello world"), new BytesRef("goodbye world"));
+
+ w.addBatch(
+ simpleBatch(
+ 2,
+ new ArrayDictionaryColumn(
+ "text",
+ TextField.TYPE_STORED,
+ phrases,
+ new int[] {0, 1},
+ new int[] {0, 1},
+ StoredValue.Type.STRING)));
+
+ DirectoryReader r = DirectoryReader.open(w);
+ LeafReader leaf = getOnlyLeafReader(r);
+ IndexSearcher searcher = new IndexSearcher(r);
+
+ assertEquals(2, searcher.count(new TermQuery(new Term("text", "world"))));
+ assertEquals(1, searcher.count(new TermQuery(new Term("text", "hello"))));
+
+ StoredFields storedFields = leaf.storedFields();
+ assertEquals("hello world", storedFields.document(0).getField("text").stringValue());
+ assertEquals("goodbye world", storedFields.document(1).getField("text").stringValue());
+
+ r.close();
+ w.close();
+ dir.close();
+ }
+
+ public void testRandomSortedCrossCheck() throws IOException {
+ int iters = atLeast(20);
+ for (int iter = 0; iter < iters; iter++) {
+ int dictSize = TestUtil.nextInt(random(), 1, 32);
+ List<BytesRef> dict = randomDictionary(dictSize);
+ boolean dense = random().nextBoolean();
+ int numBatches = TestUtil.nextInt(random(), 1, 4);
+
+ try (Directory dictDir = newDirectory();
+ Directory plainDir = newDirectory();
+ IndexWriter dictW = new IndexWriter(dictDir, newIndexWriterConfig());
+ IndexWriter plainW = new IndexWriter(plainDir, newIndexWriterConfig())) {
+
+ // Per-insertion-id expected term, or null if the doc has no value.
+ List<BytesRef> expected = new ArrayList<>();
+ int nextId = 0;
+
+ for (int b = 0; b < numBatches; b++) {
+ int batchDocs = TestUtil.nextInt(random(), 1, 60);
+ long[] ids = new long[batchDocs];
+
+ if (dense) {
+ int[] ords = new int[batchDocs];
+ for (int i = 0; i < batchDocs; i++) {
+ int ord = random().nextInt(dictSize);
+ ords[i] = ord;
+ ids[i] = nextId;
+ BytesRef term = dict.get(ord);
+ expected.add(term);
+ Document plainDoc = new Document();
+ plainDoc.add(new SortedDocValuesField("f", term));
+ plainDoc.add(new NumericDocValuesField("id", nextId));
+ plainW.addDocument(plainDoc);
+ nextId++;
+ }
+ dictW.addBatch(
+ simpleBatch(
+ batchDocs,
+ new ArrayDenseDictionaryColumn("f", SortedDocValuesField.TYPE, dict, ords),
+ new ArrayDenseLongColumn("id", NumericDocValuesField.TYPE, ids)));
+ } else {
+ List<Integer> ds = new ArrayList<>();
+ List<Integer> os = new ArrayList<>();
+ for (int i = 0; i < batchDocs; i++) {
+ ids[i] = nextId;
+ Document plainDoc = new Document();
+ plainDoc.add(new NumericDocValuesField("id", nextId));
+ if (random().nextInt(10) < 7) {
+ int ord = random().nextInt(dictSize);
+ ds.add(i);
+ os.add(ord);
+ plainDoc.add(new SortedDocValuesField("f", dict.get(ord)));
+ expected.add(dict.get(ord));
+ } else {
+ expected.add(null);
+ }
+ plainW.addDocument(plainDoc);
+ nextId++;
+ }
+ int[] docIds = ds.stream().mapToInt(Integer::intValue).toArray();
+ int[] ords = os.stream().mapToInt(Integer::intValue).toArray();
+ dictW.addBatch(
+ simpleBatch(
+ batchDocs,
+ new ArrayDictionaryColumn("f", SortedDocValuesField.TYPE, dict, docIds, ords),
+ new ArrayDenseLongColumn("id", NumericDocValuesField.TYPE, ids)));
+ }
+ }
+
+ if (random().nextBoolean()) {
+ dictW.forceMerge(1);
+ plainW.forceMerge(1);
+ }
+
+ try (DirectoryReader dictR = DirectoryReader.open(dictW);
+ DirectoryReader plainR = DirectoryReader.open(plainW)) {
+ assertSortedReadersEqual("f", "id", dictR, plainR, expected);
+ }
+ }
+ }
+ }
+
+ public void testRandomSortedSetCrossCheck() throws IOException {
+ int iters = atLeast(20);
+ for (int iter = 0; iter < iters; iter++) {
+ int dictSize = TestUtil.nextInt(random(), 1, 16);
+ List<BytesRef> dict = randomDictionary(dictSize);
+ int numBatches = TestUtil.nextInt(random(), 1, 4);
+
+ // Per-insertion-id expected term SETS (deduped across the doc).
+ List<Set<BytesRef>> expected = new ArrayList<>();
+ int nextId = 0;
+
+ try (Directory dictDir = newDirectory();
+ Directory plainDir = newDirectory();
+ IndexWriter dictW = new IndexWriter(dictDir, newIndexWriterConfig());
+ IndexWriter plainW = new IndexWriter(plainDir, newIndexWriterConfig())) {
+
+ for (int b = 0; b < numBatches; b++) {
+ int batchDocs = TestUtil.nextInt(random(), 1, 40);
+ List<Integer> ds = new ArrayList<>();
+ List<Integer> os = new ArrayList<>();
+ long[] ids = new long[batchDocs];
+ for (int i = 0; i < batchDocs; i++) {
+ int numValues = random().nextInt(5); // 0..4 values per doc
+ Set<BytesRef> docTerms = new HashSet<>();
+ Document plainDoc = new Document();
+ plainDoc.add(new NumericDocValuesField("id", nextId));
+ ids[i] = nextId;
+ for (int v = 0; v < numValues; v++) {
+ int ord = random().nextInt(dictSize);
+ ds.add(i);
+ os.add(ord);
+ BytesRef term = dict.get(ord);
+ if (docTerms.add(term)) {
+ plainDoc.add(new SortedSetDocValuesField("f", BytesRef.deepCopyOf(term)));
+ }
+ }
+ plainW.addDocument(plainDoc);
+ expected.add(docTerms);
+ nextId++;
+ }
+
+ int[] docIds = ds.stream().mapToInt(Integer::intValue).toArray();
+ int[] ords = os.stream().mapToInt(Integer::intValue).toArray();
+ dictW.addBatch(
+ simpleBatch(
+ batchDocs,
+ new ArrayDictionaryColumn("f", SortedSetDocValuesField.TYPE, dict, docIds, ords),
+ new ArrayDenseLongColumn("id", NumericDocValuesField.TYPE, ids)));
+ }
+
+ if (random().nextBoolean()) {
+ dictW.forceMerge(1);
+ plainW.forceMerge(1);
+ }
+
+ try (DirectoryReader dictR = DirectoryReader.open(dictW);
+ DirectoryReader plainR = DirectoryReader.open(plainW)) {
+ assertSortedSetReadersEqual("f", "id", dictR, plainR, expected);
+ }
+ }
+ }
+ }
+
+ private static List<BytesRef> randomDictionary(int size) {
+ Set<String> uniq = new HashSet<>();
+ while (uniq.size() < size) {
+ uniq.add(TestUtil.randomSimpleString(random(), 1, 12));
+ }
+ List<BytesRef> dict = new ArrayList<>(size);
+ for (String s : uniq) {
+ dict.add(new BytesRef(s));
+ }
+ return dict;
+ }
+
+ private static void assertSortedReadersEqual(
+ String field,
+ String idField,
+ DirectoryReader dictR,
+ DirectoryReader plainR,
+ List<BytesRef> expected)
+ throws IOException {
+ assertEquals(expected.size(), dictR.maxDoc());
+ assertEquals(expected.size(), plainR.maxDoc());
+
+ boolean anyValue = expected.stream().anyMatch(Objects::nonNull);
+ if (!anyValue) {
+ // No doc carries a value for "f"; nothing to compare.
+ return;
+ }
+ checkSortedByInsertionId(field, idField, dictR, expected, "dict");
+ checkSortedByInsertionId(field, idField, plainR, expected, "plain");
+ }
+
+ private static void checkSortedByInsertionId(
+ String field, String idField, DirectoryReader r, List<BytesRef> expected, String label)
+ throws IOException {
+ int seen = 0;
+ for (LeafReaderContext ctx : r.leaves()) {
+ LeafReader leaf = ctx.reader();
+ NumericDocValues ids = leaf.getNumericDocValues(idField);
+ SortedDocValues dv = leaf.getSortedDocValues(field);
+ assertNotNull(label + " reader missing id field", ids);
+ int docID;
+ while ((docID = ids.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ int insertionId = (int) ids.longValue();
+ BytesRef want = expected.get(insertionId);
+ BytesRef got = (dv != null && dv.advanceExact(docID)) ? dv.lookupOrd(dv.ordValue()) : null;
+ assertEquals(label + " at insertionId " + insertionId, want, got);
+ seen++;
+ }
+ }
+ assertEquals(label + " reader saw wrong number of docs", expected.size(), seen);
+ }
+
+ private static void assertSortedSetReadersEqual(
+ String field,
+ String idField,
+ DirectoryReader dictR,
+ DirectoryReader plainR,
+ List<Set<BytesRef>> expected)
+ throws IOException {
+ assertEquals(expected.size(), dictR.maxDoc());
+ assertEquals(expected.size(), plainR.maxDoc());
+
+ boolean anyValue = expected.stream().anyMatch(s -> !s.isEmpty());
+ if (!anyValue) {
+ return;
+ }
+ checkSortedSetByInsertionId(field, idField, dictR, expected, "dict");
+ checkSortedSetByInsertionId(field, idField, plainR, expected, "plain");
+ }
+
+ private static void checkSortedSetByInsertionId(
+ String field, String idField, DirectoryReader r, List<Set<BytesRef>> expected, String label)
+ throws IOException {
+ int seen = 0;
+ for (LeafReaderContext ctx : r.leaves()) {
+ LeafReader leaf = ctx.reader();
+ NumericDocValues ids = leaf.getNumericDocValues(idField);
+ SortedSetDocValues dv = leaf.getSortedSetDocValues(field);
+ assertNotNull(label + " reader missing id field", ids);
+ int docID;
+ while ((docID = ids.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ int insertionId = (int) ids.longValue();
+ Set<BytesRef> want = expected.get(insertionId);
+ Set<BytesRef> got = (dv != null && dv.advanceExact(docID)) ? collect(dv) : Set.of();
+ assertEquals(label + " at insertionId " + insertionId, want, got);
+ seen++;
+ }
+ }
+ assertEquals(label + " reader saw wrong number of docs", expected.size(), seen);
+ }
+
+ private static Set<BytesRef> collect(SortedSetDocValues dv) throws IOException {
+ Set<BytesRef> out = new HashSet<>();
+ for (int i = 0; i < dv.docValueCount(); i++) {
+ out.add(BytesRef.deepCopyOf(dv.lookupOrd(dv.nextOrd())));
+ }
+ return out;
+ }
+}