es_man
es_man

Reputation: 41

Elasticsearch - Querying nested objects

I'm storing objects in elasticsearch like this

{
  "user":{
           "name":"Johnson",
           "age":24
          }
}

Please note that I do not have a default mapping set in elasticsearch. I'm simply inserting the data directly.

Now, While using "nested query" to try to query the data.

GET user_index/user_document/_search
{

  "query":{
        "nested" : {
            "path" : "user",
            "score_mode" : "avg",
            "query" : {
                "bool" : {
                    "must" : [
                        {
                            "match" : {"user.name" : "Johnson"}
                        }
                    ]
                }
            }
        }
    }
}

This fails and i get an error

nested object under path [user] is not of nested type

My Questions are

  1. Should i create a default mapping for querying nested objects?
  2. Why can't a query like this below (which works) be used instead?

    GET user_index/_search
     {
    
        "query":{
    
            "match":{
    
                  "user.name":"Johnson"
    
                     }
    
                } 
    
    }
    

Upvotes: 4

Views: 280

Answers (1)

jhilden
jhilden

Reputation: 12429

Should i create a default mapping for querying nested objects?

No. Nested objects in ES are used when you are going to be putting many objects into the array and need to query them separately. As a general rule, don't create nested objects until you find that you really need them. They bite you more then they help you in most cases.

Why can't a query like this below (which works) be used instead?

  1. ES lowercases everything for searchability.
  2. You should also use a "term" query when querying the whole value.

Here is a sample for you:

PUT test

POST test/index1
{
  "user":{
           "name":"Johnson",
           "age":24
          }
}

GET test/index1/_search
{
  "query": {
    "term": {
      "user.name": {
        "value": "johnson"
      }
    }
  }
}

Upvotes: 1

Related Questions