Elasticsearch Nest查询布尔筛选器包含多个必须子句

本文关键字:子句 包含多 Nest 查询 布尔 筛选 Elasticsearch | 更新日期: 2023-09-27 17:58:16

我有一个弹性搜索查询,它在原始格式中运行得很好,但我很难将其转换为C#NEST子句。

这是原始查询:

{  
"query":{  
      "constant_score":{  
         "filter":{  
            "bool":{  
               "must":{  
                  "term":{  
                     "ingredients":"baking"
                  }
               },
               "must":{  
                  "term":{  
                     "ingredients":"soda"
                  }
               }
            }
         }
      }
   }
}

这就是我认为在C#NEST:中会起作用的地方

public List<Recipe> FindByMultipleValues(string field, string[] values) {
        List<string> vals = values.ToList();
        return client.Search<Recipe>(s => s
            .Query(q => q
                .Bool(fq => fq
                    .Filter(f => f
                        .Term(rec => rec.Ingredients, vals)
                    )
                )
            )
        ).Documents.ToList();
    }

用户可以发送一个x值的数组,这意味着每个值都必须有一个:

"must":{  
    "term":{  
        "ingredients":"soda"
         }
     }

Elasticsearch Nest查询布尔筛选器包含多个必须子句

这样的东西可以在中工作

var terms = new[] { "baking", "soda" };
client.Search<Recipe>(s => s
    .Query(q => q
        .ConstantScore(cs => cs
            .Filter(csf => 
            {
                var firstTerm = csf.Term(f => f.Ingredients, terms.First());        
                return terms.Skip(1).Aggregate(firstTerm, (query, term) => query && csf.Term(f => f.Ingredients, term));
            })
        )
    )
);

将产生

{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "ingredients": {
                  "value": "baking"
                }
              }
            },
            {
              "term": {
                "ingredients": {
                  "value": "soda"
                }
              }
            }
          ]
        }
      }
    }
  }
}

这利用了QueryContainer的运算符重载,使它们能够被&&’组合在一起,形成具有must子句的bool查询。