布尔查询(Bool Query)
布尔查询是一种联合查询,可以对多个查询条件进行组合,布尔查询有四个子查询关键词:
关键词 | 描述 |
---|---|
must | 查询的结果必须匹配查询条件,并计算score |
filter | 查询的结果必须匹配查询条件,和must不同不会计算score |
should | 查询结果必须符合查询条件中的一个或多个 |
must_not | 查询结果必须不符合查询条件 |
有时我们在查询es时,希望能够一次返回符合多个查询条件的结果,如多个时间范围查询、多个项的查询等。
- 使用should进行多个时间范围的查询
curl -XPOST 'ip:9200/indices/_search' -H "Content-Type: application/json" -d
'{
"query": {
"bool": {
"should": [
{
"range": {
"@timestamp": {
"gt": "2019-05-28T00:00:14.310Z",
"lt": "2019-05-28T00:00:30.310Z"
}
}
},
{
"range": {
"@timestamp": {
"gt": "2019-05-28T00:01:30.310Z",
"lt": "2019-05-28T00:02:00.310Z"
}
}
}
]
}
}
}'
查询结果为符合@timestamp字段在2019-05-28T00:00:14.310Z到2019-05-28T00:00:30.310Z,或2019-05-28T00:01:30.310Z到2019-05-28T00:02:00.310Z时间范围内的结果
- 使用should进行多个项的查询
curl -XPOST 'ip:9200/indices/_search' -H "Content-Type: application/json" -d
'{
"query": {
"bool": {
"should": [
{
"term": {
"username": "username01"
}
},
{
"term": {
"username": "username02"
}
}
]
}
}
}'
查询结果返回用户名username为username01和username02的所有结果
- 使用多个关键词查询
curl -XPOST 'ip:9200/indices/_search' -H "Content-Type: application/json" -d
'{
"query": {
"bool": {
"must": [
{
"term": {
"username": "username01"
}
}
],
"must_not": [
{
"term": {
"ip": "127.0.0.1"
}
}
]
}
}
}'
查询结果为用户名username为username01且登录ip不为127.0.0.1的结果
参考资料:
官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html