首页 > 解决方案 > Elasticsearch - 以任何方式找出所有字段值为文本的文档

问题描述

在弹性搜索集群中,我不小心将一些文本推送到理想情况下应该是数字的字段中。后来,我修复了这个问题并推送了 Number 类型的值。现在,我想修复它,以便所有旧值都可以替换为某个数字,我需要找出所有将此字段作为文本的文档。

是否有任何弹性搜索查询可用于获取此信息?

标签: elasticsearchelasticsearch-query

解决方案


我认为这可以通过使用嵌套的aggregations.

在顶层;在子级别使用术语聚合来了解文本值;使用top_hits聚合来获取documents包含这些值的内容。

例如:

GET example_index/_search
{
  "size": 0,
  "aggs": {
    "NAME": {
      "terms": {
        "field": "example_field.keyword",
        "size": 10
      },
      "aggs": {
        "documents": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
}

这个查询;将返回字段的不同值,以及documents子级别中的相关值,例如:

{
  "aggregations": {
    "NAME": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "mistake",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "2QoDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                },
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "qAoDoXEBOCkJkkpwq5T0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                }
              ]
            }
          }
        },
        {
          "key": "520",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "5goDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "1"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}

我上面的例子;我们需要删除documentswithmistake值,您可以简单地通过id删除它们。

注意:如果你有一个大索引,最好在你的代码中编写一个函数来构建聚合,获取响应,过滤值(如果可以解析为数字),然后按 id 删除文档。


推荐阅读