Baby.zhou
Baby.zhou

Reputation: 561

Get all docs which not contains the key?

For example,i have 2 type docs,such as

{
    "field2":"xx",
    "field1","x"
}
{
    "field1","x"
}

The one has 2 fields(field1 and field2),another one just has 1 field(field1).

Now,i want to query all docs which do not have field2 field?

EIDT dsl:

 {
    "query": {
        "bool": {
            "filter": [
                {
                    "exists": {
                        "field": "LableToMember"
                    }
                }
            ]
        }
    }
}

doc:

{
    "LableToMember": [
        {
            "xxx": "xxx",
            "id": "1"
        }
    ],
    "field2":"xxx"
}  

LableToMember is a nested field.I find exists api can't be used for nested field?

Upvotes: 1

Views: 967

Answers (2)

Val
Val

Reputation: 217324

Note that in ES 5.x the missing query has been removed in favor of the exists one.

So if you want to be forward compatible, you should prefer using this:

POST /_search
{
    "query": {
        "bool": {
            "must_not": {
                "exists": {
                    "field": "field2"
                }
            }
        }
    }
}

UPDATE

If you want to retrieve all docs which don't have field2 or have field2 with a given value, you can do it like this:

POST /_search
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "field2"
              }
            }
          }
        },
        {
          "term": {
            "field2": "somevalue"
          }
        }
      ]
    }
  }
}

Upvotes: 3

Richa
Richa

Reputation: 7649

In short you want to query those documents which have field2 missing. You can use Missing Query like:

"filter" : {
              "missing" : { "field" : "field2" }
           }

Hope it helps

Upvotes: 0

Related Questions