Entity class에 @Document 어노테이션을 추가하고,
특정필드에 @Indexed를 추가하면 자동으로 인덱스가 생성된다.
만약에 잘 안되면, 원인분석을 해야겠지만,
임시로 코드로 하는 방법이있는데, 다음과 같다.
1. 잘 동작함 - MongoConfig 수정 방식
//AUTO INDEX CREATION안되서 추가: 참고- https://github.com/spring-projects/spring-boot/issues/28478#issuecomment-954627106
@Override
protected boolean autoIndexCreation() {
return true;
}
@Bean
@Primary
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions, MongoManagedTypes managedTypes) {
MongoMappingContext mappingContext = super.mongoMappingContext(conversions, managedTypes);
mappingContext.setAutoIndexCreation(true);
return mappingContext;
}
2. not TESTED. - post Construct방식
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class IndexCreatorService {
@Autowired
private MongoTemplate mongoTemplate;
@PostConstruct
public void initIndexes() {
IndexOperations indexOps = mongoTemplate.indexOps(ExampleEntity.class);
indexOps.ensureIndex(new Index().on("fieldToIndex", org.springframework.data.domain.Sort.Direction.ASC));
}
}