Combining Filters
之前的兩個例子都是單個字段的查詢。在生成環境中,你會需要多個值一起查詢的,例如在sql語言中
SELECT product
FROM products
WHERE (price = 20 OR productID = "XHDK-A-1293-#fJ3")
AND (price != 30)
這種情況,你需要一個bool query在constant_score裏面。
話不多說,直接上例子!
{
“bool” : {
“must” : [],
“should” : [],
“must_not” : [],
“filter”: []
}
}
must: 所有的clauses都必須匹配,跟and等價
must_not: 跟NOT等價
should:跟or等價
filter: Clauses必須匹配,但是執行non-scoring模式
寫一個與上邊sql代碼等價的代碼
GET /my_store/products/_search
{
"query" : {
"constant_score" : {
"filter" : {
"bool" : {
"should" : [
{ "term" : {"price" : 20}},
{ "term" : {"productID" : "XHDK-A-1293-#fJ3"}}
],
"must_not" : {
"term" : {"price" : 30}
}
}
}
}
}
}
注意bool是怎麼放在constant_score裏面的,但是單個的term查詢僅僅放在should和mustnot。
當然還有更復雜的查詢,這裏不再詳細描述了。
SELECT document
FROM products
WHERE productID = "KDKE-B-9947-#kL5"
OR ( productID = "JODL-X-1937-#pV7"
AND price = 30 )
等價於
GET /my_store/products/_search
{
"query" : {
"constant_score" : {
"filter" : {
"bool" : {
"should" : [
{ "term" : {"productID" : "KDKE-B-9947-#kL5"}},
{ "bool" : {
"must" : [
{ "term" : {"productID" : "JODL-X-1937-#pV7"}},
{ "term" : {"price" : 30}}
]
}}
]
}
}
}
}
}