Filtering Nested Array Objects in Elasticsearch Document with Painless Scripting

Painless is a simple, secure scripting language designed specifically for use with Elasticsearch. It is the default scripting language for Elasticsearch and can safely be used for inline and stored scripts.

https://bit.ly/2TRuUNj

Sharing is caring!

Overview

I have been using Elasticsearch for a while. Starting as a log aggregations for microservices (ELK stack) and progressing towards as a document searching functionalities. Because the usages are advancing, therefore the demand for searching criteria is increasing as well. Of course, as a consequence, the searching requirement is getting complex. Luckily, Elasticsearch has one of the most powerful features, which is painless scripting.

Also, the demands are growing to Kibana as reporting and monitoring tools as well.

Use Case

I want to search for a product in which stocks are less than or equal to 50. This is the product document looks like:

Index Creation

First, I will create a new index and give it a name: product.

Prepare Document

Insert documents with BULK API

Searching with Painless

It is time to searching with painless scripting. Syntax over words.

You will get results such as:

Of course, you can play around by changing the limit, or combining with other filters. It is up to you. You have total control over your search queries.

Conclusion

I find this painless scripting approach in this article is similar to the EXISTS clause in traditional SQL language. To be honest, the SQL query is still a more elegant abstraction language compare to the JSON approach query language. However, in the end, it is about functionalities. As long as it works perfectly well, we can put aside the elegance aspect.

And lots more functionalities come with this feature. One of the lovely ones is debugging features. If you are curious to know more, please visit this link.

References

Author: ru rocker

I am a professional software developer with more than 10 years experiences. I am a certified Java Developer (SCJP and SCWCD). However, In the recent months, I have more interest in DevOps and start to become a polyglot developer. Python and Go-lang become my favorite programming languages besides Java.

Leave a Reply

Your email address will not be published. Required fields are marked *