Home > OS >  Conditions on array of objects in ElasticSearch
Conditions on array of objects in ElasticSearch

Time:12-01

Still new to ES so apologies if this is obvious. Let's say I have a document with the structure like this

{..., 'objectArray': [{'a': 3, 'b': 2}, {'a': 0, 'b': 4}]}

in which my objectArray property is an array of objects. How would I query for documents in this index that have an object within objectArray with a = 3 and b = 4? So the above document would not be in the result set but

{..., 'objectArray': [{'a': 3, 'b': 2}, {'a': 3, 'b': 4}]}

would be

If you could show an example in NEST or just illustrate the type of query so I could read about it, that would be awesome, thanks so much

CodePudding user response:

Assuming that we are talking about a property of type nested, we use nested query.

Mapping

PUT idx_nested
{
  "mappings": {
    "properties": {
      "objectArray":{
        "type": "nested"
      }
    }
  }
}

Documents

POST idx_nested/_doc
{
  "objectArray": [
    {
      "a": 3,
      "b": 2
    },
    {
      "a": 0,
      "b": 4
    }
  ]
}


POST idx_nested/_doc
{
  "objectArray": [
    {
      "a": 3,
      "b": 2
    },
    {
      "a": 3,
      "b": 4
    }
  ]
}

Query

GET idx_nested/_search
{
  "query": {
    "nested": {
      "path": "objectArray",
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "objectArray.a": {
                  "value": 3
                }
              }
            },
            {
              "term": {
                "objectArray.b": {
                  "value": 4
                }
              }
            }
          ]
        }
      }
    }
  }
}

Response:

"hits": [
  {
    "_index": "idx_nested",
    "_id": "4j5VxoQBiZR2Tvxo_zXz",
    "_score": 2,
    "_source": {
      "objectArray": [
        {
          "a": 3,
          "b": 2
        },
        {
          "a": 3,
          "b": 4
        }
      ]
    }
  }
]
  • Related