[TOC]
現在,我們已經啟動并運行了自己的節點(集群),下一步是要了解如何溝通。幸運的是,Elasticsearch提供了一個非常全面和強大的REST API,讓我們可以與集群進行交互,例如:
- 檢查我們的集群、節點和索引健康狀態和統計數據
- 管理集群、節點和索引數據和元數據
- 執行CRUD(創建、讀取、更新和刪除)索引和搜索操作
- 執行高級搜索操作,比如分頁、排序、過濾、腳本、聚合等
>[success] API 匹配模式:\<HTTP Verb> /\<Index>/\<Type>/\<ID>
## **集群管理**
### **查看集群健康狀態: `GET /_cat/health` 或 `GET /_cluster/health`**
查看集群健康狀態命令:
```
curl -X GET "localhost:9200/_cat/health?v"
```
運行結果如下:
```cmd
epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1543028474 03:01:14 docker-cluster green 1 1 0 0 0 0 0 0 - 100.0%
```
```
curl -X GET "localhost:9200/_cluster/health?pretty"
```
運行結果如下:
```cmd
{
"cluster_name" : "docker-cluster",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 1,
"number_of_data_nodes" : 1,
"active_primary_shards" : 0,
"active_shards" : 0,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0
}
```
每當我們問集群健康,我們要么得到green,yellow和red。
- Green - everything is good (cluster is fully functional)
- Yellow - all data is available but some replicas are not yet allocated (cluster is fully functional)
- Red - some data is not available for whatever reason (cluster is partially functional)
### **查看集群中的節點: `GET /_cat/nodes`**
查看集群中的節點命令:
```
curl -X GET "localhost:9200/_cat/nodes?v"
```
運行結果如下:
```cmd
ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
172.17.0.2 10 95 13 0.16 0.24 0.49 mdi * jNMR62Z
```
在這里,我們可以看到一個名為“jNMR62Z”的節點.目前在我們的集群是單一節點。
### **列出當前所有的索引: `GET /_cat/indices`**
列出當前所有的索引命令:
```
curl -X GET "localhost:9200/_cat/indices?v"
```
運行結果如下:
```cmd
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
```
目前,我們還沒有創建任何一個索引
### **創建索引: `PUT /<index>`**
創建一個索引“customer”命令:
```
curl -X PUT "localhost:9200/customer?pretty"
```
我們使用PUT方法,創建了一個名字為“customer”的索引,上面的參數`pretty`,是格式化輸出JSON的作用
運行結果如下:
```cmd
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "customer"
}
```
列出當前所有索引命令:
```
curl -X GET "localhost:9200/_cat/indices?v"
```
運行結果如下:
```cmd
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open customer H4FuIykjRIeAbPij8yLRug 5 1 0 0 1.1kb 1.1kb
```
### **刪除索引: `DELETE /<index>`**
刪除上面練習中添加的索引customer,命令:
```
curl -X DELETE "localhost:9200/customer?pretty"
```
運行結果如下:
```cmd
{
"acknowledged" : true
}
```
由上面結果可知,已成功刪除索引“teacher”