Reputation: 1472
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.
Upvotes: 3
Views: 1929
Reputation: 1472
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.
Upvotes: 3