版本说明
本文基于Elasticsearch6.4.0版本
演示数据
mapping映射
{
"emp": {
"mappings": {
"base_info": {
"properties": {
"age": {
"type": "integer"
},
"dept": {
"type": "long"
},
"detail": {
"type": "text"
},
"name": {
"type": "keyword"
},
"salary": {
"type": "double"
},
"sex": {
"type": "integer"
}
}
}
}
}
}
当前已有数据
{
"took": 11,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 6,
"max_score": 1,
"hits": [
{
"_index": "emp",
"_type": "base_info",
"_id": "10",
"_score": 1,
"_source": {
"name": "王者",
"age": 26,
"sez": 1,
"salary": 6666,
"detail": "渣渣辉"
}
},
{
"_index": "emp",
"_type": "base_info",
"_id": "5",
"_score": 1,
"_source": {
"name": "赵六",
"age": 24,
"sex": 1,
"salary": 8888,
"detail": null
}
},
{
"_index": "emp",
"_type": "base_info",
"_id": "2",
"_score": 1,
"_source": {
"name": "李四",
"age": 22,
"sex": 0,
"salary": 18888,
"detail": "才华横溢、天赋异禀"
}
},
{
"_index": "emp",
"_type": "base_info",
"_id": "1",
"_score": 1,
"_source": {
"name": "张三",
"age": 18,
"sex": 1,
"salary": 6000,
"detail": "普通人"
}
},
{
"_index": "emp",
"_type": "base_info",
"_id": "3",
"_score": 1,
"_source": {
"name": "王五",
"age": 23,
"sex": 1,
"salary": 10000,
"detail": "全能王者"
}
},
{
"_index": "emp",
"_type": "base_info",
"_id": "11",
"_score": 1,
"_source": {
"name": "小王",
"age": 26,
"sez": 1,
"salary": 1234,
"detail": "隔壁老王"
}
}
]
}
}
Bool Query
可以用来组合多个条件实现复杂的查询,以下是几个关键属性
must:相当于并且的关系,条件必须满足
filter:与must相似,但不会计算得分,且会缓存文档查询结果
should:相当于或者的关系,满足其中一个条件即可
must_not:与must相反,不能满足任何一个。
以下语句表示:查询name为“赵六”,且年龄不在10-20岁之间
注意当must与should一起使用时,should条件会失效,以下语句相当于“年龄等于25或者salary等于111”这个条件不存在
GET /emp/base_info/_search
{
"query": {
"bool": {
"must": {
"match": {
"name": "赵六"
}
},
"should": [
{
"match": {
"age": 25
}
},
{
"term": {
"salary": 111
}
}
],
"must_not": {
"range": {
"age": {
"gte": 10,
"lte": 20
}
}
}
}
}
}
查询结果
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.6931472,
"hits": [
{
"_index": "emp",
"_type": "base_info",
"_id": "5",
"_score": 0.6931472,
"_source": {
"name": "赵六",
"age": 24,
"sex": 1,
"salary": 8888,
"detail": null
}
}
]
}
}