AbtPst
AbtPst

Reputation: 8018

Elasticsearch : How to get top 10 distinct values for a field

I am trying to get the top 1 distinct values for a field as

GET /indexName/test/_search?search_type=count
{
  "aggs": {
    "my_fields": {
      "terms": {
        "field": "col1",
        "size": 10
      }
    }
  }

}

and here is what i get

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  },
  "hits": {
    "total": 21030,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "my_fields": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "",
          "doc_count": 21030
        }
      ]
    }
  }
}

in total, i have 21030 records, hence the doc_count. But this is not the result i was expecting. Is there something wrong with my query?

Followup: What if i want to get the top 10 values after applying a filter?

Upvotes: 0

Views: 12685

Answers (3)

sudev pk
sudev pk

Reputation: 125

The following Lucene query can be used to get top 10 distinct year:

#DISTINCT
    GET index_name/type_name/_search?size=10
    {
      "aggs":{
        "distict_Year":{
          "cardinality": {
            "field": "Year"
          }
        }
      }
    }

See here for more

Upvotes: 2

krishna kumar
krishna kumar

Reputation: 1230

And also you can use this,I think thats what you searching for,

 GET /bank/account/_search?search_type=count
          {
           "aggs": {
              "my_fields": {
                   "terms": {
                   "field": "age",
                        "size": 10
                             }
                            }
                   }
           }

Upvotes: 0

krishna kumar
krishna kumar

Reputation: 1230

You can Try Cardinality Metrics. I think it will Solve Your Problem.

GET /indexName/test/_search

{ "size" : 10, "aggs" : { "distinct_colors" : { "cardinality" : { "field" : "col1" } } } }

Upvotes: 1

Related Questions