Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search query to retrieve nested documents in elasticsearch with _source disabled

I have the following mapping

{
    "cloth": {
                 "dynamic" : false,
                 "_source" : {"enabled" : false },
        "properties": {
            "name": {
                "type": "string",
                "index": "analyzed"
            },
            "variation": {
                "type": "nested",
                "properties": {
                    "size": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "color": {
                        "type": "string",
                        "index": "not_analyzed"
                    }
                }
            }
        }
    }
}

I am not able to figure out a way to retrieve the nested object fields using the fields query.

{
    "fields" : ["name" , "variation.size", "variation.color"],
    "query" : {
        "nested" : {
            "path" : "variation",
            "query" : {
                "bool" : {
                    "must" : [
                        { "term" : { "variation.size" : "XXL" } },
                        { "term" : { "variation.color" : "red" } }
                        ]
                }
            }
        }
    }
}

The above query returns

"_id" : "1",
  "_score" : 1.987628,
  "fields" : {
    "variation.size" : [ "XXL", "XL" ],
    "variation.color" : [ "red", "black" ],
    "name" : [ "Test shirt" ]
  }

When I tried

"fields" : ["name" , "variation"]

I got the error

status: 400

reason: "ElasticsearchIllegalArgumentException[field [variation] isn't a leaf field]"

Which is as expected.

How can I get the variation object as it is?

Expected Result. I need to retrieve the variable object as a whole so that I can preserve the association of size and color. Like "red" with "XXL".

"variation" : { "XXL" , "red"}

Update: Source is disabled for this Index Type.

like image 587
user1760178 Avatar asked Oct 03 '14 15:10

user1760178


1 Answers

If you use Source Filtering it will return the nested objects as a whole, your query would be:

{
  "_source": [
    "name",
    "variation"
  ],
  "query": {
    "nested": {
      "path": "variation",
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "variation.size": "XXL"
              }
            },
            {
              "term": {
                "variation.color": "red"
              }
            }
          ]
        }
      }
    }
  }
}
like image 198
Dan Tuffery Avatar answered Oct 09 '22 19:10

Dan Tuffery