Nishant Kumar
Nishant Kumar

Reputation: 2169

Elastic search: Nested query with and condition on parent and child

I have 2 sample record like below:

{
    "parents": [
      {
        "child": [
          {
            "is_deleted": false,
            "child_id": -1,
            "timestamp": 1483536052232
          }
        ],
        "parent_id": 810
      },
      {
        "child": [
          {
            "is_deleted": true,
            "child_id": 105,
            "timestamp": 1483537567000
          }
        ],
        "parent_id": 42
      }
    ]
},
{
  "parents": [
      {
        "child": [
          {
            "is_deleted": false,
            "child_id": 105,
            "timestamp": 1483537567000
          }
        ],
        "parent_id": 42
      }
    ]
}

and my mapping:

"properties": {
  "parents": {
    "type": "nested",
    "properties": {
      "parent_id": {
        "type": "integer",
        "doc_values": false
      },
      "child": {
        "type": "nested",
        "properties": {
          "is_deleted": {
            "type": "boolean",
            "doc_values": false
          },
          "child_id": {
            "type": "integer",
            "doc_values": false
          },
          "timestamp": {
            "type": "long",
            "doc_values": false
          }
        }
      }
    }
  }

I want to search by parent ID which has at least one child with is_deleted as false. For example if i will query with parent ID 42, i should get only 2nd document not first.

Upvotes: 0

Views: 1275

Answers (1)

Artholl
Artholl

Reputation: 93

You should use nested query to query nested field.

Here is an example, but I don't know if this is the best solution at least it is a working one:

POST /test1/test/_search
{
   "query": {
      "nested": {
         "path": "parents",
         "query": {
            "bool": {
               "must": [
                  {
                     "match": {
                        "parents.parent_id": 42
                     }
                  },
                  {
                     "nested": {
                        "path": "parents.child",
                        "query": {
                           "term": {
                              "parents.child.is_deleted": "F"
                           }
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

Upvotes: 1

Related Questions