如何通过JSON中的嵌套字段进行搜索

时间:2017-08-23 14:05:17

标签: json elasticsearch

我的文件看起来像:

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

我想搜索字段10.value的值与*some*类似的所有文档:

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

但是得到错误:

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

为什么呢?我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要在映射中将字段10的类型明确设置为nested

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