You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Elastic Search中筛选仅含指定attributes.name值的文档?

在Elasticsearch中筛选仅包含指定attributes.name的文档

我在Elasticsearch中存储了3个结构如下的文档:

[
    {
        "name": "Test_1",
        "attributes": [
            { "name": "attribute_1" },
            { "name": "attribute_2" }
        ]
    },
    {
        "name": "Test_2",
        "attributes": [
            { "name": "attribute_1" },
            { "name": "attribute_2" },
            { "name": "attribute_3" }
        ]
    },
    {
        "name": "Test_3",
        "attributes": [
            { "name": "attribute_2" },
            { "name": "attribute_3" }
        ]
    }
]

需求:筛选出**仅包含attributes.name为attribute_1和attribute_2**的文档,最终仅返回Test_1,因为它恰好只包含这两个指定值,不多不少。

解决方案

使用布尔查询结合脚本筛选,确保文档同时满足以下条件:

  1. 包含所有指定的属性值
  2. 不包含任何指定之外的属性值
  3. 属性数量与指定的数量一致(避免重复属性的情况)

查询DSL如下:

{
  "query": {
    "bool": {
      "must": [
        {"term": {"attributes.name": "attribute_1"}},
        {"term": {"attributes.name": "attribute_2"}}
      ],
      "filter": [
        {
          "script": {
            "source": "def allowedAttrs = ['attribute_1', 'attribute_2']; doc['attributes.name'].every(attr -> allowedAttrs.contains(attr)) && doc['attributes.name'].size() == allowedAttrs.size()"
          }
        }
      ]
    }
  }
}

逻辑说明

  • must子句:强制文档必须包含attribute_1和attribute_2这两个属性
  • filter中的脚本:
    • 遍历文档所有attributes.name,确保每个值都在允许的列表内
    • 检查属性数量与允许的属性数量完全匹配,防止出现重复属性(比如两个attribute_1)但总数量符合的情况

内容的提问来源于stack exchange,提问作者Disteonne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:46:12