Elasticsearch 2.0: how to delete by query in Java

若如初见. 提交于 2019-12-04 04:58:54

I believe you can use this:

     DeleteByQueryResponse rsp = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
            .setTypes("mydocytype")
            .setSource(b.toString())
            .execute()
            .actionGet();

You have to add plugin type to your settings:

     Settings settings = Settings.settingsBuilder()
                         .put("plugin.types", DeleteByQueryPlugin.class.getName())

If you have remote server you have to install the plugin.

plugin.types have been deprecated in ES 2.1.0 (source). So the accepted solution will result in a NullPointerException.

The solution is to use the addPlugin method:

Client client = TransportClient.builder().settings(settings())
                .addPlugin(DeleteByQueryPlugin.class)
                .build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host",9300));

From Elastic 5 in onwards...

final BulkIndexByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(super.transportClient)
                    .filter(
                            QueryBuilders.boolQuery()
                                    .must(QueryBuilders.termQuery("_type", "MY_TYPE")) // Trick to define and ensure the type.
                                    .must(QueryBuilders.termQuery("...", "...")))
                    .source("MY_INDEX")
                    .get();

    return response.getDeleted() > 0;

Oficial documentation

firstly: add elasticsearch-2.3.3/plugins/delete-by-query/delete-by-query-2.3.3.jar to build path.

then:

Client client = TransportClient.builder().settings(settings)
                .addPlugin(DeleteByQueryPlugin.class)
                .build()
                .addTransportAddress(new InetSocketTransportAddress(
                        InetAddress.getByName("192.168.0.224"), 9300));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!