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}")

Advertisements

})

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"

Advertisements

},

{

"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

Advertisements

你可能會喜歡