以下代码有两个BoolQueryDescriptor类型的变量。各个变量有各自不同的Must,MustNot,Filter部分。
有没有办法将每个变量中的所有相应的Must(s),Filters,MustNot(s)组合成BoolQueryDescriptor变量并提供给最终查询或Boolquery。
BoolQueryDescriptor<Requote> queryParameter = null;
BoolQueryDescriptor<Requote> queryParameterMultiple = null;
queryParameter = QueryFilterBuilder.BuildQueryFilter<Requote>(group);
queryParameterMultiple = QueryFilterBuilder.BuildQueryFilterForMultipleInputValues<Requote>(group);
Var searchResult = elasticClient.Search<Requote>(query => query.Query(q => q.Bool(b => queryParameter)).Index(IndexConstants.Requote).Size(searchInputs.ResultCount).From(searchInputs.From).Sort(s => s.Field(sortField, sortOrder)));
答案 0 :(得分:2)
由于BoolQueryDescriptor<T>
明确实现了IBoolQuery
,您可以将每个描述符转换为IBoolQuery
并将这些子句合并为一个新的BoolQueryDescriptor<T>
public static BoolQueryDescriptor<T> CombineBoolQueryDescriptors<T>(params BoolQueryDescriptor<T>[] queries) where T : class
{
var descriptor = new BoolQueryDescriptor<T>();
var combinedQuery = (IBoolQuery)descriptor;
foreach (var query in queries.Cast<IBoolQuery>())
{
if (query.Must != null)
{
combinedQuery.Must = combinedQuery.Must != null
? combinedQuery.Must.Concat(query.Must)
: (query.Must.ToArray());
}
if (query.Should != null)
{
combinedQuery.Should = combinedQuery.Should != null
? combinedQuery.Should.Concat(query.Should)
: (query.Should.ToArray());
}
if (query.MustNot != null)
{
combinedQuery.MustNot = combinedQuery.MustNot != null
? combinedQuery.MustNot.Concat(query.MustNot)
: (query.MustNot.ToArray());
}
if (query.Filter != null)
{
combinedQuery.Filter = combinedQuery.Filter != null
? combinedQuery.Filter.Concat(query.Filter)
: (query.Filter.ToArray());
}
}
return descriptor;
}
您需要决定如何将其他属性(如.Boost()
,.MinimumMustMatch()
,Strict()
,.Verbatim()
等应用于新的合并{{1} } query。
一个例子
bool
产量
var bool1 = new BoolQueryDescriptor<Document>()
.Must(
m => m.Term("field", "value"),
m => m.Match(match => match.Query("query").Field("field"))
);
var bool2 = new BoolQueryDescriptor<Document>()
.Must(
m => m.Term("field1", "value1"),
m => m.Match(match => match.Query("query1").Field("field1"))
);
var combined = CombineBoolQueryDescriptors(bool1, bool2);
client.Search<Document>(s => s.Query(q => q.Bool(b => combined)));