Update By Query in Elasticsearch using Java

后端 未结 2 1384
-上瘾入骨i
-上瘾入骨i 2020-12-10 06:16

I’m currently using Elasticsearch V2.3.1. I want to use the following Elasticsearch query in Java.

POST /twitter/_update_by_query
{
  \"script\": {
    \"in         


        
相关标签:
2条回答
  • 2020-12-10 07:00

    As of ES 2.3, the update by query feature is available as the REST endpoint _update_by_query but nor for Java clients. In order to call this endpoint from your Java client code, you need to include the reindex module in your pom.xml, like this

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

    Then you need to include this module when building your client:

    clientBuilder.addPlugin(ReindexPlugin.class);
    

    Finally you can call it like this:

    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();
    

    UPDATE

    If you need to specify the type(s) the update should focus on, you can do so:

    ubqrb.source("twitter").source().setTypes("type1");
    BulkIndexByScrollResponse r = ubqrb.script(script)
        .filter(termQuery("user", "kimchy"))
        .get();
    
    0 讨论(0)
  • 2020-12-10 07:00

    In ES 7.9 this also works using 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);
    
    0 讨论(0)
提交回复
热议问题