首页 > 解决方案 > Elasticsearch 在给定过滤器后从数组字段返回唯一字符串

问题描述

如何从弹性搜索记录中获取具有给定前缀的所有 id 的所有值并使它们唯一。

记录

PUT items/1
{ "ids" :  [ "apple_A", "orange_B" ] }

PUT items/2
{ "ids" :  [ "apple_A", "apple_B" ] }

PUT items/3
{ "ids" :  [ "apple_C", "banana_A" ] }

我需要的是找到给定前缀的所有唯一 ID,例如,如果输入是苹果,则 ID 的输出应该是 ["apple_A", "apple_B", "apple_C"]

到目前为止,我尝试使用术语聚合,通过以下查询,我能够过滤掉具有给定前缀的 id 的文档,但在聚合中它将返回文档的所有 id 部分。

{
  "aggregations": {
    "filterIds": {
      "filter": {
        "bool": {
          "filter": [
            {
              "prefix": {
                "ids.keyword": {
                  "value": "apple"
                }
              }
            }
          ]
        }
      },
      "aggregations": {
        "uniqueIds": {
          "terms": {
            "field": "ids.keyword",
          }
        }
      }
    }
  }
}

如果我们将前缀输入作为苹果,它将返回聚合列表为 [ "appleA", "orange_B", "apple_B","apple_C", "banana_A"]。基本上返回所有具有匹配过滤器的 id。

是否只获取与数组中的前缀匹配的 ID,而不是文档数组中的所有 ID?

标签: elasticsearchelasticsearch-aggregation

解决方案


include您可以使用参数限制返回值:

POST items/_search
{
  "size": 0,
  "aggregations": {
    "filterIds": {
      "filter": {
        "bool": {
          "filter": [
            {
              "prefix": {
                "ids.keyword": {
                  "value": "apple"
                }
              }
            }
          ]
        }
      },
      "aggregations": {
        "uniqueIds": {
          "terms": {
            "field": "ids.keyword",
            "include": "apple.*"    <--
          }
        }
      }
    }
  }
}

请检查处理在其中使用正则表达式的其他线程include——它与您的用例非常相似。


推荐阅读