【问题标题】:Broken aggregation in elasticsearch弹性搜索中的破坏聚合
【发布时间】:2015-11-02 00:35:16
【问题描述】:

我在索引中的字段names 中执行术语聚合时得到错误的结果。 以下是我对names字段的映射:

{
  "dbnames": {
    "properties": {
      "names": {
        "type": "string",
        "index": "not_analyzed"
      }
    }
  }
}

这是我在现场进行简单的terms 聚合得到的结果:

"aggregations": {
  "names": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
      {
        "key": "John Martin",
        "doc_count": 1
      },
      {
        "key": "John martin",
        "doc_count": 1
      },
      {
        "key": " Victor Moses",
        "doc_count": 1
      }
    ]
  }
}

如您所见,我有相同的名称,不同的大小写在聚合中显示为不同的存储桶。我在这里想要的是不管情况如何,名字都应该放在一起。

【问题讨论】:

  • 他们应该如何分组?在John MartinJohn martin 或其他东西下,例如小写的john martin?

标签: elasticsearch


【解决方案1】:

最简单的方法是确保在索引时正确区分 names 字段的值。

如果这不是一个选项,另一种方法是定义一个分析器来为您执行此操作,并将该分析器设置为index_analyzer 用于names 字段。这样的自定义分析器需要使用keyword tokenizer(即将字段的整个值作为单个标记)和lowercase token filter(即小写值)

curl -XPUT localhost:9200/your_index -d '{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "casing": {               <--- custom casing analyzer
            "filter": [
              "lowercase"
            ],
            "tokenizer": "keyword"
          }
        }
      }
    }
  },
  "mappings": {
    "your_type": {
      "properties": {
        "names": {
          "type": "string",
          "index_analyzer": "casing"      <--- use your custom analyzer
        }
      }
    }
  }
}'

然后我们可以索引一些数据:

curl -XPOST localhost:9200/your_index/your_type/_bulk -d '
{"index":{}}
{"names": "John Martin"}
{"index":{}}
{"names": "John martin"}
{"index":{}}
{"names": "Victor Moses"}
'

最后,names 字段上的 terms 聚合将返回您的预期结果:

curl -XPOST localhost:9200/your_index/your_type/_search-d '{
  "size": 0,
  "aggs": {
    "dbnames": {
      "terms": {
        "field": "names"
      }
    }
  }
}'

结果:

{
  "dbnames": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
      {
        "key": "john martin",
        "doc_count": 2
      },
      {
        "key": "victor moses",
        "doc_count": 1
      }
    ]
  }
}

【讨论】:

    【解决方案2】:

    这里有两个选项

    1. 使用 not_analyzed 选项 - 这个选项有一个相同的缺点 不同大小写的字符串不会被视为 on
    2. 关键字标记器 + 小写过滤器 - 这个没有 以上问题

    我已经在此处简洁地概述了这两种方法以及如何使用它们 - https://qbox.io/blog/elasticsearch-aggregation-custom-analyzer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 2019-11-08
      • 2021-02-19
      • 2023-03-18
      • 2021-10-11
      • 1970-01-01
      相关资源
      最近更新 更多