話不多說,直接上代碼:
public boolean createMapNameIndex() {
IndexOptions indexOptions=new IndexOptions();
indexOptions.background(true);
//設置索引名
indexOptions.name("hanhan_index_mapname");
String resultStr=template.getCollection("maps")
.createIndex(new Document("mapname","hashed"),new IndexOptions().background(false).name("hanhan_index_mapname"));
System.out.println("index created");
return true;
}
對上面的參數略作解釋:
indexOptions.name(“hanhan_index_mapname”);:這個裏面設置的是你的索引名。
template.getCollection(“maps”):maps是你數據庫的集合名字。
new Document(“mapname”,“hashed”):對名字爲mapname這個字段創建hashed類型的索引。
代碼實現截圖: