ES05-实战

1-ES环境安装
1-Windonws安装ES
Windonws安装ES参考:https://blog.csdn.net/2301_77717148/article/details/150937421
- 1)下载解压,配置环境变量
- ES_HOME:D:\TT_INSTALL\ElasticSearch9.0.0\elasticsearch-9.0.0
- ES_JAVA_HOME:D:\TT_INSTALL\ElasticSearch9.0.0\elasticsearch-9.0.0\jdk
- JAVA_HOME 由于我总是启动报错,不得不暂时将JAVA_HOME指向ES_JAVA_HOME对应的路径
- 2)编辑elasticsearch.yml文件:配置允许IP和跨域支持
- 3)运行/bin/elasticsearch.bat文件即可运行
- 4)访问端口:127.0.0.1:9200(因为我关闭了安全认证,所以可以直接进行访问)
- 访问地址:http://localhost:9200/

- 验证集群可用性:http://localhost:9200/_cluster/health?pretty

2-Docker安装ES
2-常用API
1-L1-Index
# |
动作 |
一句话 |
请求示例 |
1.1 |
创建索引 |
指定 mapping/settings/alias |
PUT /shop_v1 { "settings":{ "number_of_shards":3 }, "mappings":{ "properties":{ "title":{ "type":"text" } } }, "aliases":{ "shop":{} } } |
1.2 |
删除索引 |
危险,谨慎 |
DELETE /shop_v1 |
1.3 |
索引是否存在 |
HEAD 判断 |
HEAD /shop_v1 |
1.4 |
关闭/打开 |
临时下线 |
POST /shop_v1/_close / _open |
1.5 |
刷新 |
刷缓存可见 |
POST /shop_v1/_refresh |
1.6 |
别名切换 |
零停机重建 |
POST _aliases { "actions":[ { "remove":{ "index":"shop_v1","alias":"shop" } },{ "add":{ "index":"shop_v2","alias":"shop" } } ] } |
2-L1-Doc
# |
动作 |
一句话 |
请求示例 |
2.1 |
新建/更新 |
指定 ID 幂等 |
PUT /shop/_doc/1001 { "title":"小米","price":4999 } |
2.2 |
局部更新 |
不改其他字段 |
POST /shop/_update/1001 { "doc":{ "price":4899 } } |
2.3 |
获取 |
拿整条 |
GET /shop/_doc/1001 |
2.4 |
删除 |
单条 |
DELETE /shop/_doc/1001 |
2.5 |
批量写入 |
一行指令一行数据 |
POST _bulk\n{"index":{"_index":"shop","_id":"2001"}}\n{"title":"iPhone"}\n{"delete":{"_index":"shop","_id":"2002"}} |
3-L1-Query
# |
动作 |
一句话 |
请求示例 |
3.1 |
match |
全文分词 |
{ "query":{ "match":{ "title":"小米手机" } } } |
3.2 |
term |
精准匹配 |
{ "query":{ "term":{ "price":4999 } } } |
3.3 |
range |
区间 |
{ "query":{ "range":{ "price":{ "gte":2000,"lte":5000 } } } } |
3.4 |
bool |
组合过滤 |
{ "query":{ "bool":{ "must":[ { "match":{ "title":"小米" } } ], "filter":[ { "range":{ "price":{ "gte":3000 } } } ] } } } |
3.5 |
match_all + 分页 |
全量+from/size |
{ "query":{ "match_all":{} }, "from":0,"size":20 } |
4-L1-Aggregations
# |
动作 |
一句话 |
请求示例 |
4.1 |
avg/max/min |
指标 |
{ "size":0, "aggs":{ "avg_price":{ "avg":{ "field":"price" } } } } |
4.2 |
terms桶 |
分组计数 |
{ "size":0, "aggs":{ "by_tag":{ "terms":{ "field":"tags.keyword" } } } } |
4.3 |
date_histogram |
时间直方图 |
{ "size":0, "aggs":{ "sales_per_day":{ "date_histogram":{ "field":"created","calendar_interval":"1d" } } } } |
4.4 |
range桶 |
区间 |
{ "size":0, "aggs":{ "price_ranges":{ "range":{ "field":"price","ranges":[ {"to":2000},{"from":2000,"to":5000},{"from":5000} ] } } } } |
4.5 |
嵌套聚合 |
桶内再算指标 |
{ "size":0, "aggs":{ "by_tag":{ "terms":{ "field":"tags.keyword" }, "aggs":{ "avg_price":{ "avg":{ "field":"price" } } } } } } |