为不同集合中的子文档和父文档中的相同字段独立定义索引

Defining indices independently for same field in child and parent documents in different collections

我有两个 class 是这样的:

@Document(collection = 'rule')
class Rule {
    @Indexed(unique = true)
    String name
}

@Document(collection = 'archived_rule')
class ArchivedRule extends Rule {
    @Indexed(unique = false)
    String name
}

规则是我的应用程序使用的主域 class。 'rule' 集合中仅存储每个规则的最新版本。更新规则时,会制作一份副本并将其保存在 'archived_rule' 集合中。

名称字段在 'rule' 集合中应该是唯一的。它应该能够在 'archived_rule' 集合中有重复项。

像上面那样定义我的 classes 似乎不起作用。当我启动我的应用程序时,出现如下异常:

Caused by: org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both @org.springframework.data.mongodb.core.index.Indexed(expireAfterSeconds=-1, dropDups=false, sparse=false, useGeneratedName=false, background=false, unique=true, name=, collection=, direction=ASCENDING) private java.lang.String ...Rule.name and @org.springframework.data.mongodb.core.index.Indexed(expireAfterSeconds=-1, dropDups=false, sparse=false, useGeneratedName=false, background=false, unique=false, name=, collection=, direction=ASCENDING) private java.lang.String ...ArchivedRule.name map to the same field name name! Disambiguate using @Field annotation!

我也试过在 ArchivedRule class 中根本不指定名称字段,但在这种情况下,它会在 'archived_rule' 集合中的 'name' 字段上创建一个唯一索引.

我想过我可以通过继承让Rule和ArchivedRule不相关,然后在ArchivedRule中显式地重新定义我需要从Rule中保存的所有字段。不过,我想避免这样做。

是否有其他方法可以指定我的 classes,以便 Rule.name 具有唯一索引而 ArchivedRule.name 没有唯一索引?

我能够通过添加一个抽象基础 class 来解决这个问题,其中共享字段不是 Rule 和 ArchivedRule 的扩展名。然后他们各自使用适当的索引配置定义自己的名称版本。

class RuleBase {
    String sharedField
}

@Document(collection = 'rule')
class Rule extends RuleBase {
    @Indexed(unique = true)
    String name
}

@Document(collection = 'archived_rule')
class ArchivedRule extends RuleBase {
    @Indexed(unique = false)
    String name
}