如何 使用 mongoTemplate 对 mongo 表 建普通索引,复合索引,唯一索引,设置分片

446 阅读1分钟

使用 mongoTemplate 对 mongo 表 进行分区设置

因为需求场景要求页面创建数据的时候,代码创建对应的mongo表,同时还要设置给创建的表建索引和 分片键。需要通过MongoTemplate来完成这些语句。用Mongo原生语句倒是知道怎么使用了。用如下:

db.t_sku_strategy_relation.ensureIndex({"strategy_relation.relation_time":-1});
db.shardCollection('shard_test',{'name':1})

mongoTemplate 怎么完成建普通索引,这个百度马上就能找到

IndexOperations indexOps = mongoTemplate.indexOps(shardCollectionName);
Index sourceIdIndex2 = new Index().named(shardCollectionName + "." + shardColumnName)
        .on(shardColumnName, Sort.Direction.ASC);
indexOps.ensureIndex(sourceIdIndex2);

mongoTemplate 建复合索引,这个百度也能很快查询

IndexOperations indexOps = mongoTemplate.indexOps(shardCollectionName);
Document document = new Document();
document.put(StrategySourceDO.SOURCE_ID, 1);
document.put(StrategySourceDO.VERSION, 1);
String underline = "-";
Index sourceIdIndex = new CompoundIndexDefinition(document)
       .named(StrategySourceDO.SOURCE_ID + underline + 1 + StrategySourceDO.VERSION + 1);
indexOps.ensureIndex(sourceIdIndex);

mongoTemplate 建唯一索引,这个百度也能很快查询,和普通索引差别不大

IndexOperations indexOps = mongoTemplate.indexOps(shardCollectionName);
Index sourceIdIndex2 = new Index().named(shardCollectionName + "." + shardColumnName)
.unique();
indexOps.ensureIndex(sourceIdIndex2);

## mongoTemplate 设置分片键 这个就很难百度了,几乎没有。

// 要获取 admin库,这里没有写 启用某个Mongo库的分片支持(enableSharding),这个最好提前数据库设置好,代码里面不再重复设置
MongoDatabase database = mongoTemplate.getMongoDatabaseFactory().getMongoDatabase("admin");
// 给对于表设置分片键,我这里使用了hash索引,也可以设置普通索引,分片键怎么选择也有讲究,大家可以百度
Document document = new Document(shardColumnName, hashed);
Index sourceIdIndex2 = new CompoundIndexDefinition(document)
        .named(shardColumnName + "_" + hashed);
indexOps.ensureIndex(sourceIdIndex2);
Document shardCmd = new Document("shardCollection", javaMongoDbName + "." + shardCollectionName).append("key", document);
database.runCommand(shardCmd);

解决过程,我是百度了多次找不到案例,就去官方文档里面搜索,才找到了解决办法,这里贴出来,希望可以帮助到有需要的小伙伴。

docs.spring.io/spring-data…

image.png