15、ES实战:实现批量操作mgetbulk

Java实现批量操作(mget&bulk)
mget

批量获取使用MultiGetResponse

public class EsMget{
   
     
    public void updateIndex(TransportClient client){
   
     
        MultiGetResponse response = client.prepareMultiGet()
							       .add("pointdata","pointdata","1","2")
							       .add("lib3","user","1","2","3")
							       .get();

		for(MultiGetItemResponse item:resopnse){
   
     
			GetResopnse gr = item.getResponse();
			if(gr!=null && gr.isExists()){
   
     
				System.out.println(gr.getSourceAsString());
			}
		}
    }
}

bulk

批量增删改使用BulkRequestBuilder

批量增加

public class EsBulkIndex{
   
     
    public void updateIndex(TransportClient client){
   
     
       BulkRequestBuilder bulkBuild = client.prepareBulk();
	   
	   //批量添加
	   Date time1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-7-21 00:00:01");
	   bulkBuild.add(client.prepareIndex("lib2","books","8")
						   .setSource(
							   XContentFactory.jsonBuilder()
                                         .startObject()
                                         .field("pointid","W3.UNIT1.10LBG01CP302")
                                         .field("pointvalue","0.8029")
                                         .field("inputtime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time1))
                                         .endObject()
						   )
			   );
		Date time2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-7-21 00:00:02");
		bulkBuild.add(client.prepareIndex("lib2","books","8")
						   .setSource(
							   XContentFactory.jsonBuilder()
                                         .startObject()
                                         .field("pointid","W3.UNIT1.10LBG01CP302")
                                         .field("pointvalue","0.8027")
                                         .field("inputtime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2))
                                         .endObject()
						   )
			   );
		BulkResponse response = bulkBuild.get();
		//查看返回状态
		System.out.println(response.status());
		if(response.hasFailures()){
   
     
			System.out.println("添加失败");
		}
    }
}

批量删除

public class EsBulkDelete{
   
     
    public void updateIndex(TransportClient client){
   
     
       BulkByScrollResponse resopnse = DeleteByQueryAction.INSTANCE
									   .newRequestBuilder(client)
									   .filter(QueryBuilders.matchQuery("pointid","W3.UNIT1.10LBG01CP302")) //筛选条件
									   .source("index1")
									   .get();
		//返回删除文档的个数
		long counts = response.getDeleted();
		System.out.println(counts);
    }
}

版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: