Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix KNNQuery Precision #882

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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 @@ -8,7 +8,10 @@

package org.opensearch.client.opensearch._types.query_dsl;

import static java.math.RoundingMode.HALF_UP;

import jakarta.json.stream.JsonGenerator;
import java.math.BigDecimal;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.opensearch.client.json.JsonpDeserializable;
Expand Down Expand Up @@ -93,7 +96,9 @@ protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
generator.writeKey("vector");
generator.writeStartArray();
for (float value : this.vector) {
generator.write(value);
BigDecimal b = new BigDecimal(value);
double T = b.setScale(6, HALF_UP).doubleValue();
generator.write(T);
}
generator.writeEnd();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,11 @@ public void toBuilder() {

assertEquals(toJson(copied), toJson(origin));
}

@Test
public void toBuilderPrecision() {
KnnQuery origin = new KnnQuery.Builder().field("field").vector(new float[] { 0.1f, 0.4f }).k(1).build();

assertEquals(toJson(origin), "{\"field\":{\"vector\":[0.1,0.4],\"k\":1}}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
package org.opensearch.client.opensearch.model;

import org.junit.Test;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.opensearch.client.json.jsonb.JsonbJsonpMapper;
import org.opensearch.client.opensearch.core.SearchRequest;

Expand Down Expand Up @@ -61,4 +62,20 @@ public void testParametersNotInJson() {
assertNull(request.q());

}

@Test
public void testKnnVectorPrecision() {

float[] vector = { 0.4f, 0.3f };
SearchRequest request = new SearchRequest.Builder().q("knn").query(q -> q.knn(k -> k.field("values").vector(vector).k(1))).build();

JacksonJsonpMapper mapper = new JacksonJsonpMapper();
String str = toJson(request, mapper);
assertEquals("{\"query\":{\"knn\":{\"values\":{\"vector\":[0.4,0.3],\"k\":1}}}}", str);

request = fromJson(str, SearchRequest.class, mapper);

assertTrue(request.query().isKnn());
assertNull(request.q());
}
}
Loading