如何索引 spring 数据 mongodb 中的所有字段?

How to index on all fields in spring data mongodb?

假设我有一些名为 candidates 的集合。我想在此集合中的所有字段上创建一个 text 索引。在mongo,我知道我可以这样做

db.candidates.createIndex({"$**":"text"},{name:"TextIndex"}) 

这是我的 java pojo 或实体。

@Document(collection = "candidates")
public class Candidate {

    @Id
    private String id;
    private String firstName;
    private String lastName;

   // Other stuff: removed for brevity
}

现在如何在 java 中 db.candidates.createIndex({"$**":"text"},{name:"TextIndex"})?那就是我如何为整个 pojo 建立索引或者如何为我的集合中的所有字段建立索引?

This question 试图做同样的事情,但没有完整的细节。

我还查看了 @Indexed 注释,但是我如何使用它来索引整个集合,因为它只能应用于一个字段?

使用@TextIndexed,您至少可以为要包含在索引中的所有字段建立索引。 https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/index/TextIndexed.html

您也可以为此使用 mongotemplate。 How to set @TextIndex name in an entity with Spring-Data-MongoDB