Elasticsearch的API操作

Elasticsearch常用API

官方文档:Elasticsearch:官方分布式搜索和分析引擎 | Elastic

查看索引列表

1
http://localhost:9200/_cat/indices?v&pretty

运行上述命令后,将会显示一个包含所有索引的表格,其中列出了索引名称、文档数量、主分片数量、副本分片数量等信息。

查询索引结构信息

1
GET http://localhost:9200/索引名?pretty

查询索引所有文档数据

1
GET http://localhost:9200/索引名/_search

删除索引

1
DELETE http://localhost:9200/索引名

返回结果为

1
2
3
{
"acknowledged": true
}

即删除成功

删除索引下的数据

只删除数据,不删除数据结构

1
2
3
4
5
6
7
POST http://localhost:9200/索引名/_delete_by_query?pretty

{
"query":{
"match_all":{}
}
}

返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"took": 185,
"timed_out": false,
"total": 10,
"deleted": 10,
"batches": 1,
"version_conflicts": 0,
"noops": 0,
"retries": {
"bulk": 0,
"search": 0
},
"throttled_millis": 0,
"requests_per_second": -1.0,
"throttled_until_millis": 0,
"failures": []
}

分词逻辑

1
2
3
4
5
6
GET http://localhost:9200/_analyze

{
"analyzer" : "standard",
"text" : "this is a test"
}

查询最早时间

1
2
3
4
5
6
7
8
9
10
11
GET /索引名/_search
{
"size": 0,
"aggregations": {
"min_date": {
"min": {
"field": "date_field"
}
}
}
}

重建索引

原索引修改别名

1
2
3
4
5
6
7
8
9
10
11
12
13
curl --location --request POST 'http://localhost:9200/_aliases' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
"actions": [
{
"add": {
"index": "原索引名",
"alias": "原索引别名"
}
}
]
}'

创建新索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
curl --location --request PUT 'http://localhost:9200/新索引名' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
"settings": {
"index": {
"refresh_interval": "1s",
"number_of_shards": "5",
"number_of_replicas": "1"
}
},
"mappings": {
"dynamic": "false",
"properties": {
"id": {
"type": "keyword",
"ignore_above": 32
}
}
}
}'

同步数据到新索引

1
2
3
4
5
6
7
8
9
10
11
curl --location --request POST 'http://localhost:9200/_reindex?slices=5&refresh=' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
"source": {
"index": "旧索引名"
},
"dest": {
"index": "新索引名"
}
}'

新的索引添加别名,旧的索引去除别名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
curl --location --request POST 'http://localhost:9200/_aliases' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
"actions": [
{
"add": {
"index": "新索引名",
"alias": "新索引别名"
}
},
{
"remove": {
"index": "旧索引名",
"alias": "旧索引别名"
}
}
]
}'

删除旧索引

1
2
curl --location --request DELETE 'http://localhost:9200/旧索引名' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)'

删除索引别名

1
2
3
curl --location --request DELETE 'http://39.98.35.72:30011/_aliases?index=索引名别名' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json'