我想用 NEST 附加多个 bool 过滤器,但我不能(实际上)在一个语句中完成它,因为我想根据不同的条件构建一组 Bool 过滤器.
像这样的伪代码:
// Append a filter
searchDescriptor.Filter(f => f.Bool(b => b.Must(m => m.Term(i => i.SomeProperty, "SomeValue"))));
if (UserId.HasValue)
{
// Optionally append another filter (AND condition with the first filter)
searchDescriptor.Filter(f => f.Bool(b => b.Must(m => m.Term(i => i.AnotherProperty, "MyOtherValue"))));
}
var result = Client.Search(searchDescriptor);
现在看来,当附加第二个可选过滤器时,它实际上取代了第一个过滤器。
我确定我在语法上遗漏了一些东西,但我无法弄清楚,而且 NEST 文档在过滤器 DSL 上有点薄。 :)
最佳答案
关于编写查询的部分几乎也适用于过滤器: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/writing-queries.html
你最终得到的解决方案不太理想,因为你将 bool
过滤器包装在 and
过滤器中,它们具有非常不同的缓存机制(并且过滤器不使用缓存的位集,因此在大多数情况下比常规 bool 过滤器表现更差。
强烈推荐阅读http://www.elastic.co/blog/all-about-elasticsearch-filter-bitsets/因为它很好地解释了 and/or/not 过滤器与 bool 过滤器之间的区别。
您实际上可以这样重写:
Client.Search(s=>s
.Filter(f=> {
BaseFilter ff = f.Term(i => i.MyProperty, "SomeValue");
if (UserId.HasValue)
ff &= f.Term(i => i.AnotherProperty, "AnotherValue");
return ff;
})
);
如果第二个词使用 UserId 进行搜索,您可以利用 NEST 的无条件查询
Client.Search(s=>s
.Filter(f=>
f.Term(i => i.MyProperty, "SomeValue")
&& f.Term(i => i.AnotherProperty, UserId)
)
);
如果 UserId
为空,则词条查询将不会作为查询的一部分生成,在这种情况下,nest 甚至不会将剩余的单个词条包装在 bool 过滤器中,而只是将其发送作为普通术语过滤器。
关于elasticsearch - 将多个 bool 过滤器附加到 NEST 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19640519/