Home > Blockchain >  How to get aggregate result in ElasticSearch?
How to get aggregate result in ElasticSearch?

Time:09-06

I need to get distinct values matching some condition in ElasticSearch where the data in this format. The SQL version will be.

select distinct kind_id from xxx where timestamp < date_add(now(), interval -1 day)

The data in elasticsearch is

{
    "id": "19504ec6bacd46aca302dc7e848aa8a1",
    "@kind": "some_data",
    "@kind_id": 4,
    "timestamp": "2022-09-06T00:02:36.697Z",
    "data": "some data"
}

CodePudding user response:

You can use the terms aggregation on your kind_id field to get the required results.

{
    "size":0,
    "query": {
        "range": {
            "timestamp": {
                "gte": "now-1d/d",
                "lt": "now"
            }
        }
    },
    "aggs": {
        "distinct_kind": {
            "terms": {
                "field": "@kind_id"
            }
        }
    }
}
   
  • Related