spring boot mongo java 动态创建索引

朴灿烈づ我的快乐病毒、 2023-07-25 11:15 48阅读 0赞

基于 org.springframework.data.mongodb. 的动态索引管理

可以在代码中实现 对索引的增删改查

支持组合索引

  1. @Autowired
  2. private MongoTemplate mongoTemplate;
  3. /**
  4. * 创建联合索引
  5. *
  6. * @param index_key 索引的名称
  7. * @param index_key2 索引的名称
  8. * @param collectionName 集合名称
  9. * @return
  10. */
  11. public boolean createInboxIndex(String index_key, String index_key2, String collectionName) {
  12. boolean scuess = true;
  13. try {
  14. Index index = new Index();
  15. index.on(index_key, Sort.Direction.ASC).on(index_key2, Sort.Direction.ASC);
  16. mongoTemplate.indexOps(collectionName).ensureIndex(index);
  17. } catch (Exception ex) {
  18. scuess = false;
  19. }
  20. return scuess;
  21. }
  22. /**
  23. * 创建单个索引
  24. *
  25. * @param index_key 索引的名称
  26. * @param collectionName 集合名称
  27. * @return
  28. */
  29. public boolean createInboxIndex(String index_key, String collectionName) {
  30. boolean scuess = true;
  31. try {
  32. Index index = new Index();
  33. index.on(index_key, Sort.Direction.ASC);
  34. mongoTemplate.indexOps(collectionName).ensureIndex(index);
  35. } catch (Exception ex) {
  36. scuess = false;
  37. }
  38. return scuess;
  39. }
  40. /**
  41. * 获取索引
  42. *
  43. * @return
  44. */
  45. public List<IndexInfo> getInboxIndex() {
  46. List<IndexInfo> indexInfoList = mongoTemplate.indexOps(Stats.class).getIndexInfo();
  47. for (IndexInfo indexInfo : indexInfoList) {
  48. String name = indexInfo.getName();
  49. // 不需要的就删除
  50. if(name.equals("delete")){
  51. // deleteInboxIndex(indexInfo.getName()); // 原
  52. deleteInboxIndex(indexInfo.getName(),"tb_stats"); // 修改
  53. }
  54. }
  55. return indexInfoList;
  56. }
  57. /**
  58. * 删除索引
  59. *
  60. * @param indexName 索引的名称
  61. * @param collectionName 集合名称
  62. * @return
  63. */
  64. public boolean deleteInboxIndex(String indexName, String collectionName) {
  65. boolean scuess = true;
  66. try {
  67. mongoTemplate.indexOps(collectionName).dropIndex(indexName);
  68. } catch (Exception ex) {
  69. scuess = false;
  70. }
  71. return scuess;
  72. }

发表评论

表情:
评论列表 (有 0 条评论,48人围观)

还没有评论,来说两句吧...

相关阅读

    相关 mongo索引

    本文主要介绍mongo的索引 索引的作用 索引的类型 索引的注意事项 索引的创建管理 索引的作用 索引的作用是在进行查询的时候,首先会去