4

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"
    
                     }
    
                } 
    
    }
    

1 Answer 1

1

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"
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, why did the nested query fail in OP's question?
Presumably because there was no explicit "nested" mapping created. You always need to do that manually, ES will never infer it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.