3

I'm using official Elasticsearch client for Java. It works nice, but unfortunately its objects do not implement Serializable interface. I need to serialize instance of QueryBuilder in particular.

I've discovered two ways of serializing objects using the client. One of them is to use QueryBuilder.writeTo(). The other one is to use:

Strings.toString(queryBuilder.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS))

But I cannot find how to deserialize object in both cases.

Also I'm not sure whether it is a best way of solving the task.

3
  • Why exactly do you want to do that? Commented Sep 17, 2020 at 13:49
  • 1
    @GhostCat I need it to pull data from ES into Apache Flink nodes using sliced scroll - it requires serializable queries. Commented Sep 18, 2020 at 7:54
  • My usecase is to cache ES-queries that are generated with quite some effort. Commented Dec 10, 2021 at 22:12

1 Answer 1

3

Finally, I ended up with the following code:

Serialization:

// wrap query with source to deserialize any type of query
SearchSourceBuilder query = new SearchSourceBuilder().query(this.query);

String sourceJson = Strings.toString(query);

Deserialization:

private static final NamedXContentRegistry xContentRegistry;

static {
    SearchModule searchModule =
        new SearchModule(Settings.EMPTY, false, Collections.emptyList());

    xContentRegistry =
        new NamedXContentRegistry(searchModule.getNamedXContents());
}

...

XContentParser parser =
        XContentType.JSON.xContent().createParser(xContentRegistry,
                                                  LoggingDeprecationHandler.INSTANCE,
                                                  sourceJson);

SearchSourceBuilder sourceBuilder = SearchSourceBuilder.fromXContent(parser);

this.query = sourceBuilder.query();

So, you can add this code to readObject() and writeObject() methods to provide (de-)serialization for ES query object.

Implemented using Elasticsearch 7.5.1 client library.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. You can also avoid the detour over SearchSourceBuilder and use AbstractQueryBuilder.parseInnerQueryBuilder(parser) for deserialization.

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.