[英]NPE while executing Update By Query in Elasticsearch using Java
[英]Update By Query in Elasticsearch using Java
我目前使用的是 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”的“user”並使用給定值更新“List”字段。 此查詢同時更新多個文檔。 我在這里閱讀了 Java 的更新 API https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.3/java-docs-update.html但找不到我要找的東西. Java 的更新 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 識別的。 我可以知道我在這里做錯了什么嗎? 謝謝。
從 ES 2.3 開始,按查詢更新功能可用作 REST 端點_update_by_query
但也不適用於 Java 客戶端。 為了從您的 Java 客戶端代碼調用此端點,您需要在 pom.xml 中包含reindex
模塊,如下所示
<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();
在 ES 7.9 中,這也適用於 UpdateByQueryRequest
Map<String, Object> map = new HashMap<String, Object>(); UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest("indexName"); updateByQueryRequest.setConflicts("proceed"); updateByQueryRequest.setQuery(new TermQueryBuilder("_id", documentId)); Script script = new Script(ScriptType.INLINE, "painless", "ctx._source = params", map); updateByQueryRequest.setScript(script);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.