
MongoDB에서 자주 사용하는 필드 조합에 인덱스를 걸면 어느 정도 성능 차이가 나는지 테스트해봤습니다. 테스트 환경은 간단한 Kotlin + Spring Boot 프로젝트이며, 데이터는 chatRoomId와 author 조합으로 이루어진 메시지들을 대상으로 합니다.
개발했던 MOCO 서비스에서는
chatRoomId + userId를 기반으로 조회하는 쿼리가 많았지만, 실제로 데이터가 많지 않아 성능 향상을 실감하기 어려운 상황이었습니다. 이에 따라 CompoundIndex 적용 전후의 성능을 비교하고, 실제로 어느 정도의 차이가 나는지 실험해 보았습니다.
chatRoomId = room10, author = user10 인 메시지: 1,000건val rawQuery = Filters.and(
Filters.eq("chatRoomId", "room10"),
Filters.eq("author", "user10")
)
val explain = mongoTemplate
.db
.getCollection("messages_index")
.find(rawQuery)
.explain(Document::class.java)
{
"stage": "COLLSCAN",
"docsExamined": 100000,
"nReturned": 1000,
"executionTimeMillis": 67
}
@Document(collection = "messages_index")
@CompoundIndex(
name = "chatRoomId_author_idx",
def = "{'chatRoomId': 1, 'author': 1}",
)
data class IndexedMessage(
@Id
val id: String? = null,
val text: String,
val author: String,
val chatRoomId: String
)
auto-index-creation: true 를 적용해야 자동으로 compoundIndex가 생성됩니다.{
"stage": "IXSCAN",
"indexName": "chatRoomId_author_idx",
"keysExamined": 1000,
"docsExamined": 1000,
"nReturned": 1000,
"executionTimeMillis": 7
}
explain() 명령어로 실행 계획을 확인하고, 실제 데이터 패턴에 맞는 인덱스를 설계하기