5

I have a structure like this:

{ "id": "object1", "fields": [{"id": 100, "value": "one"}, {"id": 101, "value": "abc"}]}
{ "id": "object2", "fields": [{"id": 100, "value": "two"}, {"id": 101, "value": "cde"}]}
{ "id": "object3", "fields": [{"id": 100, "value": "three"}]}

where fields are a nested datatype.

With a nested query I can get all objects that have a specific value of given field (for example with: field.id = 101 && field.value = "abc" I can get object1).

How can I query for objects, whose fields arrays don't include given field by its id?

  • Example1: I want all objects that do not have a field with id 101 - returns object3
  • Example2: I want all objects that do not have a field with id 102 - returns object1, 2 and 3

What I'm looking for is basically an exists query (which I can then negate) that accepts a predicate.

1 Answer 1

8

Since you are dealing with nested documents and you want that if neither of the nested document matches the condition then that document should be considered as a match. If I rephrase this, I can say that do not fetch that document which has a nested document that matches the condition. Translating this to the query dsl,

GET <index>/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "nested": {
            "path": "fields",
            "query": {
              "term": {
                "fields.id": 101
              }
            }
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I owe you a good beer (or coffee, if you don't drink) ;) This is precisely what I needed and it seems so obvious now.
Glad it helped. Thanks for the coffee :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.