查找存储在 ElasticSearch 字段中的不同字符串值列表

Find list of Distinct string Values stored in a field in ElasticSearch

我已经将我的数据存储在 elasticsearch 中,如下所示。它 returns 只有给定字段中的不同单词,而不是整个不同的短语。

    {
    "_index" : "test01",
    "_type" : "whatever01",
    "_id" : "1234",
    "_score" : 1.0,
    "_source" : {
      "company_name" : "State Bank of India",
      "user" : ""
    }
  },
  {
    "_index" : "test01",
    "_type" : "whatever01",
    "_id" : "5678",
    "_score" : 1.0,
    "_source" : {
      "company_name" : "State Bank of India",
      "user" : ""
    }
  },
  {
    "_index" : "test01",
    "_type" : "whatever01",
    "_id" : "8901",
    "_score" : 1.0,
    "_source" : {
      "company_name" : "Kotak Mahindra Bank",
      "user" : ""
    }
  }

我尝试使用术语聚合函数

    GET /test01/_search/
    {
        "aggs" : {
        "genres":
            {
               "terms" : 
                     { "field": "company_name"} 
             }
          }
    }

我得到以下输出

    "aggregations" : {
"genres" : {
  "doc_count_error_upper_bound" : 0,
  "sum_other_doc_count" : 10531,
  "buckets" : [
    {
      "key" : "bank",
      "doc_count" : 2818
    },
    {
      "key" : "mahindra",
      "doc_count" : 1641
    },
    {
      "key" : "state",
      "doc_count" : 1504
    }]

}}

如何获取字段中的整个字符串 "company_name" 只有不同的值,如下所示?

    "aggregations" : {
"genres" : {
  "doc_count_error_upper_bound" : 0,
  "sum_other_doc_count" : 10531,
  "buckets" : [
    {
      "key" : "Kotak Mahindra Bank",
      "doc_count" : 2818
    },
    {
      "key" : "State Bank of India",
      "doc_count" : 1641
    }
    ]

}}

您似乎已经为类型为 text 的字段 company_name 设置了 "fielddata": "true"。这并不好,因为它最终会消耗大量堆 space,如本 link 中所述。

此外,字段的 text 类型的值 被分解为标记,并使用名为 Analysis 的过程保存在倒排索引中。在文本类型的字段上设置 fielddata 会导致聚合按照您在问题中提到的那样工作。

您需要做的是创建它的同级等效类型 keyword as mentioned in this link 并对该字段执行聚合。

基本上修改 company_name 的映射如下:

映射:

PUT <your_index_name>/_search
{
  "mappings": {
    "mydocs": {
      "properties": {
        "company_name": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

运行 此 company_name.keyword 字段的以下聚合查询,您会得到您要查找的内容。

查询:

POST <your_index_name>/_search
{
  "aggs": {
    "unique_names": {
      "terms": {
        "field": "company_name.keyword",        <----- Run on this field
        "size": 10
      }
    }
  }
}

希望对您有所帮助!