NEST有多个条件的条件过滤器查询 [英] NEST Conditional filter query with multiple terms
问题描述
我想像这样做一个ElasticSearch查询:
I would like to do a ElasticSearch query like this:
{
"query" :
{
"bool" :
{
"filter" : [
{
"terms" :
{
"name" : ["name1", "name2"]
}
},
{
"terms" :
{
"color" : ["orange", "red"]
}
}
]
}
}
}
我试图像这样在NEST中实现它:
I've tried to implement it in NEST like this:
_elasticClient
.SearchAsync<MyDocument>(s =>
s.Index("myindex")
.Query(q => q
.Bool(bq => bq
.Filter(fq =>
{
QueryContainer query = null;
if (nameList.Any()) {
query &= fq.Terms(t => t.Field(f => f.Name).Terms(nameList));
}
if (colorList.Any()) {
query &= fq.Terms(t => t.Field(f => f.Color).Terms(colorList));
}
return query;
})
)
)
);
但是,这给了我这样的查询,其中过滤器包装在布尔型中:
But that gives me a query like this where the filters are wrapped inside a bool must:
{
"query" :
{
"bool" :
{
"filter" : [
{
"bool" :
{
"must" : [
{
"terms" :
{
"name" : ["name1", "name2"]
}
},
{
"terms" :
{
"color" : ["orange", "red"]
}
}
]
}
}
]
}
}
}
如何更改我的NEST代码以提供正确的查询?是否必须将我的条款添加到除 QueryContainer 之外的其他内容上?
How should I change my NEST code to give me the right query? Do have have to add my terms to something other then a QueryContainer?
推荐答案
如果要检查条件过滤器,则可以在查询之前创建过滤器列表,如下所示:
You can create a list of filters before you make a query if you want to check conditional filters as shown below:
var nameList = new[] {"a", "b"};
var colorList = new[] {1, 2};
var filters = new List<Func<QueryContainerDescriptor<MyDocument>, QueryContainer>>();
if (nameList.Any())
{
filters.Add(fq=> fq.Terms(t => t.Field(f => f.Name).Terms(nameList)));
}
if (colorList.Any())
{
filters.Add(fq => fq.Terms(t => t.Field(f => f.Color).Terms(colorList)));
}
ISearchResponse<Property> searchResponse =
elasticClient.Search<MyDocument>(x => x.Query(q => q
.Bool(bq => bq.Filter(filters))));
如果在进行过滤器查询之前不需要检查任何条件,那么您可以得到类似的内容:
If you don't need to check any condition before making filter query then you can have something like that:
ISearchResponse<MyDocument> searchResponse =
elasticClient.Search<MyDocument>(x => x.Query(q => q
.Bool(bq => bq
.Filter(
fq => fq.Terms(t => t.Field(f => f.Name).Terms(nameList)),
fq => fq.Terms(t => t.Field(f => f.Color).Terms(colorList))
))));
这篇关于NEST有多个条件的条件过滤器查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!