Query all unique values of a field with Elasticsearch

前端 未结 5 932
陌清茗
陌清茗 2020-12-29 19:52

How do I search for all unique values of a given field with Elasticsearch?

I have such a kind of query like select full_name from authors

5条回答
  •  無奈伤痛
    2020-12-29 20:19

    For Elasticsearch 1.0 and later, you can leverage terms aggregation to do this,

    query DSL:

    {
      "aggs": {
        "NAME": {
          "terms": {
            "field": "",
            "size": 10
          }
        }
      }
    }
    

    A real example:

    {
      "aggs": {
        "full_name": {
          "terms": {
            "field": "authors",
            "size": 0
          }
        }
      }
    }
    

    Then you can get all unique values of authors field. size=0 means not limit the number of terms(this requires es to be 1.1.0 or later).

    Response:

    {
        ...
    
        "aggregations" : {
            "full_name" : {
                "buckets" : [
                    {
                        "key" : "Ken",
                        "doc_count" : 10
                    },
                    {
                        "key" : "Jim Gray",
                        "doc_count" : 10
                    },
                ]
            }
        }
    }
    

    see Elasticsearch terms aggregations.

提交回复
热议问题