pedramcode
pedramcode

Reputation: 357

Fetch unique values from a field in elasticsearch

I have this document structure :

[
{
   "uuid":1,
   "data":{....},
   "date":"2020-10-10T23:00:00"
},
{
   "uuid":1,
   "data":{....},
   "date":"2020-10-10T23:00:00"
},
{
   "uuid":1,
   "data":{....},
   "date":"2020-10-10T23:00:00"
},
{
   "uuid":2,
   "data":{....},
   "date":"2020-10-10T23:00:00"
},
{
   "uuid":2,
   "data":{....},
   "date":"2020-10-10T23:00:00"
}
]

How can I write a query that returns the uuids. for above example I want this result:

[1, 2]

Upvotes: 0

Views: 48

Answers (1)

Assael Azran
Assael Azran

Reputation: 2993

Aggregation based on uuid field:

A working example:

Mappings

PUT my_index
{
  "mappings": {
    "properties": {
      "uuid": {
        "type": "keyword"
      },
      "date": {
        "type": "date"
      }
    }
  }
}

Insert some documents:

POST my_index/_doc/1
{
   "uuid":1,
   "date":"2020-10-10T23:00:00"
}
POST my_index/_doc/2
{
   "uuid":1,
   "date":"2020-10-10T23:00:00"
}
POST my_index/_doc/3
{
   "uuid":2,
   "date":"2020-10-10T23:00:00"
}
POST my_index/_doc/4
{
   "uuid":2,
   "date":"2020-10-10T23:00:00"
}

Search query:

GET my_index/_search
{
  "size": 0, 
  "aggs": {
    "uuids": {
      "terms": {
        "field": "uuid",
        "size": 10
      }
    }
  }
}

Results

"aggregations" : {
    "uuids" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "1",
          "doc_count" : 2
        },
        {
          "key" : "2",
          "doc_count" : 2
        }
      ]
    }
  }

The key field inside buckets is the uuid value.

Upvotes: 1

Related Questions