Skip to content

Apache Lucene open-source search software

Cache frozen FieldType to skip schema validation (#15886)

Tim Brooks9e1c6a37c6e3
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 8cdfb9e4f48..c86ec77b26f 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -291,6 +291,8 @@ Optimizations
* GITHUB#15779: Improve BytesRefHash.add performance by optimize rehash operation (tyronecai)
+* GITHUB#15886: Cache frozen FieldType to skip redundant schema validation. (Tim Brooks)
+
Bug Fixes
---------------------
* GITHUB#15754: Fix HTMLStripCharFilter to prevent tags from incorrectly consuming subsequent
diff --git a/lucene/core/src/java/org/apache/lucene/document/FieldType.java b/lucene/core/src/java/org/apache/lucene/document/FieldType.java
index 632c3b24e0d..f4ad79ec97f 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FieldType.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FieldType.java
@@ -96,6 +96,15 @@ public class FieldType implements IndexableFieldType {
this.frozen = true;
}
+ /**
+ * Returns the frozen FieldTypes's state.
+ *
+ * @return <code>true</code> if this FieldType is frozen against future modifications.
+ */
+ public boolean isFrozen() {
+ return frozen;
+ }
+
/**
* {@inheritDoc}
*
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 fd5be625493..2edefc662a5 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
@@ -550,8 +550,8 @@ final class IndexingChain implements Accountable {
}
void processDocument(int docID, Iterable<? extends IndexableField> document) throws IOException {
- // number of unique fields by names (collapses multiple field instances by the same name)
- int fieldCount = 0;
+ // number of unique fields by name which need to be init in segment or full validation
+ int fieldsNeedInitOrValidate = 0;
int indexedFieldCount = 0; // number of unique fields indexed with postings
long fieldGen = nextFieldGen++;
int docFieldIdx = 0;
@@ -568,40 +568,40 @@ final class IndexingChain implements Accountable {
// 1st pass over doc fields – verify that doc schema matches the index schema
// build schema for each unique doc field
for (IndexableField field : document) {
- IndexableFieldType fieldType = field.fieldType();
+ final String fieldName = field.name();
+ final IndexableFieldType fieldType = field.fieldType();
final boolean isReserved = field.getClass() == ReservedField.class;
PerField pf =
getOrAddPerField(
- field.name(), false
+ fieldName, false
/* we never add reserved fields during indexing should be done during DWPT setup*/ );
if (pf.reserved != isReserved) {
throw new IllegalArgumentException(
- "\""
- + field.name()
- + "\" is a reserved field and should not be added to any document");
+ "\"" + fieldName + "\" is a reserved field and should not be added to any document");
}
if (pf.fieldGen != fieldGen) { // first time we see this field in this document
- fields[fieldCount++] = pf;
pf.fieldGen = fieldGen;
- pf.reset(docID);
+ pf.reset(docID, fieldType);
+ if (pf.validatedFrozenFieldType == null) {
+ fields[fieldsNeedInitOrValidate++] = pf;
+ }
+ } else if (pf.multiValueForcesDeoptimize(fieldType)) {
+ // Multi-valued field with a different field type than the cached frozen type.
+ // Drop the validated frozen field type to force the validation path.
+ pf.validatedFrozenFieldType = null;
+ fields[fieldsNeedInitOrValidate++] = pf;
}
if (docFieldIdx >= docFields.length) oversizeDocFields();
docFields[docFieldIdx++] = pf;
- updateDocFieldSchema(field.name(), pf.schema, fieldType);
- }
- // For each field, if it's the first time we see this field in this segment,
- // initialize its FieldInfo.
- // If we have already seen this field, verify that its schema
- // within the current doc matches its schema in the index.
- for (int i = 0; i < fieldCount; i++) {
- PerField pf = fields[i];
- if (pf.fieldInfo == null) {
- initializeFieldInfo(pf);
- } else {
- pf.schema.assertSameSchema(pf.fieldInfo);
+ if (pf.validatedFrozenFieldType == null) {
+ updateDocFieldSchema(fieldName, pf.schema, fieldType);
}
}
+ if (fieldsNeedInitOrValidate > 0) {
+ initAndValidateFields(fieldsNeedInitOrValidate);
+ }
+
// 2nd pass over doc fields – index each field
// also count the number of unique fields indexed with postings
docFieldIdx = 0;
@@ -632,6 +632,22 @@ final class IndexingChain implements Accountable {
}
}
+ private void initAndValidateFields(int fieldCount) throws IOException {
+ // For each field, if it's the first time we see this field in this segment,
+ // initialize its FieldInfo.
+ // If we have already seen this field, verify that its schema
+ // within the current doc matches its schema in the index.
+ for (int i = 0; i < fieldCount; i++) {
+ PerField pf = fields[i];
+ if (pf.fieldInfo == null) {
+ initializeFieldInfo(pf);
+ pf.trySetValidatedFrozenFieldType();
+ } else {
+ pf.schema.assertSameSchema(pf.fieldInfo);
+ }
+ }
+ }
+
private void oversizeDocFields() {
PerField[] newDocFields =
new PerField
@@ -1099,6 +1115,14 @@ final class IndexingChain implements Accountable {
private final Analyzer analyzer;
private boolean first; // first in a document
+ /**
+ * Allows IndexingChain to skip schema validation if fields keep using the same frozen field
+ * type
+ */
+ private FieldType validatedFrozenFieldType;
+
+ private IndexableFieldType candidateFieldType;
+
PerField(
String fieldName,
int indexCreatedVersionMajor,
@@ -1116,9 +1140,33 @@ final class IndexingChain implements Accountable {
this.reserved = reserved;
}
- void reset(int docId) {
+ void reset(int docId, IndexableFieldType fieldType) {
first = true;
- schema.reset(docId);
+ if (fieldInfo == null) {
+ // The first time we encounter this field in a segment propose a frozen field to optimize
+ // the validation step. This will be promoted in trySetValidatedFrozenFieldType if it is
+ // frozen and valid.
+ candidateFieldType = fieldType;
+ }
+ if (fieldType == validatedFrozenFieldType) {
+ schema.resetJustDocId(docId);
+ } else {
+ // Encountered new FieldType. Deoptimize the schema validation skip.
+ validatedFrozenFieldType = null;
+ schema.reset(docId);
+ }
+ }
+
+ boolean multiValueForcesDeoptimize(IndexableFieldType fieldType) {
+ return validatedFrozenFieldType != null && fieldType != validatedFrozenFieldType;
+ }
+
+ void trySetValidatedFrozenFieldType() {
+ assert fieldInfo != null;
+ if (candidateFieldType instanceof FieldType ft && ft.isFrozen()) {
+ validatedFrozenFieldType = ft;
+ }
+ candidateFieldType = null;
}
void setFieldInfo(FieldInfo fieldInfo) {
@@ -1536,8 +1584,12 @@ final class IndexingChain implements Accountable {
}
}
- void reset(int doc) {
+ void resetJustDocId(int doc) {
docID = doc;
+ }
+
+ void reset(int doc) {
+ resetJustDocId(doc);
omitNorms = false;
storeTermVector = false;
indexOptions = IndexOptions.NONE;
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexOptions.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexOptions.java
index 3dae50ba62f..6f66a9a6d2c 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexOptions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexOptions.java
@@ -17,7 +17,10 @@
package org.apache.lucene.index;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.List;
+import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
@@ -30,20 +33,22 @@ public class TestIndexOptions extends LuceneTestCase {
public void testChangeIndexOptionsViaAddDocument() throws IOException {
for (IndexOptions from : IndexOptions.values()) {
for (IndexOptions to : IndexOptions.values()) {
- doTestChangeIndexOptionsViaAddDocument(from, to);
+ doTestChangeIndexOptionsViaAddDocument(from, to, false);
}
}
}
- private void doTestChangeIndexOptionsViaAddDocument(IndexOptions from, IndexOptions to)
- throws IOException {
+ private void doTestChangeIndexOptionsViaAddDocument(
+ IndexOptions from, IndexOptions to, boolean freeze) throws IOException {
Directory dir = newDirectory();
IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
FieldType ft1 = new FieldType(TextField.TYPE_STORED);
ft1.setIndexOptions(from);
+ if (freeze) ft1.freeze();
w.addDocument(Collections.singleton(new Field("foo", "bar", ft1)));
FieldType ft2 = new FieldType(TextField.TYPE_STORED);
ft2.setIndexOptions(to);
+ if (freeze) ft2.freeze();
if (from == to) {
w.addDocument(Collections.singleton(new Field("foo", "bar", ft2))); // no exception
} else {
@@ -152,4 +157,200 @@ public class TestIndexOptions extends LuceneTestCase {
IOUtils.close(w1, dir1, dir2);
}
+
+ public void testChangeIndexOptionsViaAddDocumentFrozenFieldType() throws IOException {
+ for (IndexOptions from : IndexOptions.values()) {
+ for (IndexOptions to : IndexOptions.values()) {
+ doTestChangeIndexOptionsViaAddDocument(from, to, true);
+ }
+ }
+ }
+
+ public void testSameFrozenFieldTypeAcrossManyDocuments() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType ft = new FieldType(TextField.TYPE_STORED);
+ ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
+ ft.freeze();
+ int numDocs = atLeast(100);
+ for (int i = 0; i < numDocs; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "bar" + i, ft)));
+ }
+ w.forceMerge(1);
+ try (LeafReader r = getOnlyLeafReader(DirectoryReader.open(w))) {
+ assertEquals(numDocs, r.maxDoc());
+ assertEquals(
+ IndexOptions.DOCS_AND_FREQS, r.getFieldInfos().fieldInfo("foo").getIndexOptions());
+ }
+ w.close();
+ dir.close();
+ }
+
+ public void testMultiValuedFieldSameFrozenFieldType() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType ft = new FieldType(TextField.TYPE_STORED);
+ ft.freeze();
+ Document doc = new Document();
+ doc.add(new Field("foo", "bar1", ft));
+ doc.add(new Field("foo", "bar2", ft));
+ doc.add(new Field("foo", "bar3", ft));
+ w.addDocument(doc);
+ try (LeafReader r = getOnlyLeafReader(DirectoryReader.open(w))) {
+ assertEquals(1, r.maxDoc());
+ assertEquals(3, r.storedFields().document(0).getValues("foo").length);
+ }
+ w.close();
+ dir.close();
+ }
+
+ public void testMultiValuedFieldMixedFrozenAndUnfrozenCompatibleTypes() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType frozenFt = new FieldType(TextField.TYPE_STORED);
+ frozenFt.freeze();
+ // Unfrozen copy with same settings
+ FieldType unfrozenFt = new FieldType(TextField.TYPE_STORED);
+ Document doc = new Document();
+ doc.add(new Field("foo", "bar1", frozenFt));
+ doc.add(new Field("foo", "bar2", unfrozenFt));
+ w.addDocument(doc);
+ try (LeafReader r = getOnlyLeafReader(DirectoryReader.open(w))) {
+ assertEquals(1, r.maxDoc());
+ assertEquals(2, r.storedFields().document(0).getValues("foo").length);
+ }
+ w.close();
+ dir.close();
+ }
+
+ public void testMultiValuedFieldMixedFrozenIncompatibleTypes() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType frozenFt = new FieldType(TextField.TYPE_STORED);
+ frozenFt.setIndexOptions(IndexOptions.DOCS);
+ frozenFt.freeze();
+ FieldType differentFt = new FieldType(TextField.TYPE_STORED);
+ differentFt.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
+ differentFt.freeze();
+ Document doc = new Document();
+ doc.add(new Field("foo", "bar1", frozenFt));
+ doc.add(new Field("foo", "bar2", differentFt));
+ IllegalArgumentException e =
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
+ assertTrue(e.getMessage(), e.getMessage().contains("index options"));
+ w.close();
+ dir.close();
+ }
+
+ public void testFrozenFieldTypeTransitionAcrossDocuments() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ // First doc uses one frozen type
+ FieldType ft1 = new FieldType(TextField.TYPE_STORED);
+ ft1.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
+ ft1.freeze();
+ w.addDocument(Collections.singleton(new Field("foo", "bar", ft1)));
+ // Second doc uses a different frozen type with different options — must fail
+ FieldType ft2 = new FieldType(TextField.TYPE_STORED);
+ ft2.setIndexOptions(IndexOptions.DOCS);
+ ft2.freeze();
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> w.addDocument(Collections.singleton(new Field("foo", "bar", ft2))));
+ assertEquals(
+ "Inconsistency of field data structures across documents for field [foo] of doc [1]."
+ + " index options: expected '"
+ + IndexOptions.DOCS_AND_FREQS
+ + "', but it has '"
+ + IndexOptions.DOCS
+ + "'.",
+ e.getMessage());
+ w.close();
+ dir.close();
+ }
+
+ public void testFrozenFieldTypeCacheRestabilizes() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ // Two distinct frozen FieldType instances with identical settings
+ FieldType ftA = new FieldType(TextField.TYPE_STORED);
+ ftA.freeze();
+ FieldType ftB = new FieldType(TextField.TYPE_STORED);
+ ftB.freeze();
+ assert ftA != ftB; // different instances
+ // First batch with ftA
+ for (int i = 0; i < 10; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "val" + i, ftA)));
+ }
+ // Switch to ftB (same schema, different instance) — triggers cache invalidation + restabilize
+ for (int i = 10; i < 20; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "val" + i, ftB)));
+ }
+ // Switch back to ftA
+ for (int i = 20; i < 30; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "val" + i, ftA)));
+ }
+ try (LeafReader r = getOnlyLeafReader(DirectoryReader.open(w))) {
+ assertEquals(30, r.maxDoc());
+ }
+ w.close();
+ dir.close();
+ }
+
+ public void testFrozenFieldTypeAcrossSegments() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType ft = new FieldType(TextField.TYPE_STORED);
+ ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
+ ft.freeze();
+ // Index several docs in the first segment using the frozen fast-path
+ for (int i = 0; i < 10; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "val" + i, ft)));
+ }
+ w.commit();
+ // Same frozen type in a new segment — should succeed
+ for (int i = 10; i < 20; i++) {
+ w.addDocument(Collections.singleton(new Field("foo", "val" + i, ft)));
+ }
+ w.commit();
+ try (DirectoryReader r = DirectoryReader.open(w)) {
+ assertEquals(20, r.numDocs());
+ }
+ // Different frozen type in a third segment — must fail against global field infos
+ FieldType ft2 = new FieldType(TextField.TYPE_STORED);
+ ft2.setIndexOptions(IndexOptions.DOCS);
+ ft2.freeze();
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> w.addDocument(Collections.singleton(new Field("foo", "bar", ft2))));
+ assertTrue(e.getMessage(), e.getMessage().contains("index options"));
+ w.close();
+ dir.close();
+ }
+
+ public void testFrozenFieldTypeInDocumentBlock() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriterConfig iwc = newIndexWriterConfig();
+ iwc.setParentField("__parent");
+ IndexWriter w = new IndexWriter(dir, iwc);
+ FieldType ft = new FieldType(TextField.TYPE_STORED);
+ ft.freeze();
+ List<Document> block = new ArrayList<>();
+ for (int i = 0; i < 5; i++) {
+ Document child = new Document();
+ child.add(new Field("foo", "child" + i, ft));
+ block.add(child);
+ }
+ Document parent = new Document();
+ parent.add(new Field("foo", "parent", ft));
+ block.add(parent);
+ w.addDocuments(block);
+ try (LeafReader r = getOnlyLeafReader(DirectoryReader.open(w))) {
+ assertEquals(6, r.maxDoc());
+ }
+ w.close();
+ dir.close();
+ }
}