【问题标题】:Elasticsearch query serialization using Java client使用 Java 客户端进行 Elasticsearch 查询序列化
【发布时间】:2021-01-03 12:27:39
【问题描述】:

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

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

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

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

我也不确定这是否是解决任务的最佳方式

【问题讨论】:

  • 你到底为什么要这么做?
  • @GhostCat 我需要它使用切片滚动将数据从 ES 拉入 Apache Flink 节点 - 它需要可序列化的查询。
  • 我的用例是缓存 ES 查询,这些查询是通过相当大的努力生成的。

标签: java elasticsearch serialization


【解决方案1】:

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

序列化:

// 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 客户端库实现。

【讨论】:

  • 像魅力一样工作。你也可以避免绕过 SearchSourceBuilder 并使用AbstractQueryBuilder.parseInnerQueryBuilder(parser) 进行反序列化。
猜你喜欢
  • 2011-12-12
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 2014-09-02
  • 2013-04-26
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多