Andrey
Andrey

Reputation: 21285

An elasticsearch query on an optionally absent field

I have an elastic index of simple objects that have two fields:

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

The acl field is an array of usernames, or a value "public", or it may not be present in an object at all. I want to write a query that gives me all objects where acl=testuser or it doesn't exist. This is my query:

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

But whenI execute it I get an error:

{
  "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
}

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 484

Answers (1)

Eugene
Eugene

Reputation: 3957

Your JSON is invalid:

  1. You have a field bool set twice inside should query
  2. must_not is an array, and you didn't add curly braces for a new object

Besides, you don't need exist query to match together with match query. So you just need to leave match query and must_not exist query inside should like this:

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

Upvotes: 2

Related Questions