When querying Elasticsearch from Spring-Data I would like to get the _score
If we take the simple following Class:
@Document(indexName = "test", type = "el_test")
public static class ElTest{
private long id;
private String myField;
}
With a JUnit Test
@Test
public void testScore() throws Exception {
elasticsearchTemplate.index(new IndexQueryBuilder()
.withIndexName("test")
.withObject(new ElTest("first value"))
.build());
elasticsearchTemplate.index(new IndexQueryBuilder()
.withIndexName("test")
.withObject(new ElTest("second value"))
.build());
elasticsearchTemplate.index(new IndexQueryBuilder()
.withIndexName("test")
.withObject(new ElTest("third"))
.build());
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("myField","second value"))
.build();
List<ElTest> els = elasticsearchTemplate.queryForList(query, ElTest.class);
assertEquals(2, els.size());
}
This will create 3 entries in Elasticsearch. The query will retrieve two values with different scores.
If we put the request directly in Elasticsearch:
POST /test/_search
{
"query": {
"match" : {
"myField" : {
"query" : "second value",
"type" : "boolean"
}
}
}
}
And the response from Elasticsearch:
{
"took": 15,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.8838835,
"hits": [
{
"_index": "test",
"_type": "el_test",
"_id": "AVKmmYCL3xnXT_BGRA3T",
"_score": 0.8838835,
"_source": {
"id": 0,
"myField": "second value"
}
},
{
"_index": "test",
"_type": "el_test",
"_id": "AVKmmYCI3xnXT_BGRA3S",
"_score": 0.028130025,
"_source": {
"id": 0,
"myField": "first value"
}
}
]
}
}
As I got a list of ElTest object back, I cannot retrieve the _score value (0.8838835 and 0.028130025). Is there a way to get the value in Spring-data?
I would imagine something like
@Document(indexName = "test", type = "el_test")
public static class ElTest{
private long id;
private String myField;
@Score
private double score;
}
Where Score would be an annotation indicating the field is filled by Elasticsearch.
The reason why I want the score is to sort the list in the gui.
Due to the many dto mappings from Elasticsearch up to the gui the list gets unsorted at some place. It is therefore not reliable.
I could of course add an score value by hand, but it would require to iterate over the list. Which is not very nice.
I use Spring-data-elasticsearch Version 1.2.0 and therefore Elasticsearch 1.4.4