《spring data mongodb index索引實踐》要點:
本文介紹了spring data mongodb index索引實踐,希望對您有用。如果有疑問,可以聯系我們。
相關主題:非關系型數據庫
在spring data mongodb中創建索引也是非常方便的.
直接在對應的實體類中用注解標識即可.
要給某個字段加索引就在字段上面加上@Indexed注解,里面可以填寫對應的參數
像唯一索引的參數就是unique=true,以后臺方式創建索引的參數是background=true.
然后是組合索引的創建,是要在類的上面定義@CompoundIndexes注解,參數是@CompoundIndex注解數組,可以傳多個.
name表示索引的名稱,def表示組合索引的字段和索引存儲升序(1)或者降序(-1).
@Document
@CompoundIndexes({
@CompoundIndex(name = "city_region_idx", def = "{'city': 1, 'region': 1}")
})
public class Person {
private String id;
@Indexed(unique=true)
private String name;
@Indexed(background=true)
private int age;
private String city;
private String region;
}
然后在插入數據的時候,框架會自動根據配置的注解創建對應的索引.
我們可以看下已創建好的索引信息.
> db.person.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "cxytiandi.person"
},
{
"v" : 1,
"key" : {
"city" : 1,
"region" : 1
},
"name" : "city_region_idx",
"ns" : "cxytiandi.person"
},
{
"v" : 1,
"unique" : true,
"key" : {
"name" : 1
},
"name" : "name",
"ns" : "cxytiandi.person"
},
{
"v" : 1,
"key" : {
"age" : 1
},
"name" : "age",
"ns" : "cxytiandi.person",
"background" : true
}
]
>
也可以直接用代碼查看索引信息
mongoTemplate.getCollection("person").getIndexInfo().forEach( index -> {
System.out.println(index);
});
源碼地址:https://github.com/yinjihuan/cxytiandi
《spring data mongodb index索引實踐》是否對您有啟發,歡迎查看更多與《spring data mongodb index索引實踐》相關教程,學精學透。維易PHP學院為您提供精彩教程。