英文:
Elasticsearch query serialization using Java client
问题
我正在使用官方的Elasticsearch Java客户端。它工作得很好,但不幸的是,它的对象没有实现Serializable接口。我需要序列化QueryBuilder的实例。
我已经发现了两种使用客户端进行对象序列化的方法。其中一种是使用**QueryBuilder.writeTo()**方法。另一种方法是使用以下代码:
Strings.toString(queryBuilder.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS))
但我找不到如何在这两种情况下进行对象反序列化的方法。
此外,我不确定这是否是解决问题的最佳方式。
英文:
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.
答案1
得分: 3
最终,我得到了以下的代码:
序列化:
// 使用源代码包装查询以对任何类型的查询进行反序列化
SearchSourceBuilder query = new SearchSourceBuilder().query(this.query);
String sourceJson = Strings.toString(query);
反序列化:
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();
因此,您可以将此代码添加到 readObject()
和 writeObject()
方法中,以为 ES 查询对象提供序列化和反序列化支持。
使用 Elasticsearch 7.5.1 客户端库实现。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论