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}}
]
}}
]
}
}
}
}
}