spring - 如何在 Spring 中的 Mongo 和 Elastic Search 之间共享的实体中使用像 @Transient 这样的通用注释?
问题描述
我正在使用 Spring Boot 并在 Elastic Search 数据库和 MongoDB 数据库之间共享相同的实体。实体以这种方式声明:
@Document
@org.springframework.data.elasticsearch.annotations.Document(indexName = "...", type = "...", createIndex = true)
public class ProcedureStep {
...
}
这个包@Document
的来源:org.springframework.data.mongodb.core.mapping.Document
这没有任何问题,但我不能使用通用注释来定位弹性搜索。例如:
@Transient
private List<Point3d> c1s, c2s, c3s, c4s;
这将从 Mongo 和 Elastic 这两个数据库中排除该字段,而我的意图是将其仅应用于 Elastic Search。
我在使用这样的 Elastic 特定注释时没有问题:
@Field(type = FieldType.Keyword)
private String studyDescription;
我的问题是:我可以使用什么注释仅从 Elastic Search 中排除字段并将其保留在 Mongo 中?我不想重写该类,因为我没有要存储的“平面”结构(主类由其他类的字段组成,它们本身具有我想从 Elastic 中排除的字段)
非常感谢
解决方案
假设: ObjectMapper 用于序列化/反序列化
我的问题是:我可以使用什么注释仅从 Elastic Search 中排除字段并将其保留在 Mongo 中?我不想重写该类,因为我没有要存储的“平面”结构(主类由其他类的字段组成,它们本身具有我想从 Elastic 中排除的字段)
- 请理解这是选择性序列化的问题。
- 可以使用JsonViews来实现。
例子:
Step1:定义2个视图,ES Specific & MongoSpecific。
class Views {
public static class MONGO {};
public static class ES {};
}
步骤2:注释字段如下。描述为评论:
@Data
class Product {
private int id; // <======= Serialized for both DB & ES Context
@JsonView(Views.ES.class) //<======= Serialized for ES Context only
private float price;
@JsonView(Views.MONGO.class) // <======= Serialized for MONGO Context only
private String desc;
}
第 3 步:
为 Spring-Data-ES 和 Mongo 配置不同的对象映射器。
// Set View for MONGO
ObjectMapper mapper = new ObjectMapper();
mapper.setConfig(mapper.getSerializationConfig().withView(Views.MONGO.class));
// Set View for ES
ObjectMapper mapper = new ObjectMapper();
mapper.setConfig(mapper.getSerializationConfig().withView(Views.ES.class));
推荐阅读
- java - Android Java 将视频从 url 保存到图库 API 19-30
- php - 如何在屏幕上显示图像它不起作用我认为我无法在 img 标签中找到正确的路径请指导我应该在其中做什么?
- regex - 匹配以 32 个字符结尾的 URL 上的正则表达式
- dynamics-365 - 在记录创建规则期间防止重复联系
- dataframe - 转换数据框中的数据类型
- powerbi - PowerBI DAX,通过在维度表中查找来计算
- mysql - 避免在数据库迁移过程中出现错误超出范围的 SQL
- flutter - 在 Flutter 中使用正则表达式验证 URL,而不需要它
- node.js - 如何使用 axios 对 keycloak 进行身份验证?
- c - 如何将一个 16 位数字分解为两个 8 位数字?