Elasticsearch学习笔记(十)批量查询mget、批量增删改bulk

时间:2023-03-08 23:50:58
Elasticsearch学习笔记(十)批量查询mget、批量增删改bulk

一、批量查询  mget


            GET
/_mget
{
  "docs":[
      {
        "_index":"ecommerce",
        "_type":"product",
        "_id":1
      },
      {
        "_index":"ecommerce",
        "_type":"product",
        "_id":2
      }
    ]

}
如果docs内的document都是同一个index则可以简略为:
        GET /ecommerce/_mget
{
  "docs":[
      {
        "_type":"product",
        "_id":1
      },
      {
        "_type":"product",
        "_id":2
      }
    ]

}
如果docs内的document都是同一个index同一个type则可以进一步简略为:
GET
/ecommerce/product/_mget
{
      "ids":[1,2,3,4]
}

二、批量增删改
bulk

       1、bulk语法
                POST /_bulk
                {"action":{"_index":"","_type":"","_id":""}}
                {"data"}
        action的值有:
                 (1)delete:删除一个文档,只要1个json串就可以了
   (2)create:PUT
/index/type/id/_create,强制创建
   (3)index:普通的put操作,可以是创建文档,也可以是全量替换文档
   (4)update:执行的partial
update操作       
        注意:

(1)action所在json和data所在的json要换行,当action为delete时没有data

                        (2)action所在的json内不能有空格换行,否则出错
                        (3)每个json串不能换行,只能放一行,同时一个json串和一个json串之间,必须有一个换行
                        (4)bulk操作中,任意一个操作失败,是不会影响其他的操作的,但是在返回结果里,会告诉你异常日志
                示例:
                        POST
/_bulk
{"delete":{"_index":"test_index","_type":"test_type","_id":"3"}}
{"create":{"_index":"test_index","_type":"test_type","_id":"13"}}
{"test_field":"replaced
test13"}
{"index":{"_index":"test_index","_type":"test_type","_id":"2"}}
{"test_field":"replaced
test2"}
{"update":{"_index":"test_index","_type":"test_type","_id":"1","_retry_on_conflict":3}}
{"doc":{"test_field2":"bulk test
1"}}

            2、bulk size最佳大小
            bulk
request会加载到内存里,如果太大的话,性能反而会下降,因此需要反复尝试一个最佳的bulk
size。一般从1000~5000条数据开始,尝试逐渐增加。另外,如果看大小的话,最好是在5~15MB之间。