es之java删除文档操作
删除文档操作
@Test public void deleteDocument(){ DeleteResponse response = client.prepareDelete("twitter4", "tweet", "1").get(); // 索引名称 String _index = response.getIndex(); // 类型 String _type = response.getType(); // 文档ID String _id = response.getId(); // 版本 long _version = response.getVersion(); // 返回的操作状态 RestStatus status = response.status(); System.out.println("索引名称:"+_index+" "+"类型 :" + _type + " 文档ID:"+_id+" 版本 :"+_version+" 返回的操作状态:"+status); }
往往生产的需求是能够类似mysql一样,通过查询出符合条件的数据进行删除:
DELETE FROM Employees WHERE ps_code=
(SELECT ps_code 不存在 FROM Employees WHERE ps_code NOT IN `icq_user_info``persons`
(SELECT ps_code FROM Persons));
那么es也是支持这种操作的:DeleteByQueryAction允许检索一个索引,把匹配出来的字段删除
@Test public void queryDeleteDocument(){ BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .filter(QueryBuilders.matchQuery("user", "tom"))//key -- value .source("twitter4")//索引名称 .get(); long deleted = response.getDeleted(); System.out.println("总共删除时间:"+deleted); }
上面的查询删除,在实际的生产中会占用大量的时间,所以为了不阻塞其他的操作,应该把上面的操作变成异步执行方式
/** * 优化--异步的方式执行 * */ @Test public void tuningqueryDeleteDocument(){ DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .filter(QueryBuilders.matchQuery("user", "kimchy")) .source("twitter4") .execute(new ActionListener<BulkByScrollResponse>() { public void onResponse(BulkByScrollResponse response) { long deleted = response.getDeleted(); System.out.println("总共删除时间:"+deleted);//因为是异步执行,所以不会打印 } public void onFailure(Exception e) { System.out.println("程序运行出错"); } }); }