《spring data mongodb index索引實(shí)踐》要點(diǎn):
本文介紹了spring data mongodb index索引實(shí)踐,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
相關(guān)主題:非關(guān)系型數(shù)據(jù)庫
在spring data mongodb中創(chuàng)建索引也是非常方便的.
直接在對(duì)應(yīng)的實(shí)體類中用注解標(biāo)識(shí)即可.
要給某個(gè)字段加索引就在字段上面加上@Indexed注解,里面可以填寫對(duì)應(yīng)的參數(shù)
像唯一索引的參數(shù)就是unique=true,以后臺(tái)方式創(chuàng)建索引的參數(shù)是background=true.
然后是組合索引的創(chuàng)建,是要在類的上面定義@CompoundIndexes注解,參數(shù)是@CompoundIndex注解數(shù)組,可以傳多個(gè).
name表示索引的名稱,def表示組合索引的字段和索引存儲(chǔ)升序(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;
}
然后在插入數(shù)據(jù)的時(shí)候,框架會(huì)自動(dòng)根據(jù)配置的注解創(chuàng)建對(duì)應(yīng)的索引.
我們可以看下已創(chuàng)建好的索引信息.
> 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索引實(shí)踐》是否對(duì)您有啟發(fā),歡迎查看更多與《spring data mongodb index索引實(shí)踐》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/10166.html