0

I hava a document in Elasticsearch:

{
  "_index": "test",
  "_type": "document",
  "_id": "1",
  "_score": 1,
  "_source": {
      "class": "aaa",
      "id": 1,
      "items": [{
          "class": "aaa",
          "id": 1
      }, {
          "class": "ccc",
          "id": 2
      }],
      "bianhao": "123"
  } 
}

I want to replace {"class": "ccc","id": 2} of items with {"class": "ccc12","id": 2},how to achieve that?

1 Answer 1

1

You can do it like this:

Map<String, Object> params = new HashMap<>();
params.put("idParam", 2);
params.put("classParam", "ccc12");

client.prepareUpdate("test", "document", "1")
    .setScript(new Script(
            "ctx._source.items.find{ it.id == idParam }['class'] = classParam",
            ScriptService.ScriptType.INLINE, null, params))
    .get();

UPDATE

And if you want to change multiple fields, you can do it like this:

Map<String, Object> params = new HashMap<>();
params.put("idParam", 2);
params.put("classParam", "ccc12");
params.put("field1Param", "value2");
params.put("field2Param", "value3");

client.prepareUpdate("test", "document", "1")
    .setScript(new Script(
            "def item = ctx._source.items.find{ it.id == idParam}; if (item) {item['class'] = classParam; item['field1'] = field1Param; item['field2'] = field2Param}",
            ScriptService.ScriptType.INLINE, null, params))
    .get();
Sign up to request clarification or add additional context in comments.

3 Comments

In this case,firstly find 'id' then set value to 'class'.I mean if there are many fields,{"id": 2,"class":"ccc","name":"dddd","field1":"value1","field1":"value2"},how to replace them once?
Do you want to change multiple fields?
This problem has been bothering me for serval days.Can you help me out ?@Val stackoverflow.com/questions/38886939/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.