Denis Nutiu
Denis Nutiu

Reputation: 1453

How do I query for an exact and only one property in ElasticSearch?

I have a document which has the following mapping:

"employees": {
   "type": "dynamic",
   "properties": { 
      "prop1":  { ""type": "text" },
      "prop2": { "type": "text"  }
   }
}

I would like to query for all the documents that have prop1 and that's it, I don't want to get documents that have both prop1 and prop2. If I use a terms query for prop1 I also get documents that may have prop2.

Upvotes: 0

Views: 363

Answers (2)

Denis Nutiu
Denis Nutiu

Reputation: 1453

In the meantime I've learned that a good way of doing it is to keep track of a count of which properties are set. So you can query for the property count and the properties that you want.

Upvotes: 0

Adam T
Adam T

Reputation: 1691

This should work:

GET employees/_search
{
    "query": {
        "bool": {
            "must": [{
                "exists": {
                    "field": "prop1"
                }
            }],
            "must_not": [{
                "exists": {
                    "field": "prop2"
                }
            }]
        }
    }
}

It is saying that prop1 must exist and prop2 must not exist, so you won't get documents that have both prop1 and prop2.

Upvotes: 1

Related Questions