Elasticsearch:在数组中搜索

时间:2014-09-26 06:26:20

标签: elasticsearch

我在elasticsearch player index中有以下对象。

GET /players/_search

"hits": [
     {
        "_index": "players",
        "_type": "1",
        "_id": "rRI5A8mVRUKKTA08bK90Vw",
        "_score": 0.2712221,
        "_source": {
           "id": "1",
           "first_name": "Lebron",
           "last_name": "James",
           "numbers": [
              {
                 "number": "23",
                 "team": {
                    "city": "Cliveland",
                    "name": "Cavaliers"
                 }
              },
              {
                 "number": "6",
                 "team": {
                    "city": "Maimi",
                    "name": "Heat"
                 }
              }
           ]
        }
     }
  ]

现在我想搜索玩“maimi”并且号码为“23”的玩家(此索引中没有这样的玩家)。我试过了

GET /players/_search
{
    "query": { 
        "bool" : {
            "must" : [
                {
                    "term" : {
                        "numbers.number" : "23"
                    }
                },
                {   "term" : {
                        "numbers.team.city" : "maimi" 
                    }
                }
            ]
        }
    }
}

但是弹性研究仍然找到了勒布朗。我该如何对elasticsearch做出正确的请求?

1 个答案:

答案 0 :(得分:2)

这是因为您的数据结构及其编制方式:arrays inner objects在内部被展平。

实际上,您的文档在ElasticSearch中编入索引,如下所示:

numbers.number:     [23,6]
numbers.team.city:  [Cliveland,Maimi]
numbers.team.name:  [Cavaliers,Heat]

虽然内部物体之间的关联已经丢失,但搜索Cliveland Heat数字6也会与本文档相符。

您应该使用nested对象映射来解决此问题:内部对象将保持原样。