zoukankan      html  css  js  c++  java
  • 利用java代码给mongo数据库加索引、删除索引等操作

    网上搜了一下相关代码,不是互相抄瞎写就是答非所问,只好自己摸索着写一下,修改之后那这篇文章记录一下,免得以后遗忘。
    我是在springboot项目中创建了一个类,需要创建索引的时候,在Test里写个函数跑一边就可以了。

    package com.sohu.umab.usercenter.service.impl;
    
    import org.springframework.data.domain.Sort;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.index.Index;
    import org.springframework.data.mongodb.core.index.IndexInfo;
    import org.springframework.stereotype.Repository;
    
    import javax.annotation.Resource;
    import java.util.List;
    import java.util.Set;
    
    /**
     * 给mongo数据库创建索引
     */
    @Repository
    public class CreateMongoIndex  {
        @Resource
        private MongoTemplate mongoTemplate;
    
        /**
         * 创建单个索引或者联合索引
         *
         * @param index_key 索引的名称,支持多个索引一起创建联合索引
         * @param collectionName 集合名称
         * @return
         */
        public boolean createInboxIndex(String collectionName, String... index_key) {
            boolean success = true;
            try {
                Index index = new Index();
                for (int i=0;i<index_key.length;i++){
                    index.on(index_key[i],Sort.Direction.ASC);
                }
                mongoTemplate.indexOps(collectionName).ensureIndex(index);
    
            } catch (Exception ex) {
                success = false;
            }
            return success;
        }
    
        /**
         * 获取现有索引集合
         *
         * @return
         */
        public List<IndexInfo> getInboxIndex(String collectionName) {
            List<IndexInfo> indexInfoList = mongoTemplate.indexOps(collectionName).getIndexInfo();
            return indexInfoList;
        }
    
        /**
         * 删除索引
         *
         * @param indexName 索引的名称
         * @param collectionName 集合名称
         * @return
         */
        public boolean deleteInboxIndex(String indexName, String collectionName) {
            boolean success= true;
            try {
                mongoTemplate.indexOps(collectionName).dropIndex(indexName);
            } catch (Exception ex) {
                success= false;
            }
            return success;
        }
    
        /**
        * 获取mongo中数据集合的名称
        */
        public Set<String> getNames(){
            Set<String> res = mongoTemplate.getCollectionNames();
            return res;
        }
      
    }
  • 相关阅读:
    hdu 5224 Tom and paper 水题
    2015 UESTC 搜索专题N题 韩爷的梦 hash
    2015 UESTC 搜索专题M题 Palindromic String 马拉车算法
    2015 UESTC 搜索专题K题 秋实大哥の恋爱物语 kmp
    2015 UESTC 搜索专题J题 全都是秋实大哥 kmp
    2015 UESTC 搜索专题F题 Eight Puzzle 爆搜
    2015 UESTC 搜索专题E题 吴队长征婚 爆搜
    2015 UESTC 搜索专题D题 基爷的中位数 二分
    2015 UESTC 搜索专题C题 基爷与加法等式 爆搜DFS
    2015 UESTC 搜索专题B题 邱老师降临小行星 记忆化搜索
  • 原文地址:https://www.cnblogs.com/47Gamer/p/14631261.html
Copyright © 2011-2022 走看看