Sorting parent documents based on the score of a nested child

Hello,

i have the following mapping:

{
  "indexname": {
    "mappings": {
      "object": {
        "properties": {
          "languagedata": {
            "type": "nested",
            "properties": {
              "language": {
                "type": "keyword"
              },
              "title": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword"
                  }
                },
                "analyzer": "standard_lowercase_asciifolding_sort"
              }
            }
          },
          "id": {
            "type": "integer"
          }
        }
      }
    }
  }
}

Is it possible to sort the parent documents based on the score, when doing a match query on the nested object 'languagedata'?

{
  "sort": [
    {
      "_score": {
        "mode": "max",
        "order": "desc",
        "nested_path": "languagedata",
        "nested_filter": {
          "bool": {
            "must": [
              {
                "match": {
                  "languagedata.title": "search_phrase"
                }
              }
            ],
            "filter": [
              {
                "term": {
                  "languagedata.language": "de"
                }
              }
            ]
          }
        }
      }
    }
  ]
}

I know that my sort-example will not work, but it is only an example that shows what I want to do.

Thanks for your help
Uli

The nested query already returns a score based on the query on the nested object. If you do not have any query clauses apart from the nested query, then you can go with just sorting on _score, which is the default sort order.

In other words, this should give you the desired sort order:

GET indexname/_search
{
  "query": {
    "nested": {
      "score_mode": "max", 
      "path": "languagedata",
      "query": {
        "bool": {
            "must": [
              {
                "match": {
                  "languagedata.title": "search_phrase"
                }
              }
            ],
            "filter": [
              {
                "term": {
                  "languagedata.language": "de"
                }
              }
            ]
          }
      }
    }
  }
}
1 Like

And what can I do, in case of other additional query clauses?

You could wrap your nested query in a bool query. You would put the nested query in the must clause, and the other criteria in a filter clause. That way, only your nested query will contribute to the score, and the other clauses will not.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.