如何在Spring或Spring Boot中编程创建MongoDB复合索引?

5

如何在Java中使用Spring Data以编程方式创建MongoDB组合索引?

使用MongoTemplate,可以像这样创建索引:

mongoTemplate.indexOps(“collectionName”). ensureIndex(new Index()。 on(“fieldName”,Sort.Direction.DESC))

是否有一种方法来创建复合键?

我看到有一个名为CompoundIndexDefinition的类似乎可以做到这一点,但我无法让它工作。

3个回答

9

您可以按以下方式在Java中以编程方式使用Spring Data在任何集合上创建复合索引:

// Compound indexes on the fields: fieldOne & fieldTwo
// db.groups.createIndex({fieldOne:1, fieldTwo:1})
IndexDefinition index =
    new CompoundIndexDefinition(new Document().append("fieldOne", 1).append("fieldTwo", 1));
mongoTemplate.indexOps(CollectionName.class).ensureIndex(index);

以上示例将创建与mongo shell上相同的索引:
db.groups.createIndex({fieldOne:1, fieldTwo:1})

这个有效。谢谢你。但是你能告诉我如何创建一个由一个文本索引和另一个非文本索引组成的复合索引吗?bson文档的追加方法只接受1或-1。它不接受“text”。你能帮忙吗? - Ann

5
使用Spring Data,您可以使用MongoTemplate或MongoOperations编程方式创建索引。
    mongoTemplate.indexOps(CollectionName.class)
            .ensureIndex(new Index().on("fieldOne", Sort.Direction.DESC)
                    .on("fieldTwo", Sort.Direction.ASC));
    mongoOperations.indexOps(CollectionName.class)
            .ensureIndex(new Index().on("fieldOne", Sort.Direction.DESC)
                    .on("fieldTwo", Sort.Direction.ASC));

这应该是最习惯化的方法,因此应该成为首选答案来完成此任务。 - Stefano L

1

我认为这是更合适的方法。

@CompoundIndexes({
@CompoundIndex(name = "customIndex", def = "{'fieldOne' : 1, 'fieldTwo': 1}")
})
public class Entity {}

在Spring Boot JPA Mongo Repository中。

它不起作用,我尝试了我的项目,但是在我检查后它没有在数据库中创建索引,你确定它有效吗? - user16486258
是的,我很确定,因为我在我的项目中使用了同样的方法,而且它起作用了。 - Jayesh Choudhary
我认为这取决于项目中使用的Spring Data Mongodb版本,从3.0开始,默认情况下关闭了自动索引创建。您可以通过配置spring.data.mongodb.auto-index-creation=true来启用它。 - Mirko Perillo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接