问题描述:spring boot + spring data MongoDB 项目中使用@CompoundIndex注解来生成MongoDB索引,但是项目启动后未生效
注解示例代码如下:
@Data
@Document("category")
@CompoundIndexes({
@CompoundIndex(name = "cid_category_idx", def = "{'cid': 1, 'category': 1}", unique = true)
})
public class Category {
@Id
private String id;
private String cid;
private Boolean isLeaf;
private String category;
private Instant createdTime;
private Instant updatedTime;
}
解决方案:
在配置文件中增加:-index-creation: true
注意:该注解在第一次生成表的时候生效,如果表已经存在,需要删除表重新生成。故该策略适用于新建表时使用。
关于MongoDB索引维护的方法总结:
1、新建表时, 通过在实体类上增加@CompoundIndex注解或者实体成员变量上添加@index注解
2、如果需要给已经存在的表建立索引可通过 ().ensureIndex(index) ;
参考代码:
public void init() {
Index index = new Index();
("property", );
("option", );
("optionDisplayName", );
(); //声明唯一性,非必须
().ensureIndex(index);
}
3、直接在MongoDB shell中通过SQL的形式创建,比如({brand:1 , model:1 , colour:1 ,fuelTypes:1},{unique:true})