Search code examples
elasticsearchelasticsearch-java-api

Elasticsearch update the whole `_source` field based on search query


"_source": {
         "id": "5b1676493d21784208c36041",
         "label": "name",
         "properties": {
           "name": "patrick"
         },
         "updatedAt": 1528259039542
       }

I want to update this document based on id (not _id) with a new document.

Something like this:

    "_source": {
             "dataSource": "ELASTIC",
             "entity": "vertices",
             "label": "vertices",
             "id": "5b1676493d21784208c36041",
             "properties": {
                     "name": "patrick"
                  },
             "updatedAt": 1528259039542
           }

elasticsearch version: 6.2, ES Java api: 6.2


Solution

  • You can achieve what you want using the update by query API, basically like this:

    POST index/_update_by_query
    {
      "query": {
        "match": {
          "id": "5b1676493d21784208c36041"
        }
      },
      "script": {
        "source": "ctx._source = params",
        "params": {
           "dataSource": "ELASTIC",
           "entity": "vertices",
           "label": "vertices"
        }
      }
    }
    

    UPDATE: Using the Java API

    Map<String, String> params = new HashMap<>();
    params.put("dataSource", "ELASTIC");
    params.put("entity", "vertices");
    params.put("label", "vertices");
    
    UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(client);
    updateByQuery.source("index")
        .filter(QueryBuilders.matchQuery("id", "5b1676493d21784208c36041"))
        .size(1000)
        .script(new Script(ScriptType.INLINE, "painless", "ctx._source.putAll(params)", params));
    BulkByScrollResponse response = updateByQuery.get();
    

    More details on using the UpdateByQuery Java API and Java high level rest client