[MongoDB] @CompoundIndex

eugene·2025년 4월 12일

Trouble Shooting

목록 보기
5/5
post-thumbnail

📊 MongoDB 복합 인덱스 성능 실험 기록

MongoDB에서 자주 사용하는 필드 조합에 인덱스를 걸면 어느 정도 성능 차이가 나는지 테스트해봤습니다. 테스트 환경은 간단한 Kotlin + Spring Boot 프로젝트이며, 데이터는 chatRoomIdauthor 조합으로 이루어진 메시지들을 대상으로 합니다.

개발했던 MOCO 서비스에서는 chatRoomId + userId를 기반으로 조회하는 쿼리가 많았지만, 실제로 데이터가 많지 않아 성능 향상을 실감하기 어려운 상황이었습니다. 이에 따라 CompoundIndex 적용 전후의 성능을 비교하고, 실제로 어느 정도의 차이가 나는지 실험해 보았습니다.


🧱 데이터 구성

  • 전체 메시지: 100,000건
  • 그 중 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)

📉 인덱스 없이 실행한 결과 (COLLSCAN)

{
  "stage": "COLLSCAN",
  "docsExamined": 100000,
  "nReturned": 1000,
  "executionTimeMillis": 67
}
  • 전수 스캔(COLLSCAN) 발생

📈 복합 인덱스 적용 후 결과 (IXSCAN)

✅ 인덱스 생성

@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
)
  • application.yml 파일에 auto-index-creation: true 를 적용해야 자동으로 compoundIndex가 생성됩니다.

📋 실행 계획

{
  "stage": "IXSCAN",
  "indexName": "chatRoomId_author_idx",
  "keysExamined": 1000,
  "docsExamined": 1000,
  "nReturned": 1000,
  "executionTimeMillis": 7
}
  • 인덱스 스캔(IXSCAN)으로 변경
  • 조회 시간 약 60ms 단축

📝 결론

  • 복합 인덱스는 쿼리 성능에 즉각적인 향상을 줍니다.
  • 특히 자주 쓰는 조합이라면 인덱스를 고려합니다.
  • explain() 명령어로 실행 계획을 확인하고, 실제 데이터 패턴에 맞는 인덱스를 설계하기

📁 참고 코드

🔗 Test GitHub Repository

profile
뽀글뽀글 개발공부

0개의 댓글