2

How can I use elastic4s to get all distinct values for particular field?

Example in JSON:

GET persons/_search
{
 "size":"0",
 "aggs" : {
  "uniq_gender" : {
   "terms" : { "field" : "Gender" }
   }
  }
}
smaiakov
  • 470
  • 5
  • 20

2 Answers2

0

Use terms aggregation.

It looks like this:

    index: 'test',
    body: {
        "aggs": {
            "uniq_gender": {
                "terms": {"field": "Gender"}
            }
        }
    },

The response would look a little something like:

{
  "uniq_gender": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
      {
        "key": "male",
        "doc_count": 55
      },
      {
        "key": "female",
        "doc_count": 38
      },
      {
        "key": "other",
        "doc_count": 1
      }
    ]
  }
}

Important to note from the docs:

terms aggregation should be a field of type keyword or any other data type suitable for bucket aggregations. In order to use it with text you will need to enable fielddata.

Meaning if your gender field is index'd as text you have to set fielddata to true on the mapping, find out how to do so here.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
0

For elastic4s client, use termsAgg(name: String, field: String).

For your case, code looks like this:

search("persons")
      .size(0)
      .aggs(
        termsAgg("uniq_gender", "Gender")
      )
Grandys
  • 163
  • 1
  • 1
  • 8