直接上代碼
@Entity
public class Product {
@Id
private ObjectId id;
@Indexed(value=IndexDirection.ASC, name="upc", unique=true, dropDups=true)
private String upcSymbol;
...
}
看到了嗎?就是看這個啦。
@Indexed(value=IndexDirection.ASC, name="upc", unique=true, dropDups=true)
參數說明:
value: 索引的方向。 IndexDirection.ASC(升序),IndexDirection.DESC(降序), IndexDirection.BOTH(兩者) ,默認爲 升序;
name: 被創建的索引的 名稱。 mongodb默認創建的名稱格式爲:key1_1/-1_key2_1/-1...
unique: 是否唯一索引。true:爲唯一索引;false:不是唯一索引。默認爲:false
dropDups:當某個字段創建唯一索引時,刪除其他相同值的記錄,只保留第一條記錄。true:刪除重複。false:不刪除重複,但是如果有重複值時,唯一索引創建失敗;默認爲false.
想創建複合索引?直接上代碼
@Entity
@Indexes(@Index(name = "a_b", value = "a, -b"))
public class TestClass
{
@Property("a")
private int fieldA;
@Property("b")
private int fieldB;
//how to annotate index of compound key fieldA and fieldB using morphia index annotation?
}
a,就是按升序排列,-b,就是降序排列。(這個複合索引。。。嗎啡的wiki竟然沒寫。。。。)
向Morphia註冊你的實體類,再調用 Datastore.ensureIndexes() 使你的索引生效。
當在系統上,重複做這個操作,不會耗費時間,也不會做任何事情。
Morphia m = ...
Datastore ds = ...
m.map(Product.class);
ds.ensureIndexes(); //creates all defined with @Indexed