ES的查询与聚合的基础使用
使用Dev tools用做学习开发
查询
-
创建索引
PUT /customer/_doc/1
{
“name”:“Jhon Doe”
}-
PUT 创建语句 customer – index / _doc – 类型 / 1 – id
-
{ “name”:“Jhon Doe”} 内容
-
-
简单查询所有
GET /customer/_doc/1
github获取测试数据
路径:https://github.com/elastic/elasticsearch/blob/v6.8.18/docs/src/test/resources/accounts.json
服务器执行:curl -H “Content-Type: application/json” -XPOST “localhost:9200/bank/_bulk?pretty&refresh” --data-binary “@/opt/accounts.json”
查询状态
查询所有
-
match_all表示查询所有
-
sort 按照某个字段排序
GET /bank/_search
{
“query”: { “match_all”: {} },
“sort”: [ { “account_number”: “asc” } ]
}
查询结果
took
– Elasticsearch运行查询所花费的时间(以毫秒为单位)
timed_out
–搜索请求是否超时_shards
- 搜索了多少个碎片,以及成功,失败或跳过了多少个碎片的细目分类。max_score
– 找到的最相关文档的分数hits.total.value
- 找到了多少个匹配的文档hits.sort
- 文档的排序位置(不按相关性得分排序时)hits._score
- 文档的相关性得分(使用match_all时不适用)
分页查询
- 增加form和size两个字段
GET /bank/_search
{ “query”: { “match_all”: {} }, “sort”: [ { “account_number”: “asc” } ],“from”: 10,
“size”: 10
}
指定字段查询
- 字段中搜索特定字词,可以使用
match
GET /bank/_search
{ “query”: { “match”: { “address”: “mill lane” } }}
多条件查询
- 构造复杂的查询可以用
tool
GET /bank/_search
{
“query”: {
“bool”: {
“must”: [
{ “match”: { “age”: “40” } }
],
“must_not”: [
{ “match”: { “state”: “ID” } }
]
}
}
}
-
query /filter
-
上下文的条件是用来给文档打分的,匹配越好 _score 越高
-
filter 的条件只产生两种结果:符合与不符合,后者被过滤掉
-
聚合查询
因为无需返回条件的具体数据, 所以设置size=0,返回hits为空。
doc_count
表示bucket中每个州的数据条数
GET /bank/_search
{
“size”: 0,
“aggs”: {
“group_by_state”: {
“terms”: {
“field”: “state.keyword”
}
}
}
}
嵌套聚合
比如承接上个例子, 计算每个州的平均结余。涉及到的就是在对state分组的基础上,嵌套计算avg(balance):
GET /bank/_search
{
“size”: 0,
“aggs”: {
“group_by_state”: {
“terms”: {
“field”: “state.keyword”
},
“aggs”: {
“average_balance”: {
“avg”: {
“field”: “balance”
}
}
}
}
}
}
聚合排序
降序排列
GET /bank/_search
{
“size”: 0,
“aggs”: {
“group_by_state”: {
“terms”: {
“field”: “state.keyword”,
“order”: {
“average_balance”: “desc”
}
},
“aggs”: {
“average_balance”: {
“avg”: {
“field”: “balance”
}
}
}
}
}
}