如何使用弹性搜索将 "in list" 运算符与 Nest (C#) 库一起应用?

How to apply "in list" operator with Nest (C#) library using the elastic search?

我有一个 ElasticSearch server that I want to query. I want to replicate the behavior of in operator in a SQL server using the NEST 图书馆。

这是 Product class 的简短版本,我用它来搜索 Type 字段在 request.Types

中的位置
public class Product
{
    [Text(Name = "types")]
    public string[] Types { get; set; }

    [Text(Name = "price")]
    public double Price { get; set; }

    // ...
}

这是我使用 Nest 库的查询请求

var properties = await client.SearchAsync<Product>(x =>
{
    x = x.Query(q =>
    {
        if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
        {
            q.Range(r =>
           {
               if (request.MinPrice.HasValue)
               {
                   r = r.Field(x => x.Price).GreaterThanOrEquals((double)request.MinPrice.Value);
               }

               if (request.MaxPrice.HasValue)
               {
                   r = r.Field(x => x.Price).LessThanOrEquals((double)request.MaxPrice.Value);
               }
               return r;
           });
        }

        if (request.Types != null && request.Types.Length > 0)
        {
            
            // Here I need to query the Type field where field in request.Types
        }

        return q;
    });

    return x;
});

正如您在上面的评论中看到的,我只想在 request.Types 具有值且服务器至少具有一种匹配类型时添加“in 子句”。

如何添加in clause条件?

我可以看到对要求的两种可能解释:

  1. 查询 Typesrequest.Types

    相交的文档

    一个terms query就可以做到这一点。通常,术语查询以映射为 keyword 类型的字段为目标,但 Product.Types 映射为 text 类型。您可能需要考虑将映射更改为映射为 keyword,或者将其映射为具有多字段的 textkeyword

    Product.Types 映射为 keyword 类型,查询将是

    q.Terms(t => t
        .Field(f => f.Types)
        .Terms(request.Types)
    );
    
  2. 查询具有 request.Types

    中指定的所有确切 Types 的文档

    一个terms set query就可以做到这一点。和以前一样,Types 字段应该映射为 keyword,那么查询将是

    q.TermsSet(t => t
        .Field(f => f.Types)
        .Terms(request.Types)
        .MinimumShouldMatchScript(s => s
           .Source("params.request_types_len")
           .Params(d => d
               .Add("request_types_len", request.Types.Length)
           )
        )
    );