【问题标题】:Elasticsearch return unique string from array field after a given filterElasticsearch 在给定过滤器后从数组字段返回唯一字符串
【发布时间】:2021-02-24 16:07:23
【问题描述】:

如何从弹性搜索记录中获取具有给定前缀的所有 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,例如,如果输入是 apple,则 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?

【问题讨论】:

    标签: elasticsearch elasticsearch-aggregation


    【解决方案1】:

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

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

    请检查this other thread,它处理在include 中使用正则表达式——它与您的用例非常相似。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2012-01-22
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多