我正在使用Nest来查询Elasticsearch,我已经为我的搜索编写了这个查询:
var searchResponse = _elasticClient.Search<AdDocument>(s => s
.Query(q => q
.Bool(b => b
.Must(m => m
.MultiMatch(mm => mm
.Fields(f => f.Field(p => p.Title, 1.5).Field(p => p.Description))
.Query("MyKeyword")
.Fuzziness(Fuzziness.Auto)
)
)
.Filter(fi => fi
.Bool(fb => fb
.Must(m => m.Range(r => r.Field(f => f.NoOfBedrooms == 3)),
m => m.Range(r => r.Field(f => f.NoOfBathrooms == 2)),
m => m.Range(r => r.Field(f => f.Price > 2000))
)
)
)
)
)
);
我想要实现的是根据传入的过滤器动态构建此查询。如何使用对象初始化程序编写此查询?
例如,我想在查询之外创建这三个范围过滤器并将它们放在3个对象中,比如rangeFilter1
,rangeFilter2
和rangeFilter3
,然后在查询中使用逻辑AND (&amp;&amp;)将它们组合起来。
答案 0 :(得分:0)
这是对象初始化程序语法:
var boolQuery = new BoolQuery
{
Must = new QueryContainer[]
{
new MultiMatchQuery
{
Fields = Field<AdDocument>(p => p.Title, 1.5).And<AdDocument>(p => p.Description),
Query = "MyKeyword",
Fuzziness = Fuzziness.Auto
}
},
Filter = new QueryContainer[]
{
new TermQuery { Field = Field<AdDocument>(f => f.NoOfBedrooms), Value = 3 } &&
new TermQuery { Field = Field<AdDocument>(f => f.NoOfBathrooms), Value = 2 } &&
new NumericRangeQuery { Field = Field<AdDocument>(p => p.Price), GreaterThan = 2000 }
}
};
var searchResponse = _elasticClient.Search<AdDocument>(new SearchRequest<AdDocument>
{
Query = boolQuery
});
这将导致以下JSON DSL:
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "MyKeyword",
"fuzziness": "AUTO",
"fields": [
"title^1.5",
"description"
]
}
}
],
"filter": [
{
"bool": {
"must": [
{
"term": {
"noOfBedrooms": {
"value": 3
}
}
},
{
"term": {
"noOfBathrooms": {
"value": 2
}
}
},
{
"range": {
"price": {
"gt": 2000.0
}
}
}
]
}
}
]
}
}
}