Spring Boot and Elasticsearch — Update Documents with Scripting
Write Painless Scripts to Update Documents in ElasticSearch
Elasticsearch Scripting and Painless:
You can use a script to calculate values (a custom score, etc.) over fields and return this value. The default language for scripting in ES is Painless (with a syntax similar to Java) and it was built for ES (you can also use different languages for scripts with their specific plugins). The scripts written with Painless are compiled directly into Java Virtual Machine (JVM) byte code and executed against a standard JVM.
You can read more about scripting and Painless in their official documentation:
You can also update documents in ES with scripts as described here:
Spring Boot Implementation
Now, I will share my implementation in my Spring Boot project.
The requirement was when an account’s subscription was cancelled or updated, I had to update the expirationDate in the documents by calculating the remaining days until the new end date (for the subscription) plus additional days value.
Firstly, I created a response class for bulk operations in ES.
@Getter
@Setter
@AllArgsConstructor
public class BulkProcessMailItemsResponse {
private Long totalDocs;
private Long durationInMiliseconds;
}
This is my service implementation:
You can see the calculation in “prepareUpdateScript” method. “ttlInDays” is our parameter for the script here.
Since this is a bulk operation, total updated documents count and total duration for the update process will be returned in the custom response class we defined earlier.
References:
https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-painless.html
https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-lang-spec.html
https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-using.html
Happy Coding!