myskbj
myskbj

Reputation: 33

Query that satisfies all conditions in an array

The documents are stored in the form below in Elastic Research index.

mapping

{
  "mappings": {
    "properties": {
      "data": {
        "type": "nested" 
      }
    }
  }
}

first docs

{
    "data": [
        {
            "value": "a"
        },
        {
            "value": "a"
        },
        {
            "value": "b"
        }
    ]
}

second docs

{
    "data": [
        {
            "value": "a"
        },
        {
            "value": "a"
        },
        {
            "value": "a"
        }
    ]
}

I want to return the document only when all values in the array are 'a' (second docs)

In this case, how should I make the query condition?

Upvotes: 1

Views: 818

Answers (1)

Bhavya
Bhavya

Reputation: 16192

The nested query searches nested field objects as if they were indexed as separate documents. If an object matches the search, the nested query returns the root parent document.

When using a combination of bool query with must and must_not, it searches for each individual nested object and eliminates the objects that do not match, but if there are some nested objects left, that match with your query, you will get your results.

Try out this below search query, where all the documents are discarded who have a nested object with the b value.

Search Query:

{
  "query": {
    "bool": {
      "must_not": {
        "nested": {
          "path": "data",
          "query": {
            "term": {
              "data.value": "b"
            }
          }
        }
      }
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "stof_64329782",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.0,
        "_source": {
          "data": [
            {
              "value": "a"
            },
            {
              "value": "a"
            },
            {
              "value": "a"
            }
          ]
        }
      }
    ]

Search Query with the combination of multiple bool and nested queries:

The below search query will also give you the required result.

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "data",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "data.value": "a"
                    }
                  }
                ]
              }
            }
          }
        }
      ],
      "must_not": [
        {
          "nested": {
            "path": "data",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "data.value": "b"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 2

Related Questions