您可以use a bool
query to combine queries和NEST使得這個由運算符重載結合QueryContainer
S(根查詢類型)稍微容易的工作。下面是NEST 2.x的一個例子
void Main()
{
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool);
var client = new ElasticClient(settings);
var itemsPerPage = 20;
var pattern = "match query";
client.Search<SearchItem>(x => x
.Sort(so => so
.Descending("_score")
)
.Size(itemsPerPage)
.Query(q => q
.MultiMatch(m => m
.Fields(fs => fs
.Field(p => p.Field1)
.Field(p => p.Field2)
.Field(p => p.Field3)
.Field(p => p.Field4)
.Field(p => p.Field5)
.Field(p => p.Field6)
)
.Operator(Operator.And)
.Query(pattern)
) && q
.Range(ra => ra
.Field(ff=>ff.SalePrice)
.GreaterThan(1000)
)
)
);
}
public class SearchItem
{
public int SalePrice { get; set; }
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
public string Field5 { get; set; }
public string Field6 { get; set; }
}
這將產生
{
"size": 20,
"sort": [
{
"_score": {
"order": "desc"
}
}
],
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "match query",
"operator": "and",
"fields": [
"field1",
"field2",
"field3",
"field4",
"field5",
"field6"
]
}
},
{
"range": {
"salePrice": {
"gt": 1000.0
}
}
}
]
}
}
}
這就會發現,都爲multi_match
查詢和也匹配文檔有salePrice
大於1000。由於我們不不需要爲範圍查詢計算分數(文檔的salePrice
大於1000或者不是),範圍查詢可以在過濾器上下文中運行。稍微改良版本
client.Search<SearchItem>(x => x
.Sort(so => so
.Descending("_score")
)
.Size(itemsPerPage)
.Query(q => q
.MultiMatch(m => m
.Fields(fs => fs
.Field(p => p.Field1)
.Field(p => p.Field2)
.Field(p => p.Field3)
.Field(p => p.Field4)
.Field(p => p.Field5)
.Field(p => p.Field6)
)
.Operator(Operator.And)
.Query(pattern)
) && +q
.Range(ra => ra
.Field(ff=>ff.SalePrice)
.GreaterThan(1000)
)
)
);
追加一元+
運營商的範圍查詢是針對布爾查詢過濾器的簡寫。查詢JSON現在看起來像
{
"size": 20,
"sort": [
{
"_score": {
"order": "desc"
}
}
],
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "match query",
"operator": "and",
"fields": [
"field1",
"field2",
"field3",
"field4",
"field5",
"field6"
]
}
}
],
"filter": [
{
"range": {
"salePrice": {
"gt": 1000.0
}
}
}
]
}
}
}
使用'bool'查詢到兩個'multi_match'和'range'查詢相結合 - https://www.elastic.co/guide/en/elasticsearch/client/淨API/2.X /布爾-queries.html –