2

I have added a new nested object field to a elastic search index. I want to update the field with some default value like [ {"key": "xyz", "value": "val1"}]. I am trying to query the index where the field value is empty or null, but was not successful.

I have tried this

"bool": {
  "must_not": {
    "exists": {
      "field": "PropertyFields"
    }
  }
}

sample data

[
  {
    "Id": 1,
    "subjectPropertyFields": [
      {
        "value": "xyz",
        "key": "zzz"
      }
    ]
  },
  {
    "Id": 2
  },
  {
    "Id": 3
  }
]

I want to query ids 2,3 .

2
  • can you please share some sample index data and expected search result ? Commented Nov 28, 2020 at 7:50
  • sample data , i want to query id's 2 and 3 [ { "Id": 1, "subjectPropertyFields": [ { "value": "xyz", "key": "zzz" } ] }, { "Id": 2 }, { "Id": 3 } ] Commented Nov 28, 2020 at 8:13

1 Answer 1

1

If you want to find documents that are missing a nested object field, you can use the must_not boolean query with the exists query.

Adding a working example with index data, mapping, search query, and search result

Index Mapping:

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

Index Data:

{
    "Id": 1,
    "subjectPropertyFields": [
      {
        "value": "xyz",
        "key": "zzz"
      }
    ]
  }
  {
    "Id": 2
  }
  {
    "Id": 3
  }

Search Query:

 {
  "query": {
    "bool": {
      "must_not": [
        {
          "nested": {
            "path": "subjectPropertyFields",
            "query": {
              "bool": {
                "filter": {
                  "exists": {
                    "field": "subjectPropertyFields"
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "65047473",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.0,
        "_source": {
          "Id": 2
        }
      },
      {
        "_index": "65047473",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.0,
        "_source": {
          "Id": 3
        }
      }
    ]
Sign up to request clarification or add additional context in comments.

5 Comments

@Ajay Kumar please go through my answer, and let me know if this resolves your issue ?
@Ajay Kumar thank u for accepting the answer, can you please upvote the answer as well :)
thank you , can you help me with the query if i need to add additional query like isdata = true and the existing query logic for the same .
@AjayKumar you can use a combination of bool query (with the match clause) for the same, and it would be better if you can ask a separate question for the same with your new requirements :)
@AjayKumar does there exist a field in your document named isdata ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.