Reputation: 1
I have a requirement where I need to update a field in elastic search for multiple ids. Currently I am using XcontentBuilder and passing an Id along with field name but it's a for loop that's why time complexity becomes horrible if I pass multiple Ids. Is there a way where I can do same operation in batches?
My Code is like this:
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("_doc");
updateRequest.id("1");
updateRequest.doc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject());
client.update(updateRequest).get();
Id is a dynamic field and for each Id I am running a loop using above code.
Upvotes: 0
Views: 988
Reputation: 807
I have not tested this but you can check If this can be of any help
Option 1:
List<String> ids = new ArrayList<>();
ids.add("1");
ids.add("2");
for (String id : ids) {
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("_doc");
updateRequest.id("1");
updateRequest.doc(jsonBuilder().startObject().field("gender", "male").endObject());
bulkRequest.add(updateRequest);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
Option 2: Using Script
List<String> ids = new ArrayList<>();
ids.add("1");
ids.add("2");
Map<String, Object> params = new HashMap<>();
String scriptCode = "ctx._source.gender=params.gender";
params.put("gender", "male");
BulkRequestBuilder bulkRequest = client.prepareBulk();
for(String id : ids) {
UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate("index", "type", id)
.setScript(new Script(ScriptType.INLINE, "painless", scriptCode, params));
bulkRequest.add(updateRequestBuilder);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
Upvotes: 0