Skip to content

Commit

Permalink
Handle null text values in RankedDocsResults.asMap() (elastic#118597)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoanFM authored and davidkyle committed Dec 16, 2024
1 parent 7846d8d commit f6d4195
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,11 @@ public void writeTo(StreamOutput out) throws IOException {
}

public Map<String, Object> asMap() {
return Map.of(NAME, Map.of(INDEX, index, RELEVANCE_SCORE, relevanceScore, TEXT, text));
if (text != null) {
return Map.of(NAME, Map.of(INDEX, index, RELEVANCE_SCORE, relevanceScore, TEXT, text));
} else {
return Map.of(NAME, Map.of(INDEX, index, RELEVANCE_SCORE, relevanceScore));
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xpack.core.ml.AbstractChunkedBWCSerializationTestCase;
import org.hamcrest.Matchers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RankedDocsResultsTests extends AbstractChunkedBWCSerializationTestCase<RankedDocsResults> {

Expand All @@ -37,6 +39,16 @@ public static RankedDocsResults.RankedDoc createRandomDoc() {
return new RankedDocsResults.RankedDoc(randomIntBetween(0, 100), randomFloat(), randomBoolean() ? null : randomAlphaOfLength(10));
}

public void test_asMap() {
var index = randomIntBetween(0, 100);
var score = randomFloat();
var mapNullText = new RankedDocsResults.RankedDoc(index, score, null).asMap();
assertThat(mapNullText, Matchers.is(Map.of("ranked_doc", Map.of("index", index, "relevance_score", score))));

var mapWithText = new RankedDocsResults.RankedDoc(index, score, "Sample text").asMap();
assertThat(mapWithText, Matchers.is(Map.of("ranked_doc", Map.of("index", index, "relevance_score", score, "text", "Sample text"))));
}

@Override
protected RankedDocsResults mutateInstance(RankedDocsResults instance) throws IOException {
List<RankedDocsResults.RankedDoc> copy = new ArrayList<>(List.copyOf(instance.getRankedDocs()));
Expand Down

0 comments on commit f6d4195

Please sign in to comment.