【问题标题】:Elasticsearch Nest query bool filter with multiple must clauses具有多个必须子句的 Elasticsearch Nest 查询布尔过滤器
【发布时间】:2016-07-24 20:12:18
【问题描述】:

我有这个 elasticsearch 查询,它以原始格式完美运行,但我无法将其转换为 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"
         }
     }

【问题讨论】:

  • must 查询的bool 子句是一个数组;我怀疑第二个must 子句属性最终会覆盖第一个。您使用的是哪个版本的 NEST?
  • 我使用的是最新版本。 2.3.x 我认为是。

标签: c# elasticsearch nest


【解决方案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 的优势,允许它们被&amp;&amp; 编辑在一起以形成带有must 子句的bool 查询。

【讨论】:

  • 该代码不会运行。它似乎无法运行术语 f => f.Ingredients,因为它找不到成分。
  • 该示例假设您有一个名为 Recipe 的 POCO 类型,其属性名为 Ingredients。您需要根据您的模型进行相应调整
  • 找出你的意思。谢谢您的帮助。效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多