Elasticsearch两个多重匹配查询

时间:2019-09-17 12:04:24

标签: elasticsearch elasticsearch-rails

我尝试搜索三个字段namename.ngrammodel_number。我提高了name,因此name上的任何比赛都比name.ngram高。但是,在某些情况下,name.ngram与包含奇怪标点符号的词不匹配,因此我想通过对namemodel_number字段进行模糊搜索来完成查询。

这是我最终想要的查询。如果删除第二个multi_match,则查询有效,但不包含模糊搜索。

{
         explain: true,
         query:{
           function_score: { 
              "query": {
                "bool": {
                  "should": 
                    {
                      multi_match:{
                         fields: ["name^10", "name.ngram", "model_number"],
                         type: "most_fields",
                         query: "#{query}"
                       },
                       multi_match:{
                           fields: ["name", "model_number"],
                           type: "most_fields",
                           query: "#{query}",
                           fuzziness: "2"
                        }
                    },
                  "filter": {
                    "bool": { 
                      "must": filters
                    }
                  }
               }
             },field_value_factor:{
                    field: "popularity",
                    modifier: "log1p",
                    factor: 5

                 },
                 boost_mode: "sum"
             }
       },highlight: {
            fields: {
              :"*" => {}
            }
          },
        aggs: {categories: { terms: { field: "category.raw"} }} 

      } 

我想像对待ngram一样最终对待模糊搜索,以便非模糊匹配排名第一,模糊匹配排名第二。如何添加第二个multi_match查询,以实现此目的?

1 个答案:

答案 0 :(得分:0)

您的bool/should子句格式不正确,它应该是一个包含两个元素的数组,每个multi_match约束一个,如下所示:

  ...
  "should": [
    {
      "multi_match": {
        "fields": [
          "name^10",
          "name.ngram",
          "model_number"
        ],
        "type": "most_fields",
        "query": "#{query}"
      }
    },
    {
      "multi_match": {
        "fields": [
          "name",
          "model_number"
        ],
        "type": "most_fields",
        "query": "#{query}",
        "fuzziness": "2"
      }
    }
  ]
  ...