MongoDB Spring Data创建索引工具

该博客介绍了如何使用MongoDB Spring Data来创建索引和实现按月分表的功能。通过MongoJpaCollectionFactory工具类,可以检查并创建 CompoundIndex 注解定义的复合索引,确保数据的高效检索。同时,示例展示了如何在TestDoc文档上定义索引,并在测试中应用到实际集合中。此外,文章提到由于资源限制,采用手动分表策略。
摘要由CSDN通过智能技术生成

MongoDB Spring Data 创建索引工具

工具类

package com.man.tools.mongodb.factory;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.theone.date.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MongoJpaCollectionFactory {
    protected static final Logger LOGGER = LoggerFactory.getLogger(MongoJpaCollectionFactory.class);

    /**
     * 按月分表
     *
     * @author Man
     * @date 2021/5/31
     **/
    public static String getCollectionName(String docName, Date date) {
        return docName + DateUtil.format(date, DateUtil.yyyyMM);
    }

    public static void creatIndex(MongoTemplate mongoTemplate, String collectionName, Class<?> aClass) {
        Set<String> indexSet = new HashSet<>();
        for (IndexInfo indexInfo : mongoTemplate.indexOps(collectionName).getIndexInfo()) {
            indexSet.add(indexInfo.getName());
        }
        CompoundIndex compoundIndex1 = AnnotationUtil.getAnnotation(aClass, CompoundIndex.class);
        if (compoundIndex1 != null) {
            index(collectionName, mongoTemplate, indexSet, compoundIndex1);
            return;
        }
        CompoundIndexes compoundIndexes = AnnotationUtil.getAnnotation(aClass, CompoundIndexes.class);
        for (CompoundIndex compoundIndex : compoundIndexes.value()) {
            index(collectionName, mongoTemplate, indexSet, compoundIndex);
        }
    }

    private static void index(String collectionName, MongoTemplate mongoTemplate, Set<String> indexSet, CompoundIndex compoundIndex) {
        if (indexSet.contains(compoundIndex.name())) {
            return;
        }
        mongoTemplate.indexOps(collectionName).ensureIndex(getIndex(compoundIndex));
    }

    private static Index getIndex(CompoundIndex compoundIndex) {
        String name = compoundIndex.name();
        String def = compoundIndex.def();
        Index index = new Index();
        index.named(name);
        index.background();
        JSONObject indexMap = JSONUtil.parseObj(def);
        for (Map.Entry<String, Object> keyOrder : indexMap.entrySet()) {
            String key = keyOrder.getKey();
            String order = String.valueOf(keyOrder.getValue());
            index.on(key, "1".equals(order) ? Sort.Direction.ASC : Sort.Direction.DESC);
        }
        return index;
    }
}

使用

实例

package com.man.tools.mongodb;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "TestDoc")
@CompoundIndexes({
        @CompoundIndex(name = "age_-1_name_1", def = "{age:-1,name:1}", background = true)
})
public class TestDoc{
    @Id
    private String id;
    
    private Integer age;
    
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
//启动Spring
@SpringBootTest(classes = Application.class)
public class BaseTest {
	@Resource 
	private MongoTemplate mongoTemplate;
	@Test
	public void testIndexOp() {
	    // 按年分表
		ArrayList<Class<?>> list = CollectionUtil.newArrayList(TestDoc.class);
		for (Class<?> aClass : list) {
			String collectionNameBase = mongoTemplate.getCollectionName(aClass);
			String collectionName =collectionNameBase + "2020";
			if (mongoTemplate.collectionExists(collectionName)) {
				MongoJpaCollectionFactory.creatIndex(mongoTemplate, collectionName, aClass);
			}
		}
	}
}

别问为什么MongoDB还要手动去分表,因为贫穷搭不起集群!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值