spring data mongodb index索引实践
《spring data mongodb index索引实践》要点: 在spring data mongodb中创建索引也是非常方便的. 直接在对应的实体类中用注解标识即可. 要给某个字段加索引就在字段上面加上@Indexed注解,里面可以填写对应的参数 像唯一索引的参数就是unique=true,以后台方式创建索引的参数是background=true. 然后是组合索引的创建,是要在类的上面定义@CompoundIndexes注解,参数是@CompoundIndex注解数组,可以传多个. name表示索引的名称,def表示组合索引的字段和索引存储升序(1)或者降序(-1). @Document @CompoundIndexes({ @CompoundIndex(name = "city_region_idx",def = "{'city': 1,'region': 1}") }) public class Person { private String id; @Indexed(unique=true) private String name; @Indexed(background=true) private int age; private String city; private String region; } 然后在插入数据的时候,框架会自动根据配置的注解创建对应的索引. 我们可以看下已创建好的索引信息. > db.person.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "cxytiandi.person" }, { "v" : 1, "key" : { "city" : 1, "region" : 1 }, "name" : "city_region_idx", "unique" : true, "key" : { "name" : 1 }, "name" : "name", "key" : { "age" : 1 }, "name" : "age", "ns" : "cxytiandi.person", "background" : true } ] > 也可以直接用代码查看索引信息 mongoTemplate.getCollection("person").getIndexInfo().forEach( index -> { System.out.println(index); }); 源码地址:https://github.com/yinjihuan/cxytiandi 《spring data mongodb index索引实践》是否对您有启发,欢迎查看更多与《spring data mongodb index索引实践》相关教程,学精学透。编程之家PHP学院为您提供精彩教程。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |