小编典典

使用Java在Elasticsearch中按查询更新

elasticsearch

我目前正在使用Elasticsearch V2.3.1。我想在Java中使用以下Elasticsearch查询。

POST /twitter/_update_by_query
{
  "script": {
    "inline": "ctx._source.List = [‘Item 1’,’Item 2’]”
  },
  "query": {
    "term": {
      "user": "kimchy"
    }
  }
}

上面的查询搜索名为“
kimchy”的“用户”,并使用给定值更新“列表”字段。该查询同时更新多个文档。我在https://www.elastic.co/guide/en/elasticsearch/client/java-
api/2.3/java-docs-
update.html上了解了有关Java的Update API,但找不到我想要的东西。Java的Update
API仅讨论一次更新单个文档。有什么办法可以更新多个文档?抱歉,如果我缺少明显的内容。感谢您的时间。

更新:

我尝试了以下Java代码:

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

UpdateByQueryRequestBuilder ubqrb = UpdateByQueryAction.INSTANCE
    .newRequestBuilder(client);

Script script = new Script("ctx._source.List = [\"Item 1\",\"Item 2\"]");

//termQuery is not recognised by the program
BulkIndexByScrollResponse r = ubqrb.source("twitter").script(script)
    .filter(termQuery("user", "kimchy")).execute().get();

因此,我如上所述编辑了Java程序,而Java不识别termQuery。我可以知道我在做什么错吗?谢谢。


阅读 1080

收藏
2020-06-22

共1个答案

小编典典

从ES
2.3开始,按查询更新功能可用作REST端点,_update_by_query但不适用于Java客户端。为了从Java客户端代码中调用该端点,您需要reindex在pom.xml中包含该模块,如下所示

<dependency>
    <groupId>org.elasticsearch.module</groupId>
    <artifactId>reindex</artifactId>
    <version>2.3.2</version>
</dependency>

然后,在构建客户端时需要包括以下模块:

clientBuilder.addPlugin(ReindexPlugin.class);

最后,您可以这样称呼它:

UpdateByQueryRequestBuilder ubqrb = UpdateByQueryAction.INSTANCE.newRequestBuilder(client);

Script script = new Script("ctx._source.List = [\"Item 1\",\"Item 2\"]");

BulkIndexByScrollResponse r = ubqrb.source("twitter")
    .script(script)
    .filter(termQuery("user", "kimchy"))
    .get();

更新

如果您需要指定更新应关注的类型,则可以执行以下操作:

ubqrb.source("twitter").source().setTypes("type1");
BulkIndexByScrollResponse r = ubqrb.script(script)
    .filter(termQuery("user", "kimchy"))
    .get();
2020-06-22