How to serialize elastic4s queries for reuse?

I'm using elastic4s to query elastic search, and now I need to cache this query to be used later for pagination purposes.

The query built process is a heavy calculation that is why I need the final query it self save in some local cache (i.e redis) to be retrieved and used later.

The problem I'm facing is, how to serialize or convert to string this query in a way that I can later deserialize and reuse.

Currently this is the approach I'm using:


var searchDefinition ="$indexName/$docType").query2(buildQuery), searchDefinition._builder.toString)


val cachedQuery = Cache.restore(key)
val searchDefinition ="$indexName/$docType")

The problem is:

Query rebuilt after restored from cache is broken. How it looks like:

Query: {
    "from" : 0,
    "size" : 20,
        "query" : {
            "function_score" : {

Note the double "query" tag.

So as it is not so clear in documentation, does anybody has a thought to work it around?

PS: I've posted in StackOverflow as well:


Finally discover the problem. Query returned by


return as well the key:

"query" : {

I could manage to solve the problem sanitizing the query string by removing the extra query string manually and then call:

val cachedQuery = Cache.restore(key)"$indexName/$docType").rawQuery(cachedQuery)

Worked like a charm!