对可选缺失字段的弹性搜索查询

An elasticsearch query on an optionally absent field

我有一个具有两个字段的简单对象的弹性索引:

{
   "content": "something",
   "acl": ["andrey", "gilles"]
}

acl字段是一个用户名数组,或者一个值"public",或者它可能根本不存在于一个对象中。我想编写一个查询,为我提供 acl=testuser 或不存在的所有对象。这是我的查询:

{
  "query": {
    "bool": {
      "should": [
        {
          "bool" : {
            "must": [
              {"exists" : { "field" : "acl" }},
              {"match" : {"acl":"testuser"}}
            ]
          },
          "bool": {
            "must_not": [
                "exists": {
                    "field": "acl"
                }
            ]
          }
        }
      ]
    }
  }
}

但是当我执行它时出现错误:

{
  "error": {
    "root_cause": [
      {
        "type": "parsing_exception",
        "reason": "[bool] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
        "line": 12,
        "col": 11
      }
    ],
    "type": "parsing_exception",
    "reason": "[bool] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
    "line": 12,
    "col": 11
  },
  "status": 400
}

知道我做错了什么吗?

您的JSON无效:

  1. 你有一个字段 boolshould 查询中设置了两次
  2. must_not是一个数组,你没有为新对象添加花括号

此外,您不需要 exist 查询与 match 查询一起匹配。所以你只需要在 should 中留下 match 查询和 must_not exist 查询,如下所示:

{
    "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "must_not": [
                            {
                                "exists": {
                                    "field": "acl"
                                }
                            }
                        ]
                    }
                },
                {
                    "match": {
                        "acl": "testuser"
                    }
                }
            ]
        }
    }
}