使用 NEST 库查询 ElasticSearch 服务器时如何应用多个条件?

How to apply multiple conditions when querying the ElasticSearch server using NEST library?

我有一个ElasticSearch server that I want to query using the C# NEST library

这是我要生成的命令

GET /records/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "available": true
          }
        },
        {
          "match": {
            "out_scope": false
          }
        }
      ]
    }
  }
}

这是我所做的,我似乎找不到指定字段名称和要搜索的值的正确方法。

var products = await client.SearchAsync<Product>(x => 
                    x.Query(q => 
                        q.Bool(b => 
                            b.Should(bs1 => 
                                bs1.Match(bsm => 
                                    bsm.Field(fff => fff.IsAvailable)
                                       .Term(isAvailable.Value) // This does not work!
                                       ),
                                bs2 =>
                                bs2.Match(bsm =>
                                    bsm.Field(fff => fff.IsAvailable)
                                       .Term(isAvailable.Value) // This does not work!
                                       )
                                )
                            );

如何正确指定要匹配的字段名称和值?

假设模型像

public class Product
{
    [Keyword(Name = "available")]
    public bool? IsAvailable { get; set; }
    
    [Keyword(Name = "out_scope")]
    public bool? OutScope { get; set; }
}

那就是

    var searchResponse = await client.SearchAsync<Product>(x => x
        .Query(q =>
            q.Bool(b =>
                b.Should(bs1 =>
                    bs1.Match(bsm =>
                        bsm.Field(fff => fff.IsAvailable)
                           .Query(isAvailable.Value ? "true" : "false")
                           ),
                    bs2 =>
                    bs2.Match(bsm =>
                        bsm.Field(fff => fff.OutScope)
                           .Query(isAvailable.Value ? "true" : "false")
                        )
                    )
                )
            )
        );

需要考虑的一些事项:

  1. match query 的查询输入是 .Query field/method。显示的 JSON DSL 示例使用缩写形式来表达查询; NEST 始终生成长格式。
  2. 匹配查询的查询输入最终在 Elasticsearch 中被强制转换为字符串。客户端将其作为字符串参数公开。
  3. A term query 看起来它可能是一个更好的查询用于这个例子;术语查询不像匹配查询那样进行分析。像term query这样的term级别的查询适合结构化搜索。
  4. NEST 在查询上重载运算符,使编写 bool 查询更加简洁。上面也可以写成
var searchResponse = client.Search<Product>(x => x
    .Query(q => q
        .Match(bsm => bsm
            .Field(fff => fff.IsAvailable)
                .Query(isAvailable.Value ? "true" : "false")
            ) || q
        .Match(bsm => bsm
            .Field(fff => fff.OutScope)
            .Query(isAvailable.Value ? "true" : "false")
        )
    )
);