# ElasticSearch常规操作

### ES REST API 风格接口

* https://www.elastic.co/guide/en/elasticsearch/reference/7.7/cat-indices.html

### 笔记参考

* https://juejin.cn/post/7156423329765654558

### 查看健康状态

```bash
GET /_cat/health?v

epoch      timestamp cluster        status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1681284001 07:20:01  docker-cluster green           1         1      4   4    0    0        0             0                  -                100.0%
```

### 查看ES集群中的索引

```bash
GET /_cat/indices?v


health status index                    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
green  open   .apm-custom-link         mEMoLqgkTbasghERbugo5g   1   0          0            0       208b           208b
green  open   .kibana_task_manager_1   dkEtqWUkQFe0TjIj4GeUJg   1   0          5            0     37.9kb         37.9kb
green  open   .apm-agent-configuration bjTtOoOfQZmvh9j5CHt9QA   1   0          0            0       208b           208b
green  open   .kibana_1                ZePVmaFiRDWrT2I70KB4Ag   1   0         87            3    145.9kb        145.9kb
yellow open   test_index               dqtYReLBSymyJwXy6cDDww   1   1          0            0       208b           208b


test_index yellow , 是因为只有一个节点， 主本和副本不能放同一个节点上
```

### 创建索引

```bash
PUT /test_index


{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "test_index"
}
```

### 删除索引

```bash
DELETE /test_index

{
  "acknowledged" : true
}
```

### 新增员工（文档）

```bash
PUT /company/_doc/1
{
  "name": "Jack",
  "age": 33, 
  "gender": "male",
  "join_date": "2012-01-01"
}



# 返回
{
  "_index" : "company",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}
```

### 查询员工

> 可以指定ID的方式来进行文档查询。

```bash
GET /company/_doc/1


# 返回
{
  "_index" : "company",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "_seq_no" : 0,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Jack",
    "age" : 33,
    "gender" : "male",
    "join_date" : "2012-01-01"
  }
}



# 无数据返回
{
  "_index" : "company",
  "_type" : "_doc",
  "_id" : "2",
  "found" : false
}
```

### 修改员工（文档）

* 通过指定ID的方式进行修改

```bash
PUT /company/_doc/1
{
    "name" : "Jack",
    "age" :  24,
    "gender" :  "male",
    "join_date":  "2012-01-01"
}


# 返回

{
  "_index" : "company",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 1,
  "_primary_term" : 1
}
```

### 删除员工（文档）

* 指定文档ID，删除文档

```bash
DELETE /company/_doc/1


{
  "_index" : "company",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 3,
  "result" : "deleted",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 2,
  "_primary_term" : 1
}
```

### 批量查询

* 使用 mget 命令进行多个id的批次查询

```bash
POST /company/_mget
{
  "ids": [1, 2]
}



{
  "docs" : [
    {
      "_index" : "company",
      "_type" : "_doc",
      "_id" : "1",
      "_version" : 3,
      "_seq_no" : 5,
      "_primary_term" : 1,
      "found" : true,
      "_source" : {
        "name" : "Jack",
        "age" : 33,
        "gender" : "male",
        "join_date" : "2012-01-01"
      }
    },
    {
      "_index" : "company",
      "_type" : "_doc",
      "_id" : "2",
      "_version" : 1,
      "_seq_no" : 6,
      "_primary_term" : 1,
      "found" : true,
      "_source" : {
        "name" : "Jack",
        "age" : 3322,
        "gender" : "male",
        "join_date" : "2012-01-01"
      }
    }
  ]
}
```

### 批量操作

* 除了批量查询之外，也可以进行批量的其他操作。这里需要使用 \_bulk 命令

\*\* 命令模板如下：\*\*

```bash
POST /index/_bulk
{ action: { metadata }}\n
{ request body }\n
{ action: { metadata }}\n
{ request body }\n
```

\*\* bulk的请求模板分成action、metadata和request body三部分。action必须是以下4种选项之一 \*\*

* index : 如果文档不存在就创建，如果文档存在就更新
* create : 如果文档不存在就创建，但如果文档存在就返回错误
* update : 更新一个文档，如果文档不存在就返回错误，使用时要给\_id值
* delete : 删除一个文档，如果要删除的文档id不存在，就返回错误

### 例如：批量添加数据

```bash
POST /company/_bulk
{"create":{"_index":"company","_id": 0}}
{"name":"Bob","age": 19,"hobby": "rap"}
{"create":{"_index":"company","_id": 1}}
{"name":"Tom","age": 20,"hobby": "football basketball sing"}
{"create":{"_index":"company","_id": 2}}
{"name":"Jack","age":30,"hobby": "basketball tennis sing"}
{"create":{"_index":"company","_id": 3}}
{"name":"Amy","age": 25,"hobby": "dance sing rap"}



# 返回，由于使用 create 方式， ID (1,2) 已经存在，所以报错

{
  "took" : 57,
  "errors" : true,
  "items" : [
    {
      "create" : {
        "_index" : "company",
        "_type" : "_doc",
        "_id" : "0",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 7,
        "_primary_term" : 1,
        "status" : 201
      }
    },
    {
      "create" : {
        "_index" : "company",
        "_type" : "_doc",
        "_id" : "1",
        "status" : 409,
        "error" : {
          "type" : "version_conflict_engine_exception",
          "reason" : "[1]: version conflict, document already exists (current version [3])",
          "index_uuid" : "nm_lNVG8RK22tTL2_CRgJg",
          "shard" : "0",
          "index" : "company"
        }
      }
    },
    {
      "create" : {
        "_index" : "company",
        "_type" : "_doc",
        "_id" : "2",
        "status" : 409,
        "error" : {
          "type" : "version_conflict_engine_exception",
          "reason" : "[2]: version conflict, document already exists (current version [1])",
          "index_uuid" : "nm_lNVG8RK22tTL2_CRgJg",
          "shard" : "0",
          "index" : "company"
        }
      }
    },
    {
      "create" : {
        "_index" : "company",
        "_type" : "_doc",
        "_id" : "3",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 8,
        "_primary_term" : 1,
        "status" : 201
      }
    }
  ]
}
```
