弹性搜索词聚合

Elastic search term aggregation


我正在编写一个 python 脚本来获取 elasticsearch 索引中的唯一值。我正在使用术语聚合来获取唯一值及其计数。但是,当我将字段列表传递给脚本时,我意识到某些字段存储为
"abc" : {
            "type" : "keyword"
        }

有些存储为

"xyz" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword"
              }
            }
          }

在术语汇总期间,我使用查询

{
    "aggs" : {
        "abc" : {
            "terms" : {
                "field" : "abc"
            }
        }
    }, "size":0
}

但是当这个查询用于“xyz”时它给出了错误Fielddata is disabled on text fields by default. Set fielddata=true on [description] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.

为了 运行 查询“xyz”,我需要向其添加“.keyword”,但“abc”不会 运行。

有什么方法可以检查哪个字段属于哪种类型,然后使用 if/else 相应地更新查询?

您可以同时拥有可聚合和可搜索的字段 w/o .keyword 表示法。只需按照错误消息的建议调整您的映射:

"xyz" : {
   "type" : "text",
   "fielddata": true
}

然后重建索引,一切顺利。

至于是否有 query-time 检查以确定哪些字段是哪些 -- 有 none。 ElasticSearch 的核心原则之一是字段类型是预先确定和定义的,以便它们被适当地索引,从而优化 search/aggregations。因此,假设在查询时您知道哪些字段属于哪种类型。