Elasticsearch Nest查询bool过滤器,包含多个必须子句

时间:2016-07-22 11:31:35

标签: c# elasticsearch nest

我有这个弹性搜索查询,它在原始格式中运行良好,我无法将其转换为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"
         }
     }

1 个答案:

答案 0 :(得分:1)

这样的东西会起作用

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"
                }
              }
            }
          ]
        }
      }
    }
  }
}

利用operator overloading for QueryContainer允许他们&&一起编辑bool mustAndroidManifest.xml个句子。

相关问题