Elasticsearch Java API 的使用(15)—实现批量操作(mget&bulk)

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值