# Access Query Metadata within an Aggregation

**URL:** <https://discuss.elastic.co/t/access-query-metadata-within-an-aggregation/115149>\
**Category:** Elasticsearch\
**Created:** [January 11, 2018, 5:23pm UTC](https://discuss.elastic.co/t/access-query-metadata-within-an-aggregation/115149 "2018-01-11T17:23:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![emmerich](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/emmerich/32/18419_2.png) [@emmerich](https://discuss.elastic.co/u/emmerich)\
**Post date:** [January 11, 2018, 5:23pm UTC](https://discuss.elastic.co/t/access-query-metadata-within-an-aggregation/115149/1 "2018-01-11T17:23:24Z")

</div>

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'] }
                     }
                 }
             }
         }
    }
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [February 8, 2018, 5:23pm UTC](https://discuss.elastic.co/t/access-query-metadata-within-an-aggregation/115149/2 "2018-02-08T17:23:32Z")

</div>

Closed on February 8, 2018, 5:23pm UTC

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