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

如何用ExistsQuery筛选user类型为Object而非数组的document?

问题解答

首先明确:ExistsQuery无法实现你的需求。因为ExistsQuery仅检查字段是否存在,不管字段是Object类型还是数组类型——哪怕document.user是包含元素的数组,ExistsQuery也会将这类文档纳入结果,这就是你当前查询返回数据不一致的原因。

要过滤出仅document.user为Object类型的文档,需要借助Elasticsearch的脚本查询(Script Query),通过Painless脚本判断字段的类型。以下是两种可行的查询方案:

方案1:直接匹配Object类型字段

GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "exists": {
            "field": "document.user"
          }
        },
        {
          "script": {
            "script": {
              "source": "doc['document.user'].getType() == 'OBJECT'",
              "lang": "painless"
            }
          }
        }
      ]
    }
  }
}

方案2:排除数组类型字段

GET _search
{
  "query": {
    "bool": {
      "must": {
        "exists": {
          "field": "document.user"
        }
      },
      "must_not": {
        "script": {
          "script": {
            "source": "doc['document.user'].getType() == 'ARRAY'",
            "lang": "painless"
          }
        }
      }
    }
  }
}

说明

  • 两个方案都会先通过exists确保document.user字段存在,再通过脚本过滤类型:
    • 方案1直接匹配类型为OBJECT的字段;
    • 方案2排除类型为ARRAY的字段,最终留下Object类型的文档。
  • 脚本中doc['field'].getType()会返回字段的类型标识,OBJECT对应单个对象,ARRAY对应数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:42:04