2> bool 查询
与 bool 过滤相似,用于合并多个查询子句。
查询 内容中带有 “第” ,但是不带有 “新” 的文档,返回 id 为 2,3 的文档
curl -XGET
'https://localhost:9200/test/article/_search?pretty' -d
'
{
"query
": {
"bool
": {
"must
": { "match
": { "content
": "第
" }},
"must_not
": { "match
": { "content
": "新
" }}
}
}
}'
3、复合查询
介绍完过滤语句和查询语句,现在我们就来将它们两个组合起来使用
请求体格式如下
{
"
query" :
{
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"term" : {
"author" : "jam"
}
}
}
}
}
filtered 中可以只包含 query 或 filter 或者两者都存在,可存在多个 filter ,若不指定查询范围(query),默认为 “match_all” : {}
query 中可包含 bool 查询或match 查询
filter 中可包含各种过滤查询
现在来看一个比较复杂的例子
curl -XGET
'https://localhost:9200/test/article/_search?pretty' -d
'
{
"query
": {
"filtered
": {
"query
" : {
"match_all
" : {}
},
"filter
" : {
"range
": {
"id
": {
"gte
": 2,
"lte
": 4
}
}
},
"filter
" : {
"bool
": {
"must
": { "term
": { "author
": "jam
" }},
"must_not
": { "term
": { "id
": 2 }}
}
}
}
}
}'
首先是查询所有数据(可省略),可改成有条件的查询
"query" : {
"match_all" : {}
},
然后进行过滤查询,查询 id 范围 大于等于 2 小于等于 4 的文档
"filter" : {
"range": {
"id": {
"gte":
2,
"lte":
4
}
}
},
最后再过滤,查询作者是 jam ,但是 id 不能是 2 的文档,这样就只有 id 为 3 的文档符合条件
"filter" : {
"bool": {
"must": {
"term": {
"author":
"jam" }},
"must_not": {
"term": {
"id":
2 }}
}
}
这条复合查询类似如下 SQL 语句
SELECT * FROM article WHERE id >= 2 AND id <= 4 AND author = ‘jam’ AND id != 2
4、 验证查询语句
查询语句的请求体越来越大,很容易在书写过程中出现错误,可以使用 validate API 的explain 进行验证
使用上面的复合查询语句(注意请求链接)
curl -XGET 'http://localhost:
9200/test/article/_validate/query?explain&pretty' -d '
{
"query": {
"filtered": {
"query" : {
"match_all" : {}
},
"filter" : {
"range": {
"id": {
"gte":
2,
"lte":
4
}
}
},
"filter" : {
"bool": {
"must": {
"term": {
"author":
"jam" }},
"must_not": {
"term": {
"id":
2 }}
}
}
}
}
}'
#返回,真是正确的
{
"valid" :
true,
"_shards" : {
"total" :
1,
"successful" :
1,
"failed" :
0
},
"explanations" : [ {
"index" :
"test",
"valid" :
true,
"explanation" :
"+(+*:* #(+author:jam -id:`\b\u0000\u0000\u0000\u0002)) #ConstantScore(+ConstantScore(_type:article))"
} ]
}
# 将第一个filter 上面的逗号去掉,再验证。错误信息中会提示第几行,第几列出错,方便修改错误
{
"valid" :
false,
"_shards" : {
"total" :
1,
"successful" :
1,
"failed" :
0
},
"explanations" : [ {
"index" :
"test",
"valid" :
false,
"error" :
"[test] QueryParsingException[Failed to parse]; nested: JsonParseException[Unexpected character ('\"' (code 34)): was expecting comma to separate OBJECT entries\n at [Source: org.elasticsearch.transport.netty.ChannelBufferStreamInput@3175024d; line: 8, column: 14]];; com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\"' (code 34)): was expecting comma to separate OBJECT entries\n at [Source: org.elasticsearch.transport.netty.ChannelBufferStreamInput@3175024d; line: 8, column: 14]"
} ]
}