javaelasticsearchspring-data-elasticsearchelasticsearch-template

Delete field in doc using spring esTemplate


I'm trying to use ElasticsearchTemplate to update my es data,code is as follows:

UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index(RiskViewDevStatistics.ESIndex);
            updateRequest.type(RiskViewDevStatistics.ESType);
            try {
                updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                        .field("owner", ownerId)
                        .endObject());
                UpdateQuery updateQuery = new UpdateQueryBuilder().withId("docId")
                        .withClass(RiskViewDevStatistics.class).withUpdateRequest(updateRequest).build();
                esTemplate.update(updateQuery);

The code is similar to :

update owner from xx where id = xx

When the argument ownerId I passed in is null,data in es is :

"hits": {
        "total": 1,
        "max_score": 1.0,
        "hits": [
            {
                "_index": "st-riskview",
                "_type": "riskviewdevstatistics",
                "_id": "AW47Wy7cEY_O-MqaGSGL",
                "_score": 1.0,
                "_source": {
                    "owner": null  // null
                }
            }
        ]
    }

My question is : How to delete this field instead of setting it to null ?

Attention:I don't want to replace total doc.


Solution

  • Try this:

    POST st-riskview/riskviewdevstatistics/AW47Wy7cEY_O-MqaGSGL/_update
    {
      "script" : "ctx._source.remove('owner')"
    }
    

    Spring - not tested

    UpdateRequest updateRequest = new UpdateRequest(RiskViewDevStatistics.ESIndex,RiskViewDevStatistics.ESType,"docid");
    Map<String, Object> parameters = singletonMap("field", "owner");
    Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.remove(params.field)",parameters);  
    updateRequest.script(inline);
    

    Updates with a script