gpt4 book ai didi

elasticsearch copy_to 字段与聚合的行为不符合预期

转载 作者:行者123 更新时间:2023-11-29 02:52:47 24 4
gpt4 key购买 nike

我有一个包含两个字符串字段的索引映射,field1field2,它们都被声明为 copy_to 到另一个名为 all_fields 的字段。 all_fields 被索引为“not_analyzed”。

当我在 all_fields 上创建桶聚合时,我期望不同的桶将 field1 和 field2 的键连接在一起。相反,我得到了单独的桶,其中 field1 和 field2 的键未连接。

例子:映射:

  {
"mappings": {
"myobject": {
"properties": {
"field1": {
"type": "string",
"index": "analyzed",
"copy_to": "all_fields"
},
"field2": {
"type": "string",
"index": "analyzed",
"copy_to": "all_fields"
},
"all_fields": {
"type": "string",
"index": "not_analyzed"
}
}
}
}
}

数据在:

  {
"field1": "dinner carrot potato broccoli",
"field2": "something here",
}

  {
"field1": "fish chicken something",
"field2": "dinner",
}

聚合:

{
"aggs": {
"t": {
"terms": {
"field": "all_fields"
}
}
}
}

结果:

...
"aggregations": {
"t": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "dinner",
"doc_count": 1
},
{
"key": "dinner carrot potato broccoli",
"doc_count": 1
},
{
"key": "fish chicken something",
"doc_count": 1
},
{
"key": "something here",
"doc_count": 1
}
]
}
}

我只期待 2 个桶,fish chicken somethingdinnerdinner carrot potato broccolisomethinghere

我做错了什么?

最佳答案

您正在寻找的是两个字符串的连接。 copy_to 即使它看起来是这样做的,但实际上不是。使用 copy_to,从概念上讲,您是从 field1field2 创建一组值,而不是将它们连接起来。

对于您的用例,您有两个选择:

  1. 使用_source transformation
  2. 执行脚本聚合

我会推荐 _source 转换,因为我认为它比编写脚本更有效。这意味着,与进行繁重的脚本聚合相比,您在编制索引时付出的代价很小。

对于_source 转换:

PUT /lastseen
{
"mappings": {
"test": {
"transform": {
"script": "ctx._source['all_fields'] = ctx._source['field1'] + ' ' + ctx._source['field2']"
},
"properties": {
"field1": {
"type": "string"
},
"field2": {
"type": "string"
},
"lastseen": {
"type": "long"
},
"all_fields": {
"type": "string",
"index": "not_analyzed"
}
}
}
}
}

和查询:

GET /lastseen/test/_search
{
"aggs": {
"NAME": {
"terms": {
"field": "all_fields",
"size": 10
}
}
}
}

对于脚本聚合,更容易做到(意思是,使用doc['field'].value 而不是更昂贵的_source.field) 添加 .raw 子字段到 field1field2:

PUT /lastseen
{
"mappings": {
"test": {
"properties": {
"field1": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"field2": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"lastseen": {
"type": "long"
}
}
}
}
}

脚本将使用这些 .raw 子字段:

{
"aggs": {
"NAME": {
"terms": {
"script": "doc['field1.raw'].value + ' ' + doc['field2.raw'].value",
"size": 10,
"lang": "groovy"
}
}
}
}

如果没有 .raw 子字段(它们是有意制作的 not_analyzed),您将需要做这样的事情,这会更昂贵:

{
"aggs": {
"NAME": {
"terms": {
"script": "_source.field1 + ' ' + _source.field2",
"size": 10,
"lang": "groovy"
}
}
}
}

关于elasticsearch copy_to 字段与聚合的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com