Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch: how to know which field the results are sorted by?

In Elasticsearch, is there any way to check which field the results are sorted by? I want something like inner-hits for sort clause.

Imagine that your documents have this kind of form:

{"numerals" : [  // nested
    {"key": "point", "value": 30},
    {"key": "points", "value": 200},
    {"key": "score", "value": 20},
    {"key": "scores", "value": 40}
  ]
}

and you sort the results by:

{"numerals.value": {
  "nested_path": "numerals",
  "nested_filter": {
    "match": {
      "numerals.key": "score"}}}}

Now I have no idea how to know the field by which the results are actually sorted: it's probably scores at this document, but is perhaps score at the others? There are 2 problems - 1. You cannot use inner-hits nor highlight for the nested fields. and - 2. Even if you can, it doesn't solve the issue if there are multiple matching candidates.

like image 983
akai Avatar asked Oct 18 '22 11:10

akai


1 Answers

The question is about sorting by fields that are inside nested objects.

So this is what the documention https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-sorting.html and https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_nested_sorting_example says:

Elasticsearch will first restrict the nested documents by the "nested_filter"-query and then sort on the same way as for multi-valued fields: Exactly the way as if there would be only the filtered nested documents as inner objects aka as if there would be only the root document with a multi-valued field which contains exactly all value which belong to the filtered nested objects
( in your example there will only one value remain: 20). If you want to be sure about the sort order insert a "mode" parameter: "min", "max", "sum", "avg" or "median"

If you do not specify the "mode" parameter according to the corresponding issue the min-value will be picked for "asc" and the max-value will be picked for "desc"-order:

By default when sorting on a multi-valued field the lowest or highest value will be picked from the field values depending on the sort order.

like image 198
Karsten R. Avatar answered Oct 21 '22 20:10

Karsten R.