Skip to content

Commit

Permalink
Fix NPE for when fields are missing in searchNearestVectors (#13195)
Browse files Browse the repository at this point in the history
Related to: #13162

Since this is unreleased, no changelog entry is necessary.
  • Loading branch information
benwtrent authored Mar 20, 2024
1 parent c78533c commit d5f8853
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lucene/core/src/java/org/apache/lucene/index/LeafReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ public final PostingsEnum postings(Term term) throws IOException {
public final TopDocs searchNearestVectors(
String field, float[] target, int k, Bits acceptDocs, int visitedLimit) throws IOException {
FieldInfo fi = getFieldInfos().fieldInfo(field);
if (fi == null || fi.getVectorDimension() == 0) {
return TopDocsCollector.EMPTY_TOPDOCS;
}
FloatVectorValues floatVectorValues = getFloatVectorValues(fi.name);
if (floatVectorValues == null) {
return TopDocsCollector.EMPTY_TOPDOCS;
Expand Down Expand Up @@ -287,6 +290,9 @@ public final TopDocs searchNearestVectors(
public final TopDocs searchNearestVectors(
String field, byte[] target, int k, Bits acceptDocs, int visitedLimit) throws IOException {
FieldInfo fi = getFieldInfos().fieldInfo(field);
if (fi == null || fi.getVectorDimension() == 0) {
return TopDocsCollector.EMPTY_TOPDOCS;
}
ByteVectorValues byteVectorValues = getByteVectorValues(fi.name);
if (byteVectorValues == null) {
return TopDocsCollector.EMPTY_TOPDOCS;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,40 @@ protected Codec getCodec() {
return codec;
}

public void testMissingFieldReturnsNoResults() throws IOException {
try (Directory directory = newDirectory()) {
IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
iwc.setCodec(
new AssertingCodec() {
@Override
public KnnVectorsFormat getKnnVectorsFormatForField(String field) {
return TestUtil.getDefaultKnnVectorsFormat();
}
});
try (IndexWriter iwriter = new IndexWriter(directory, iwc)) {
Document doc = new Document();
doc.add(newTextField("id", "1", Field.Store.YES));
iwriter.addDocument(doc);
}

try (IndexReader ireader = DirectoryReader.open(directory)) {
LeafReader reader = ireader.leaves().get(0).reader();
TopDocs hits =
reader.searchNearestVectors(
"missing_field",
new float[] {1, 2, 3},
10,
reader.getLiveDocs(),
Integer.MAX_VALUE);
assertEquals(0, hits.scoreDocs.length);
hits =
reader.searchNearestVectors(
"id", new float[] {1, 2, 3}, 10, reader.getLiveDocs(), Integer.MAX_VALUE);
assertEquals(0, hits.scoreDocs.length);
}
}
}

public void testTwoFieldsTwoFormats() throws IOException {
try (Directory directory = newDirectory()) {
// we don't use RandomIndexWriter because it might add more values than we expect !!!!1
Expand Down

0 comments on commit d5f8853

Please sign in to comment.