Get one document per bucket in elasticsearch aggregation

I had asked a question in Stack Overflow: https://stackoverflow.com/questions/51816815/get-one-document-per-bucket-in-elasticsearch-aggregation

Sharing it here. Please let me know if you know the solution for the same.

You can use top hits metric for that.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html#_example

1 Like

Hi Peter. Thanks. I saw it earlier but assumed it wont solve the problem but it ended up working once I tried.

This is the query I used:

GET myindex/_search
{
    "size": 0,
    "aggs": {
        "clusters": {
            "terms": {
                "field": "myfield",
                "size": 100000
            },
        "aggs": {
            "mydoc": {
                "top_hits": {
                    "size" : 1
                }
            }
        }
        }
    },
    "query": {
                "bool": {
                    "must": [
                        {
                            "query_string": { "default_field": "field1", "query": "val1" }
                        },
                        {
                            "query_string": { "default_field": "field2", "query": "val2" }
                        }
                    ]
                }
            }
}

Good to hear it solved your problem!

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