[TOC]
## **批量處理 `_bulk:index、delete、create、update`**
- 批量創建/更新 index
```
POST _bulk
{ "index" : { "_index" : "teacher", "_type" : "_doc", "_id" : "1" } }
{ "name" : "Milton" }
{ "index" : { "_index" : "teacher", "_type" : "_doc", "_id" : "2" } }
{ "name" : "Cherish" }
{ "index" : { "_index" : "teacher", "_type" : "_doc", "_id" : "3" } }
{ "name" : "Evan" }
```
- 批量創建 create
```
POST _bulk
{ "create" : { "_index" : "teacher", "_type" : "_doc", "_id" : "4" } }
{ "name" : "yangp" }
{ "create" : { "_index" : "teacher", "_type" : "_doc", "_id" : "5" } }
{ "name" : "yangf" }
```
>[danger] index 和 create 都可以增加文檔。使用index時,如果記錄已存在,則會進行更新,如果不存在,則會新增;但是使用create時,如果記錄已存在,則會創建失敗!
- 批量更新 update
```
POST /teacher/_doc/_bulk
{ "update" : { "_id" : "4" } }
{"doc":{ "name" : "yangp_update" }}
{ "update" : { "_id" : "5" } }
{"doc":{ "name" : "yangf_update" }}
```
- 批量刪除 delete
```
POST /teacher/_doc/_bulk
{"delete":{"_id":"4"}}
{"delete":{"_id":"5"}}
```
## **批量獲取 `_mget`**
- 獲取索引teacher中,id為1,2的document
```
GET /_mget
{
"docs":[
{
"_index":"teacher",
"_type":"_doc",
"_id":"1",
"_source" : false
},
{
"_index":"teacher",
"_type":"_doc",
"_id":"2",
"_source" : ["name"]
}
]
}
```
- 獲取索引teacher中,id為1,2的document
```
GET /teacher/_mget
{
"docs":[
{
"_type":"_doc",
"_id":"1"
},
{
"_type":"_doc",
"_id":"2"
}
]
}
```
- 獲取索引teacher中,id為1,2的document
```
GET /teacher/_doc/_mget
{
"docs":[
{ "_id":"1"},
{ "_id":"2" }
]
}
```
- 獲取索引teacher中,id為1,2的document
```
GET /teacher/_doc/_mget
{
"ids":["1","2"]
}
```
## **匹配刪除 `_delete_by_query`**
從索引teacher中刪除name為“Evan”的document
```
POST /teacher/_delete_by_query
{
"query":{
"match": {
"name": "Evan"
}
}
}
```
## **匹配更新`_update_by_query`**
從索引teacher中,更新name包含“Milton”的文檔,設置其gener=“Boy”,age=100
```
POST /teacher/_update_by_query
{
"query":{
"match": {
"name": "Milton"
}
},
"script":{
"source":"ctx._source.gener=params.gener;ctx._source.age=params.age",
"params":{
"gener":"Boy"
,
"age":100
}
}
}
```