首页 > 解决方案 > 如何在 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 中排除的字段)

非常感谢

标签: springmongodbelasticsearchspring-data

解决方案


假设: ObjectMapper 用于序列化/反序列化

我的问题是:我可以使用什么注释仅从 Elastic Search 中排除字段并将其保留在 Mongo 中?我不想重写该类,因为我没有要存储的“平面”结构(主类由其他类的字段组成,它们本身具有我想从 Elastic 中排除的字段)

  1. 请理解这是选择性序列化的问题。
  2. 可以使用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));

推荐阅读