ElasticSearch Sorting parent documents based on number of child documents satisfying some filter


(Ashish Kumar) #1

Problem statement I am having nested documents where I have to apply some filters on nested document and want to sort the parent documents based on the number of nested documents satisfying that filter.

//Sample problem

We needed to apply filter and sort in single query, in this order specifically:

  1. Filter => Blogs having comments from city 'Pune'
  2. Sort => based on No. of comments coming from 'Pune' city

Sample Data:

[{
  "title": "Investment secrets",
  "body":  "What they don't tell you ...",
  "tags":  [ "shares", "equities" ],
  "comments": [
    {
      "id": 12313,
      "city": "Pune",
      "name":    "Mary Brown 1",
      "comment": "Lies, lies, lies ",
      "date":    "2018-10-18"
    },
    {
      "id": 12314,
      "city": "Pune",
      "name":    "Mary Brown 1",
      "comment": "Lies, lies, lies ",
      "date":    "2018-10-20"
    }
  ]
},
{
  "title": "Investment secrets",
  "body":  "What they don't tell you ...",
  "tags":  [ "shares", "equities" ],
  "comments": [
    {
      "id": 12315,
      "city": "Pune",
      "name":    "Mary Brown ",
      "comment": "Lies, lies, lies ",
      "date":    "2018-10-18"
    },
    {
      "id": 12316,
      "city": "Bangalore",
      "name":    "Mary Brown ",
      "comment": "Lies, lies, lies ",
      "date":    "2018-10-20"
    }
  ]
}]

Solutions tried so far:

  1. using scripts field
{  
"query":{  
    "nested":{  
        "path":"comments",
        "inner_hits":{  

        },
        "query":{  
            "term":{  
                "comments.city":{  
                    "value":"Pune"
                }
            }
        }
    }
},
"sort":{  
    "_script":{  
        "script":"params._source.inner_hits.comments.hits.total",
        "type":"number",
        "order":"desc"
    }
}}  

Problem with this solution => inner_hits is not accessible here

  1. We also tried score_mode: sum, but it seems it works more correctly with fields already having numeric values, else it would sort but we can't determine it's relevance. And our current data structure doesn't have any numeric field other than ID .(so can't use score_mode as sum here obviously).

    {
    "query": {
    "nested": {
    "path": "comments",
    "query": {
    "bool": {
    "must": [
    {
    "term": {
    "comments.numericField": {
    "value": "numericValue"
    }
    }
    }
    ]
    }
    },
    "score_mode": "sum",
    "inner_hits": {}
    }
    }
    }

  2. we thought about using custom function_score, but haven't tried it, as it might be complex to decide sorting priority if there are lot of filters.

So, we were thinking of solving this problem, without using score.