简体   繁体   English

如何在具有数组字段的弹性搜索中进行搜索?

[英]How to search in elastic search having an array field?

My indexed elastic search documents contains a field which is an array.我的索引弹性搜索文档包含一个数组字段。 For example featuers of a car.例如汽车的特征。

{
"features": [ "Anti-Lock Brakes",
              "Alarm", 
              "Air Bag Driver",
              "Cruise Control", 
              "Satellite Navigation"'
}

How can I search for documents with which includes values from a given array.如何搜索包含给定数组中的值的文档。 For example: I want to checkout cars which contain features such as 'Satellite navigation' and 'Cruise control'.例如:我想检查包含“卫星导航”和“巡航控制”等功能的汽车。

I tried the following but it is not working (php code)我尝试了以下但它不工作(php代码)

public function index(Request $request, Client $search, SerializerInterface $serializer): JsonResponse
   ...

    $search_query = ["Satellite Navigation", "Cruise Control"]
  
    $filters = [];
    $filters[] = [
                   'terms' => [
                       'features' => $search_query,
                   ]
               ];

    $results = $search->search([
               'index' => 'cars',
               'body' => [
                   'from' => $offset,
                   'size' => self::PAGE_WINDOW,
                   'query' => [
                       "bool" => [
                           "must" => [
                               "match_all" => new \stdClass()
                           ],
                           "filter" => $filters
                       ]
                   ]
               ]
           ]);
...

I would like get a hint on how to set the $filters so that I get the desired results.我想获得有关如何设置 $filters 的提示,以便获得所需的结果。

Since you do not have the mapping for features and you are adding index data, so a default mapping is generated.由于您没有features映射并且您正在添加索引数据,因此会生成默认映射。

Try this below search query, this will return all the documents that contain features such as 'Satellite navigation' and 'Cruise control'试试下面的搜索查询,这将返回所有包含'Satellite navigation''Cruise control'features的文档

Search Query:搜索查询:

{
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "features": "Satellite Navigation"
          }
        },
        {
          "match_phrase": {
            "features": "Cruise Control"
          }
        }
      ]
    }
  }
}

Search Result:搜索结果:

"hits": [
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.7178956,
        "_source": {
          "features": [
            "Anti-Lock Brakes",
            "Alarm",
            "Air Bag Driver",
            "Cruise Control",
            "Satellite Navigation"
          ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM