java程序中增加mongodb的联合索引
早期,增加mongo索引,我只了解这一种
@Indexed private String docId;
这种不是联合索引。当时不了解其它方式,只想到一个办法,在服务启动后,判断是否含XX联合索引,没的话创建
1 @Component 2 @Slf4j 3 public class MongoInit implements ApplicationRunner { 4 @Resource 5 protected MongoOperations mongoOperations; 6 7 @Override 8 public void run(ApplicationArguments args) throws Exception { 9 try { 10 checkCollectionName(); 11 checkCollectionIndex(); 12 } catch (Exception e) { 13 log.error("索引插入异常, e:{}", e); 14 } 15 } 16 17 /** 18 * 检查集合是否存在,不存在则创建 19 */ 20 private void checkCollectionName() { 21 String collectionNameLib = "doc_lib"; 22 if (!mongoOperations.collectionExists(collectionNameLib)) { 23 mongoOperations.createCollection(collectionNameLib); 24 } 25 } 26 27 private void checkCollectionIndex() { 28 addIndexForLib(); 29 } 30 31 public void addIndexForLib() { 32 try { 33 IndexOperations indexOps = mongoOperations.indexOps("doc_lib"); 34 List<IndexInfo> indexInfo = indexOps.getIndexInfo(); 35 List<String> indexNames = indexInfo.stream().map(IndexInfo::getName).collect(Collectors.toList()); 36 37 if (!indexNames.contains("tenantId_account_label_orgCode")) { 38 Map<String, Object> map = new HashMap<>(); 39 map.put("tenantId", 1); 40 map.put("created_by", 1); 41 map.put("label", 1); 42 map.put("orgCode", 1); 43 indexOps.ensureIndex(new CompoundIndexDefinition(new Document(map)).background()); 44 indexSleep(); 45 } 46 } catch (Exception e) { 47 log.error("lib索引插入异常, e:{}", e); 48 } 49 } 50 } 51
再后来,我得知了更优雅的方式:
spring: data: mongodb: uri: xxxx database: xxx auto-index-creation: true
@Document(collection = "emb_data") @CompoundIndexes({ @CompoundIndex(name = "task_knowledge_manualMark", def = "{'taskId': 1, 'knowledgeId': 1, 'manualMark': 1}") }) @Accessors(chain = true) public class EmbData extends AbstractAuditingEntity {
这样做在项目启动后,就可以加入联合索引了,哪怕表已经创建了也是没问题的。

mongodb中已存在了这个联合索引

浙公网安备 33010602011771号