demas demas - 27 days ago 7
JSON Question

How can I search by nested fields in JSON

I have documents which looks like:

λ curl -XGET -u elastic:elasticpassword 192.168.1.71:9200/mytweets/ex3/_search?pretty -H "Content-Type: application/json" -d'{"query":{"match_all":{}}}'
{
"took" : 4,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_index" : "mytweets",
"_type" : "ex3",
"_id" : "AV4PXt6Be-9TCGhLorhI",
"_score" : 1.0,
"_source" : {
"10" : {
"id" : 10,
"name" : "f1",
"value" : "some_v"
},
"20" : {
"id" : 20,
"name" : "f2",
"value" : "some_val"
}
}
}
]
}
}


I want to search all documents where the value for field
10.value
is like
*some*
:

{
"query": {
"nested": {
"path": "10",
"query": {
"wildcard": {
"value": "*some*"
}
}
}
}
}


But get the error:

λ curl -XGET -u elastic:elasticpassword 192.168.1.71:9200/mytweets/ex3/_search -H "Content-Type: application/json" -d'{ "query": { "nested": { "path": "10", "query": { "wildcard": { "value": "*some*" }}}}}'
{"error":{"root_cause":[{"type":"query_shard_exception","reason":"failed to create query: {\n \"nested\" : {\n \"query\" : {\n \"wildcard\" : {\n \"value\" : {\n \"wildcard\" : \"*some*\",\n \"boost\" : 1.0\n }\n }\n },\n \"path\" : \"10\",\n \"ignore_unmapped\" : false,\n \"score_mode\" : \"avg\",\n \"boost\" : 1.0\n }\n}","index_uuid":"OGa3zCZoQ3GjAGdpIXiIfw","index":"mytweets"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"mytweets","node":"d6mbNtxERmuOnAN7YYvumg","reason":{"type":"query_shard_exception","reason":"failed to create query: {\n \"nested\" : {\n \"query\" : {\n \"wildcard\" : {\n \"value\" : {\n \"wildcard\" : \"*some*\",\n \"boost\" : 1.0\n }\n }\n },\n \"path\" : \"10\",\n \"ignore_unmapped\" : false,\n \"score_mode\" : \"avg\",\n \"boost\" : 1.0\n }\n}","index_uuid":"OGa3zCZoQ3GjAGdpIXiIfw","index":"mytweets","caused_by":{"type":"illegal_state_exception","reason":"[nested] nested object under path [10] is not of nested type"}}}]},"status":400}


Why? And how can I fix it ?

Answer Source

You need to explicitly set the type for field 10 to nested in mappings.

PUT mytweets
{
  "mappings": {
    "ex3": {
      "properties": {
        "10": {
          "type": "nested" 
        }
      }
    }
  }
}