Friday, 6 November 2015

Elasticsearch: exists filter : Check for existence of a field

exists filter is used to check whether given document contains field or not.  “exists” returns documents that have at least one non null value in the field.

Example
"exists" : { "field" : "user" }

Return all the documents that contains field user, which has at least one non-null value.
I inserted below student data into college index.
PUT /_bulk
{"create" : {"_index": "college", "_type": "student", "_id": "1" }}
{"id":358,"firstName":"Hari Krishna","lastName":"Gurram", "hobbies":["visiting places","watching movies","chat with friends"]}
{"create" : {"_index": "college", "_type": "student", "_id": "2" }}
{"id":12345,"firstName":"Joel Babu","lastName":"Chelli","hobbies":[null]}
{"create" : {"_index": "college", "_type": "student", "_id": "3" }}
{"id":765,"firstName":"PTR","lastName":"sailaja"}
{"create" : {"_index": "college", "_type": "student", "_id": "4" }}
{"id":75,"firstName":"Rama Krishna","lastName":"Gurram","hobbies":["climbing hills", null]}

1.Get all the documents where there is a field hobbies

GET /college/student/_search
{
  "query": {
    "filtered": {
      "filter": {
        "exists": {
          "field": "hobbies"
        }
      }
    }
  }
}
Above query return following response.

{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 1,
      "hits": [
         {
            "_index": "college",
            "_type": "student",
            "_id": "4",
            "_score": 1,
            "_source": {
               "id": 75,
               "firstName": "Rama Krishna",
               "lastName": "Gurram",
               "hobbies": [
                  "climbing hills",
                  null
               ]
            }
         },
         {
            "_index": "college",
            "_type": "student",
            "_id": "1",
            "_score": 1,
            "_source": {
               "id": 358,
               "firstName": "Hari Krishna",
               "lastName": "Gurram",
               "hobbies": [
                  "visiting places",
                  "watching movies",
                  "chat with friends"
               ]
            }
         }
      ]
   }
}
As you observe results document with id’s 12345 and 765 are not returned. Since document 12345 contains has hobbies field as null.
{"id":12345,"firstName":"Joel Babu","lastName":"Chelli","hobbies":[null]}

Document 765 don’t contain hobbies field. 
{"id":765,"firstName":"PTR","lastName":"sailaja"}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment