java - 使用 Java 客户端进行 Elasticsearch 查询序列化
问题描述
我正在使用Java 的官方 Elasticsearch客户端。它工作得很好,但不幸的是它的对象没有实现Serializable接口。我特别需要序列化QueryBuilder的实例。
我发现了两种使用客户端序列化对象的方法。其中之一是使用QueryBuilder.writeTo()。另一种是使用:
Strings.toString(queryBuilder.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS))
但是在这两种情况下我都找不到如何反序列化对象。
另外我不确定这是否是解决任务的最佳方法。
解决方案
最后,我得到了以下代码:
序列化:
// 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客户端库实现。
推荐阅读
- oauth-2.0 - 在 Azure API 管理 Oauth2 服务中指定受众参数
- java - 使用 apache http-components 的 DefaultBHttpClientConnection 发送 http 请求
- php - 如何使用 PDO 搜索和显示多个带有连接表的 POST 值?
- javascript - 正则表达式检查字符是否仅出现在字符串的末尾
- python - 如何在plotly python中的烛台图表上添加折线图
- visual-studio-code - 如何删除 VS Code Jupyter Notebook 弃用通知?
- python - 如何将 mm/yy 转换为日期格式?
- vb.net - 如何在不手动将控件添加到表单的情况下使用控件填充 tableLayoutPanel?
- amazon-web-services - 如何将“–kubelet-extra-args”传递给 Terraform aws_eks_node_group 创建的 AWS EKS 节点组?
- c# - 将 .NET 5 库中的 UserControl 加载到 .NET Framework (4.8) 项目中