Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elastic exists query for nested documents

I have a nested documents as:

"someField": "hello", "users": [    {      "name": "John",       "surname": "Doe",       "age": 2    } ] 

according to this https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html, the above should match:

GET /_search {   "query": {     "exists" : { "field" : "users" }   } 

}

whereas the following should not,

"someField": "hello", "users": [] 

but unfortunately both do not match. any ideas?

like image 321
rethabile Avatar asked Jan 05 '17 18:01

rethabile


People also ask

How do you write nested query in Elasticsearch?

You can perform a nested query in Elasticsearch by using the nested parameter. A nested query will search the nested field objects and return the document's root parent if there's a matching object.

What is nested in Elasticsearch?

The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.

What is a nested field?

When a packed class contains an instance field that is a packed type, the data for that field is packed directly into the containing class. The field is known as a nested field . When reading from a nested field, a small object is created as a pointer to the data.

What is nested datatype?

Nested data types are structured data types for some common data patterns. Nested data types support structs, arrays, and maps. A struct is similar to a relational table. It groups object properties together.


2 Answers

The example mentioned on the Elasticsearch blog refers to string and array of string types, not for nested types.

The following query should work for you:

{     "query": {         "nested": {             "path": "users",             "query": {                 "bool": {                     "must": [                         {                             "exists": {                                 "field": "users"                             }                         }                     ]                 }             }         }     } } 

Also, you can refer to this issue for more info, which discusses this usage pattern.

like image 176
user3775217 Avatar answered Sep 26 '22 08:09

user3775217


This works for me

GET /type/_search?pretty=true {   "query": {     "bool": {       "must": [         {           "nested": {             "path": "outcome",             "query": {               "exists": {                 "field": "outcome.outcomeName"               }             }           }         }       ]     }   } } 
like image 39
manu prasanth Avatar answered Sep 24 '22 08:09

manu prasanth