Access Query Metadata within an Aggregation


(Steven Hall) #1

I'm running a search and aggregating the results using a top_hit aggregation with a custom sort based on a script.

In this script, I want to aggregate differently depending on which queries in the search were matched. For example, if I matched the query on the field "text", I want to sort by the _score, otherwise I want to sort by the date.

To do this, I'll need to access the search context from within my aggregation. Is there any way to do this? Maybe using named queries or writing a custom script that has access to the execution context?

I've tried to write an example below:

{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "text": "Hello World"
                    }
                 },
                {
                    "match": {
                        "title": "Hello World"
                    }
                 }
            ]
        }
        
     },
    "aggs": {
        "top_hit": {
             "top_hits": {
                 "sort": {
                     "type": "number",
                     "script": {
                         "lang": "expression",
                         "inline": "if(MATCHED_TEXT) { return _score } else { return doc['date'] }
                     }
                 }
             }
         }
    }
}

(system) #2

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