Elasticsearch使用MultiGet批量获取文档与使用Bulk批量操作

Multi Get 批量获取

Multi Get API可以通过索引名、类型名、文档id一次得到一个文档集合,文档可以来自同一个索引库,也可以来自不同的索引库。

GET /_mget
{
  "docs":[
     {
        "_index": "lib",
        "_type": "user",
        "_id": "1"
     },
     {
        "_index": "lib",
        "_type": "user",
        "_id": "2"
     },
     {
        "_index": "lib",
        "_type": "user",
        "_id": "3"
     }
  ]
}

//可以指定具体的字段
GET /_mget
{
  "docs":[
     {
        "_index": "lib",
        "_type": "user",
        "_id": "1",
        "_source": "interests"
     },
     {
        "_index": "lib",
        "_type": "user",
        "_id": "2",
        "_source": {"age","interests"}
     }
  ]
}

//获取同索引同类型下的不同文档
GET /lib/user/_mget
{
  "docs":[
     {
        "_id": "1"
     },
     {
        "_type": "user", //若是指定索引和类型必须和请求头上的保持一致,否者将会报错。
        "_id": "2"
     }
  ]
}
//也可以使用下面这种更为简化的写法
GET /lib/user/_mget
{
  "ids":["1","2"]
}
Bulk 批量操作

bulk的格式:
{action:{metadata}}\n
{requstbody}\n (请求体)

  • action:(行为),包含create(文档不存在时创建)、update(更新文档)、index(创建新文档或替换已用文档)、delete(删除一个文档)。
    create和index的区别:如果数据存在,使用create操作失败,会提示文档已存在,使用index则可以成功执行。
  • metadata:(行为操作的具体索引信息),需要指明数据的_index、_type、_id。

示例:

{"delete":{"_index":"lib","_type":"user","_id":"1"}}

批量添加

POST /lib2/books/_bulk
{"index":{"_id":1}}  \\行为:索引信息
{"title":"Java","price","55"} \\请求体
{"index":{"_id":2}}
{"title":"Html5","price","45"}
{"index":{"_id":3}}
{"title":"Php","price","35"}`
{"index":{"_id":4}}
{"title":"Python","price","50"}

//返回结果
{
  "took": 60,
  "error": false //请求是否出错,返回false、具体的错误
  "items": [
     //操作过的文档的具体信息
     {
        "index":{
           "_index": "lib",
           "_type": "user",
           "_id": "1",
           "_version": 1,
           "result": "created", //返回请求结果
           "_shards": {
              "total": 1,
              "successful": 1,
              "failed": 0
           },
           "_seq_no": 0,
           "_primary_trem": 1
           "status": 200
        }
    }, 
    ... 
  ]
}

猜你喜欢

转载自blog.csdn.net/zx711166/article/details/81540823