如果匹配条件或其他条件,我想在过滤器中执行一个带有结果的应该。
在弹性搜索中,它将是:
POST /my_index/_search
{
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{
"match": {
"type1_title": "searched match"
}
},
{
"match": {
"type2_title": "searched match"
}
}
]
}
}
]
}
}
}
我试图在nest中的另一个boolQuery中输入en boolQuery:
var shouldForFilter = new List<QueryContainer>();
shouldForFilter.Add(new TermQuery()
{
Field = "type1Title", Value = "searched match",
});
shouldForFilter.Add(new TermQuery()
{
Field = "type2Title", Value = "searched match",
});
var shouldContainer = new List<QueryContainer> {
....
}
...
var innerFilterQuery = new BoolQuery
{
Should = shouldForFilter
};
var searchQuery = new BoolQuery
{
Filter = innerFilterQuery, //does not work
Should = shouldContainer,
Must = mustContainer,
From = 10,
Size = 20
Minscore = 1
};
显然类型不匹配。
你知道怎么做吗?
答案 0 :(得分:2)
在NEST中运算符重载时,可以非常简洁地表达
client.Search<MyDocument>(s => s
.Query(q => +(q
.Match(m => m
.Field("type1Title")
.Query("searched match")
) || q
.Match(m => m
.Field("type2Title")
.Query("searched match")
))
)
);
产生
{
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{
"match": {
"type1Title": {
"query": "searched match"
}
}
},
{
"match": {
"type2Title": {
"query": "searched match"
}
}
}
]
}
}
]
}
}
}
您还可以使用Object Initializer语法进行运算符重载,这可能比包装bool
查询更简洁。重要的是以正确的顺序应用操作。此示例生成与上面相同的查询
QueryContainer query = new MatchQuery
{
Field = "type1Title",
Query = "searched match"
};
// use binary || operator to wrap combined queries
// into bool query should clause
query |= new MatchQuery
{
Field = "type2Title",
Query = "searched match"
};
// use unary operator to wrap query in bool
// query filter clause
query = +query;
var request = new SearchRequest<MyDocument>
{
Query = query
};
client.Search<MyDocument>(request);