首页 > 解决方案 > 使用 Java 客户端进行 Elasticsearch 查询序列化

问题描述

我正在使用Java 的官方 Elasticsearch客户端。它工作得很好,但不幸的是它的对象没有实现Serializable接口。我特别需要序列化​​QueryBuilder的实例。

我发现了两种使用客户端序列化对象的方法。其中之一是使用QueryBuilder.writeTo()。另一种是使用:

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

但是在这两种情况下我都找不到如何反序列化对象。

另外我不确定这是否是解决任务的最佳方法

标签: javaelasticsearchserialization

解决方案


最后,我得到了以下代码:

序列化:

// wrap query with source to deserialize any type of query
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客户端库实现。


推荐阅读