Skip to content

Commit 7d2625c

Browse files
committed
Check that we may not have magnitudes at all, or for normalized vectors
1 parent f9447f7 commit 7d2625c

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

server/src/main/java/org/elasticsearch/index/mapper/BlockDocValuesReader.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -532,11 +532,9 @@ public AllReader reader(LeafReaderContext context) throws IOException {
532532
FloatVectorValues floatVectorValues = context.reader().getFloatVectorValues(fieldName);
533533
if (floatVectorValues != null) {
534534
if (fieldType.isNormalized()) {
535-
return new FloatDenseVectorNormalizedValuesBlockReader(
536-
floatVectorValues,
537-
dimensions,
538-
context.reader().getNumericDocValues(fieldType.name() + COSINE_MAGNITUDE_FIELD_SUFFIX)
539-
);
535+
NumericDocValues magnitudeDocValues = context.reader()
536+
.getNumericDocValues(fieldType.name() + COSINE_MAGNITUDE_FIELD_SUFFIX);
537+
return new FloatDenseVectorNormalizedValuesBlockReader(floatVectorValues, dimensions, magnitudeDocValues);
540538
}
541539
return new FloatDenseVectorValuesBlockReader(floatVectorValues, dimensions);
542540
}
@@ -632,8 +630,12 @@ protected void appendDoc(BlockLoader.FloatBuilder builder) throws IOException {
632630
assert floats.length == dimensions
633631
: "unexpected dimensions for vector value; expected " + dimensions + " but got " + floats.length;
634632

635-
assert magnitudeDocValues.advanceExact(iterator.docID());
636-
float magnitude = Float.intBitsToFloat((int) magnitudeDocValues.longValue());
633+
float magnitude = 1.0f;
634+
// If all vectors are normalized, no doc values will be present. The vector may be normalized already, so we may not have a
635+
// stored magnitude for all docs
636+
if ((magnitudeDocValues != null) && magnitudeDocValues.advanceExact(iterator.docID())) {
637+
magnitude = Float.intBitsToFloat((int) magnitudeDocValues.longValue());
638+
}
637639
for (float aFloat : floats) {
638640
builder.appendFloat(aFloat * magnitude);
639641
}

x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/DenseVectorFieldTypeIT.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ public void setup() throws IOException {
209209
for (int j = 0; j < numDims; j++) {
210210
vector.add(randomFloatBetween(0F, 1F, true));
211211
}
212-
if (similarity == DenseVectorFieldMapper.VectorSimilarity.DOT_PRODUCT) {
212+
if ((similarity == DenseVectorFieldMapper.VectorSimilarity.DOT_PRODUCT) || rarely()) {
213213
// Normalize the vector
214214
float magnitude = DenseVector.getMagnitude(vector);
215215
vector.replaceAll(number -> number.floatValue() / magnitude);

0 commit comments

Comments
 (0)