除了一个字段外,MostFields multi_match模糊

时间:2018-04-05 17:31:06

标签: nest elasticsearch-6

我有一些不同的字段映射。我有一个是拼音的字段。我想用模糊的方式进行查询,但不要在语音场上使用模糊性。

...
_client.Search<JobModelSummary>(s => s
  .Index(indexName)
  .Query(q => q
    .MultiMatch(m => m
      .Query(paginationQuery.Search)
      .Type(TextQueryType.MostFields)
      .Fuzziness(Fuzziness.EditDistance(1))
      .Fields(f => f
        .Field(ff => ff.Name.Suffix("standard"), 3)
        .Field(ff => ff.Name.Suffix("edge-ngram"), 2)
        .Field(ff => ff.Name.Suffix("phonetic"))  // <--- Don't want this fuzzy
))));

文档很少,我发现很难和平相处如何做到这一点。

1 个答案:

答案 0 :(得分:1)

如果您正在执行如上所述的大多数字段multi_match查询,则可以通过将多个匹配查询组合在一起来实现您的目标

var indexName = "foo";
var search = "search";

var searchResponse client.Search<JobModelSummary>(s => s
    .Index(indexName)
    .Query(q => q
        .Bool(b => b
            .Should(sh => sh
                .Match(m => m
                    .Query(search)
                    .Fuzziness(Fuzziness.EditDistance(1))
                    .Field(ff => ff.Name.Suffix("standard"))
                    .Boost(3)
                ), sh => sh
                .Match(m => m
                    .Query(search)
                    .Fuzziness(Fuzziness.EditDistance(1))
                    .Field(ff => ff.Name.Suffix("edge-ngram"))
                    .Boost(2)
                ), sh => sh
                .Match(m => m
                    .Query(search)
                    .Field(ff => ff.Name.Suffix("phonetic"))
                )
            )
        )   
    )
);

使用查询的重载运算符可以稍微简洁一些

client.Search<JobModelSummary>(s => s
    .Index(indexName)
    .Query(q => q
        .Match(m => m
            .Query(search)
            .Fuzziness(Fuzziness.EditDistance(1))
            .Field(ff => ff.Name.Suffix("standard"))
            .Boost(3)
        ) || q
        .Match(m => m
             .Query(search)
             .Fuzziness(Fuzziness.EditDistance(1))
             .Field(ff => ff.Name.Suffix("edge-ngram"))
             .Boost(2)
        ) || q
        .Match(m => m
             .Query(search)
             .Field(ff => ff.Name.Suffix("phonetic"))
        )
    )
);

两者都产生

POST http://localhost:9200/foo/jobmodelsummary/_search 
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name.standard": {
              "boost": 3.0,
              "query": "search",
              "fuzziness": 1
            }
          }
        },
        {
          "match": {
            "name.edge-ngram": {
              "boost": 2.0,
              "query": "search",
              "fuzziness": 1
            }
          }
        },
        {
          "match": {
            "name.phonetic": {
              "query": "search"
            }
          }
        }
      ]
    }
  }
}

将在should子句中将每个查询的分数相加,以便为每个文档提供最终_score。如果仅指定了should子句,则至少必须匹配一个文档才能被视为匹配。