Spring Data MongoDB 教程

创建索引

MongoTemplate 提供了一些管理索引和集合的方法,这些方法被收集到一个名为 IndexOperations 的助手接口中。可以通过调用 MongoTemplate.indexOps() 方法,并传入集合名称或实体的 java.lang.Class 来访问这些操作。indexOps() 方法定义如下:

  • IndexOperations indexOps(Class<?> entityClass) 通过 Class 返回可以对索引进行操作的 IndexOperations 对象

  • IndexOperations indexOps(String collectionName) 通过集合名返回可以对索引进行操作的 IndexOperations 对象

  • IndexOperations indexOps(String collectionName, Class<?> type) 通过集合名和 Class 返回可以对索引进行操作的 IndexOperations 对象

下面显示了 IndexOperations 接口方法定义:

public interface IndexOperations {
   // 创建索引
   void ensureIndex(IndexDefinition indexDefinition);
   // 删除集合中名为 name 的索引
   void dropIndex(String name);
   // 删除集合中所有索引
   void dropAllIndexes();
   // 重置索引缓存
   void resetIndexCache();
   // 获取索引信息
   List<IndexInfo> getIndexInfo();
}

创建索引

你可以通过使用MongoTemplate类在一个集合上创建一个索引来提高查询性能,如下例所示:

Index index = new Index().on("name", Sort.Direction.ASC);
mongoTemplate.indexOps(Person.class).ensureIndex(index);

注意:ensureIndex() 方法确保所提供的 IndexDefinition 的索引在集合中存在。

你还可以通过使用 IndexDefinition、GeoSpatialIndex 和 TextIndexDefinition 类来创建标准、地理空间和文本类型索引。例如,在 Venue 类对应的集合上声明一个地理空间查询索引,如下所示:

GeospatialIndex geoIndex = new GeospatialIndex("location");
mongoTemplate.indexOps(Person.class).ensureIndex(geoIndex);

完整示例

(1)application.properties 配置文件

# Log
logging.level.root=debug

# MongoDB
spring.data.mongodb.uri=mongodb://localhost:27017/test

(2)AppConfig.java 配置类,配置 MongoTemplate 对象

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
* 配置 MongoTemplate
* @author hxstrive.com 2022/12/23
*/
@Slf4j
@Configuration
public class AppConfig {

   @Bean
   public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
       log.info("mongoTemplate({}, {})", mongoDatabaseFactory);
       return new MongoTemplate(mongoDatabaseFactory);
   }

}

(3)集合 person 对应的实体

import lombok.Builder;
import lombok.Data;
import lombok.ToString;

@Data
@ToString
@Builder
public class Person {
   /** 用户ID */
   private int id;
   /** 用户姓名 */
   private String name;
   /** 年龄 */
   private int age;
}

(4)客户端代码,说明见注释。

import com.hxstrive.springdata.mongodb.entity.Person;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.Index;

/**
* 创建索引示例
* @author hxstrive.com
*/
@SpringBootTest
public class IndexManagementDemo1 {

   @Autowired
   private MongoTemplate mongoTemplate;

   @BeforeEach
   public void init() {
       mongoTemplate.dropCollection(Person.class);

       // 准备数据
       mongoTemplate.insert(Person.builder().id(100).name("Tom").age(27).build());
       mongoTemplate.insert(Person.builder().id(200).name("Helen").age(30).build());
       mongoTemplate.insert(Person.builder().id(300).name("Bill").age(47).build());
       mongoTemplate.insert(Person.builder().id(400).name("Joe").age(20).build());
   }

   // 创建简单索引
   @Test
   public void contextLoads() {
       Index index = new Index().on("name", Sort.Direction.ASC);
       String val = mongoTemplate.indexOps(Person.class).ensureIndex(index);
       System.out.println("val=" + val);
       // 结果:
       // val=name_1

       // 执行的语句如下:
       // {
       //    "createIndexes": "person",
       //    "indexes": [{"key": {"name": 1}, "name": "name_1"}],
       //    "$db": "test",
       //    "lsid": {"id": {"$binary": {"base64": "rHmCzMRCRkCcjb0yWTzF3w==", "subType": "04"}}}
       // }
   }

   // 创建地理空间索引
   @Test
   public void contextLoads2() {
       GeospatialIndex geoIndex = new GeospatialIndex("location");
       String val = mongoTemplate.indexOps(Person.class).ensureIndex(geoIndex);
       System.out.println("val=" + val);
       // 结果:
       // val=location_2d

       // 执行的语句如下:
       // {
       //    "createIndexes": "person",
       //    "indexes": [{"key": {"location": "2d"}, "name": "location_2d"}],
       //    "$db": "test",
       //    "lsid": {"id": {"$binary": {"base64": "RqfA+vouQOOfPpz8TfBQbw==", "subType": "04"}}}
       // }
   }

}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号