[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
}
}
}
```