如何使用 Spring-Data-MongoDB 在实体中设置 @TextIndex 名称

2024-03-24

我有一个实体Person,继承于Musician and 政治家和一个存储库 PersonRepository。

我试图使用 PersonRepository.save(..) 默认方法将所有三个实体保存到 MongoDB 中的集合“person”中,但不知何故,Spring-Data-MongoDB 将其保存到 3 个单独的集合“person”、“musician”和“政治家”。

Java代码:

@Document
public class Person {
    @Id private String id;

    @Indexed private String name;

    @TextIndexed private String biography;
}

@Document  
public Musician extends Person {
    private String something;
}

@Document  
public Politician extends Person {
    private String somethingElse;
}

@Repository
public interface PersonRepository extends CrudRepository<User, String> {
}

在阅读了一些帖子后,说我必须将存储库的所有三个实体的集合名称设置到注释 @Document(collection = "person") 中,以将其保存到同一个集合中。

它工作得很好,但是当我检查 MongoDB 中的索引时,不知怎的,我得到了以保存的最后一个实体类命名的 TextIndex。

看来 TextIndex 总是以保存的实体类名称命名,而不是我在文档注释中设置的集合名称。

MongoDB 外壳:

db.person.getIndexes()
[
    {
        "v" : 1,
        "key" : {
                "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.person"
    },
    {
        "v" : 1,
        "key" : {
                "_fts" : "text",
                "_ftsx" : 1
        },
        "name" : "Musician_TextIndex",
        "ns" : "test.person",
        "weights" : {
                "description" : 1,
                "name" : 10
        },
        "default_language" : "english",
        "language_override" : "language",
        "textIndexVersion" : 3
    }
]

有什么方法可以设置 TextIndex 名称,而不是在我保存的实体类之后命名它。尝试搜索可以找到任何。


目前无法设置索引名称TextIndex使用基于注释的设置。为此,请使用IndexOperations通过template手动设置文本索引。

template.indexOps(Person.class)
  .ensureIndex(
     new TextIndexDefinitionBuilder()
       .named("YourIndexNameHere")
       .onField("biography")
       .build());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Spring-Data-MongoDB 在实体中设置 @TextIndex 名称 的相关文章

随机推荐