场景
在使用ES时经常需要通过接口或者查询工具查找ES中的数据,需要了解基本的查询命令。 如精确查询,模糊匹配,多条件查询等。
操作
-
查询
#默认返回10条
GET http://127.0.0.1:9200/user_index/_search
- 条件查询
#全值匹配
GET http://127.0.0.1:9200/user_index/_search?q=_id:532
#包含
GET http://127.0.0.1:9200/user_index/_search?q=+name:李
#不包含
GET http://127.0.0.1:9200/user_index/_search?q=-name:李
#全文搜索
GET http://127.0.0.1:9200/user_index/_search?q=李
- 指定条数
#返回指定条数
GET http://127.0.0.1:9200/user_index/_search?size=10
#指定数据的位置,一般分页中使用
GET http://127.0.0.1:9200/user_index/_search?size=10&from=10
#组合查询
GET http://127.0.0.1:9200/user_index/_search?q=+name:李&size=10
- json格式
# 字段匹配
GET user_index/_search
{
"_source": ["name", "age"], #显示字段
"query":{
"match":{
"name": "lizz"
}
}
}
# 多条件匹配
GET user_index/_search
{
"query": {
"bool": { # 是否为真
"must": [ # 满足下列条件
{"match": {"name": "lizz"}}, # name字段为lizz
{"terms": {"code": [110,112,113]}}, # name字段为lizz
{"range": {"createAt": { "gte": "2024-06-10T12:00:00", "lte": "2024-06-11" } } } # createAt时间范围
],
"must_not": [ # 不满足下列调整
{ "exists": { "field": "idcard" } } #存在idcard字段
]
}
}
}
- 分组统计
GET /users_lizz/_search
{
"size": 0,
"aggs": {
"xzqh_count": { // 统计数量字段
"terms": {
"field": "xzqh", # 分组字段
"size": 100 # 返回条数
}
}
}
}
- 返回结果
{
"took": 35, #执行时间,毫秒数
"timed_out": false, #查询是否超时
"_shards": {
"total": 1, #返回条数
"successful": 1, #成功返回条数
"skipped": 0, #跳过的数据条数
"failed": 0 #失败的数据条数
},
"hits": {
"total": {
"value": 6963, #总条数
"relation": "eq" #查询类型,eq=equal相等
},
"max_score": 0.7731953, # 返回数据中匹配最高分
"hits": [
{
"_index": "qx_user", #索引名词
"_type": "_doc", # 索引类型
"_id": "6013584", # 数据id
"_score": 0.7731953, # 数据分数
"_source": { # 数据内容
...
}
}
]
}
}