Skip to content
This repository has been archived by the owner on Aug 2, 2022. It is now read-only.

Added validation that vector is not NaN #100

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -246,15 +246,35 @@ public void parse(ParseContext context) throws IOException {

ArrayList<Float> vector = new ArrayList<>();
XContentParser.Token token = context.parser().currentToken();

float value;
if (token == XContentParser.Token.START_ARRAY) {
token = context.parser().nextToken();
while (token != XContentParser.Token.END_ARRAY) {
vector.add(context.parser().floatValue());
value = context.parser().floatValue();

if (Float.isNaN(value)) {
throw new IllegalArgumentException("KNN vector values cannot be NaN");
}

if (Float.isInfinite(value)) {
throw new IllegalArgumentException("KNN vector values cannot be infinity");
}

vector.add(value);
token = context.parser().nextToken();
}
} else if (token == XContentParser.Token.VALUE_NUMBER) {
vector.add(context.parser().floatValue());
value = context.parser().floatValue();

if (Float.isNaN(value)) {
throw new IllegalArgumentException("KNN vector values cannot be NaN");
}

if (Float.isInfinite(value)) {
throw new IllegalArgumentException("KNN vector values cannot be infinity");
}

vector.add(value);
context.parser().nextToken();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ public void testVectorMappingValidationInvalidDimension() {
KNNVectorFieldMapper.MAX_DIMENSION + " for vector: " + FIELD_NAME));
}

public void testVectorMappingValidationInvalidVectorNaN() throws IOException {
Settings settings = Settings.builder()
.put(getKNNDefaultIndexSettings())
.build();

createKnnIndex(INDEX_NAME, settings, createKnnIndexMapping(FIELD_NAME, 2));

Float[] vector = {Float.NaN, Float.NaN};
Exception ex = expectThrows(ResponseException.class, () -> addKnnDoc(INDEX_NAME, "3", FIELD_NAME, vector));
assertThat(ex.getMessage(), containsString("KNN vector values cannot be NaN"));
}

public void testVectorMappingValidationInvalidVectorInfinity() throws IOException {
Settings settings = Settings.builder()
.put(getKNNDefaultIndexSettings())
.build();

createKnnIndex(INDEX_NAME, settings, createKnnIndexMapping(FIELD_NAME, 2));

Float[] vector = {Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY};
Exception ex = expectThrows(ResponseException.class, () -> addKnnDoc(INDEX_NAME, "3", FIELD_NAME, vector));
assertThat(ex.getMessage(), containsString("KNN vector values cannot be infinity"));
}

public void testVectorMappingValidationUpdateDimension() throws Exception {
Settings settings = Settings.builder()
.put(getKNNDefaultIndexSettings())
Expand Down