如何在弹性搜索中查询数组元素

时间:2016-11-16 04:41:54

标签: ruby-on-rails elasticsearch elasticsearch-rails

这是弹性搜索中我的模型的索引

 {  
       "_index":"cars",
       "_type":"car",
       "_id":"3275",
       "_version":4,
       "_score":1,
       "_source":{  
         "category_id": 6,
          "car_branches":[  
             {  
                "id":32,
                "name":"Type1"
             },
             {  
                "id":33,
                "name":"Type2"
             },
             {  
                "id":36,
                "name":"Type3"
             }
          ],

       }
    }

我可以用

查询category_id

Car.__elasticsearch__.search query:{match:{category_id: 6}}

如何查询car_branches?我试过这个

response = Car.__elasticsearch__.search query:{match:{car_branches:[id: 32]}}

我正在Elasticsearch::Transport::Transport::Errors::BadRequest: [400]

1 个答案:

答案 0 :(得分:0)

首先需要删除索引并重新创建它。在此之前,您需要更改映射并制作car_branches字段nested,如下所示:

  indexes :car_branches, type: 'nested' do
      indexes :id
      indexes :name

然后,您就可以按照以下方式进行查询:

response = Car.__elasticsearch__.search query:{nested:{path: 'car_branches', query:{term:{'car_branches.id':[32]}}}}