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

Elasticsearch嵌套JSON文档_source过滤查询问题求助

问题分析与解决方案

你当前的查询仅完成了文档级筛选:匹配出包含applied_as: COMMISSION的文档,但Elasticsearch默认会返回完整的_source原始数据,不会自动过滤数组中不符合条件的元素。要实现只保留指定条件的嵌套数组元素,需要用到以下两种方法之一:

方法一:使用Nested字段+inner_hits(推荐,性能更优)

如果你的factor.some_amount_usd字段尚未设置为nested类型,需先更新映射:

PUT form_some_index/_mapping
{
  "properties": {
    "factor": {
      "properties": {
        "some_amount_usd": {
          "type": "nested"
        }
      }
    }
  }
}

之后使用Nested查询配合inner_hits提取符合条件的元素:

GET form_some_index/_search
{
  "query": {
    "nested": {
      "path": "factor.some_amount_usd",
      "query": {
        "match": {
          "factor.some_amount_usd.applied_as": "COMMISSION"
        }
      },
      "inner_hits": {}
    }
  },
  "_source": false // 若仅需过滤后的结果,可关闭原始_source返回
}

inner_hits字段会返回所有符合applied_as: COMMISSION的嵌套元素,原始文档内容可按需关闭。

方法二:使用_source脚本过滤(无需修改映射)

如果不想调整映射,可通过脚本直接过滤_source内容:

GET form_some_index/_search
{
  "query": {
    "match": {
      "factor.some_amount_usd.applied_as": "COMMISSION"
    }
  },
  "_source": {
    "script": {
      "source": """
        def filteredFactor = [];
        for (def f : ctx._source.factor) {
          def filteredAmount = [];
          for (def a : f.some_amount_usd) {
            if (a.applied_as == 'COMMISSION') {
              filteredAmount.add(a);
            }
          }
          if (filteredAmount.size() > 0) {
            f.some_amount_usd = filteredAmount;
            filteredFactor.add(f);
          }
        }
        ctx._source.factor = filteredFactor;
        return ctx._source;
      """
    }
  }
}

该脚本会遍历嵌套数组,仅保留applied_as等于COMMISSION的元素,返回过滤后的_source。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:47:23