Indexes
개요
이 가이드에서는 MongoDB Go 드라이버에서 인덱스를 사용하는 방법을 배울 수 있습니다.
인덱스는 MongoDB에서 쿼리를 효율적으로 실행할 수 있도록 지원합니다. 인덱스가 없는 MongoDB는 collection의 모든 문서를 스캔해 (컬렉션 스캔) 쿼리와 일치하는 문서를 찾습니다. 컬렉션 스캔은 속도가 느려 애플리케이션 성능에 부정적인 영향을 미칠 수 있습니다. 적절한 인덱스를 사용하면 MongoDB가 검사하는 문서 수를 제한할 수 있습니다.
팁
업데이트 작업, 삭제 작업 및 특정 집계 파이프라인 단계에서 인덱스를 사용할 수도 있습니다.
쿼리 커버리지 및 성능
MongoDB의 쿼리에는 다음 요소가 포함될 수 있습니다.
요소 | 필요성 | 목적 |
---|---|---|
쿼리 | 필수 사항 | 찾고자 하는 필드와 값 지정. |
옵션 | 옵션 | 쿼리 실행 방법 지정. |
프로젝션 | 옵션 | MongoDB가 반환하는 필드를 지정합니다. |
Sort | 옵션 | MongoDB가 문서를 반환하는 순서 지정. |
이러한 요소를 동일한 인덱스에 지정하면 MongoDB는 인덱스에서 직접 결과를 반환하며 이를 커버 쿼리라고도 합니다.
중요
정렬 기준
정렬 기준은 인덱스의 순서와 일치하거나 반전되어야 합니다.
name
필드의 인덱스를 오름차순 (A-Z) 으로 age
인덱스를 내림차순 (9-0) 으로 가정해 보겠습니다.
name_1_age_-1
MongoDB는 다음 중 하나를 기준으로 데이터를 정렬할 때 이 인덱스를 사용합니다.
name
오름차순,age
내림차순name
내림차순,age
오름차순
그러나 두 필드의 정렬 순서를 같은 방향으로 지정하려면 메모리 내 정렬이 필요합니다.
인덱스가 쿼리 기준 및 프로젝션을 포함하는지 확인하는 방법에 대한 자세한 내용은 쿼리 커버리지를 참조하세요.
운영 고려 사항
쿼리 성능을 향상하려면 정렬된 결과를 반환하는 쿼리와 정렬된 결과를 반환하는 작업에 자주 나타나는 필드에 인덱스를 생성하세요. 추가하는 각 인덱스는 디스크 공간과 메모리를 사용하므로 용량 계획을 위해 인덱스 메모리와 디스크 사용량을 추적해야 합니다. 또한 쓰기 작업이 인덱싱된 필드를 업데이트할 때는 MongoDB도 관련 인덱스도 업데이트해야 합니다.
MongoDB는 동적 스키마를 지원하므로 애플리케이션은 이름이 알려지지 않았거나 임의의 이름을 가진 필드에 쿼리할 수 있습니다. MongoDB 4.2는 이러한 쿼리를 지원하기 위해 와일드카드 인덱스를 도입했습니다. 와일드카드 인덱스는 워크로드 기반 인덱스 계획을 대체하도록 설계되지 않았습니다.
데이터 모델을 설계하고 애플리케이션에 적합한 인덱스를 선택하는 방법에 대해 자세히 알아보려면 인덱싱 전략 및 데이터 모델링 및 인덱스를 참조하세요.
인덱스 유형
MongoDB는 데이터 쿼리를 지원하기 위해 여러 가지 인덱스 유형을 지원합니다. 다음 섹션에서는 가장 일반적인 인덱스 유형 생성 방법을 설명합니다. 인덱스 유형 전체 목록을 보려면 인덱스를 참조하세요.
단일 필드 인덱스
단일 필드 인덱스는 collection 문서 내의 필드에 대한 참조를 보유합니다.
이 인덱스는 단일 필드 쿼리 및 정렬 성능을 향상시키고 일정 시간이 지나면 컬렉션에서 문서를 자동으로 제거하는 TTL 인덱스을 지원합니다.
참고
_id_
인덱스는 단일 필드 인덱스의 예입니다. 이 인덱스는 새 collection을 생성할 때 _id
필드에 자동으로 생성됩니다.
예시
다음 예시에서는 sample_mflix.movies
collection의 title
필드에 오름차순으로 인덱스를 만들어 봅니다.
coll := client.Database("sample_mflix").Collection("movies") indexModel := mongo.IndexModel{ Keys: bson.D{{"title", 1}}, } name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
Name of Index Created: title_1
복합 인덱스
복합 인덱스는 collection 문서 내의 여러 필드에 대한 참조를 보유합니다. 이 인덱스는 쿼리 및 정렬 성능을 향상시킵니다.
예시
다음 예시에서는 sample_mflix.movies
collection의 fullplot
및 title
필드에 복합 인덱스를 생성합니다.
coll := client.Database("sample_mflix").Collection("movies") indexModel := mongo.IndexModel{ Keys: bson.D{ {"fullplot", -1}, {"title", 1} } } name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
Name of Index Created: fullplot_-1_title_1
다중 키 인덱스(배열 필드의 인덱스)
다중 키 인덱스는 단일 필드 인덱스 및 복합 인덱스와 동일한 구문을 사용합니다. 이 인덱스는 배열 필드를 인덱스로 지정하는 쿼리의 성능을 향상시킵니다.
예시
다음 예에서는 sample_mflix.movies
컬렉션의 cast
필드에 멀티키 인덱스를 생성합니다.
coll := client.Database("sample_mflix").Collection("movies") indexModel := mongo.IndexModel{ Keys: bson.D{{"cast", -1}} } name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
Name of Index Created: cast_-1
Atlas Search 및 Atlas Vector Search 인덱스
고 (Go) 운전자 사용하여 Atlas Search 및 Atlas Vector Search 인덱스를 프로그래밍 방식으로 관리 할 수 있습니다.
Atlas Search 기능 사용하면 MongoDB Atlas 에서 호스팅되는 컬렉션에서 전체 텍스트 검색을 수행할 수 있습니다. Atlas Search 에 대해 자세히 학습 Atlas Search 설명서를 참조하세요.
Atlas Vector Search 사용하면 Atlas 에 저장된 벡터 임베딩에 대해 시맨틱 검색을 수행할 수 있습니다. Atlas Vector Search 에 대해 자세히 학습 Atlas Vector Search 문서를 참조하세요.
Atlas Vector Search 쿼리를 실행 방법에 대해 자세히 학습 Atlas Vector Search 쿼리 실행 가이드 참조하세요.
다음 섹션에는 Atlas Search 및 Atlas Vector Search 인덱스를 관리 방법을 보여주는 코드 예제가 포함되어 있습니다.
검색 인덱스 만들기
SearchIndexView.CreateOne()
메서드에 인덱스 정의를 제공하여 Atlas Search 또는 Atlas Vector Search 인덱스 만들 수 있습니다.
다음 예시 sample_mflix.movies
컬렉션 의 plot
필드 에 Atlas Search 인덱스 만듭니다.
// Sets the index name and type to "search" const indexName = "search_index" opts := options.SearchIndexes().SetName(indexName).SetType("search") // Defines the index definition searchIndexModel := mongo.SearchIndexModel{ Definition: bson.D{ {Key: "mappings", Value: bson.D{ {Key: "dynamic", Value: false}, {Key: "fields", Value: bson.D{ {Key: "plot", Value: bson.D{ {Key: "type", Value: "string"}, }}, }}, }}, }, Options: opts, } // Creates the index searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) if err != nil { log.Fatalf("Failed to create the Atlas Search index: %v", err) }
다음 예시 sample_mflix.embedded_movies
컬렉션 의 plot_embedding
필드 에 Atlas Vector Search 인덱스 만듭니다.
// Defines the structs used for the index definition type vectorDefinitionField struct { Type string `bson:"type"` Path string `bson:"path"` NumDimensions int `bson:"numDimensions"` Similarity string `bson:"similarity"` Quantization string `bson:"quantization"` } type vectorDefinition struct { Fields []vectorDefinitionField `bson:"fields"` } // Sets the index name and type to "vectorSearch" const indexName = "vector_search_index" opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch") // Defines the index definition vectorSearchIndexModel := mongo.SearchIndexModel{ Definition: vectorDefinition{ Fields: []vectorDefinitionField{{ Type: "vector", Path: "plot_embedding", NumDimensions: 1536, Similarity: "dotProduct", Quantization: "scalar"}}, }, Options: opts, } // Creates the index searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, vectorSearchIndexModel) if err != nil { log.Fatalf("Failed to create the Atlas Vector Search index: %v", err) }
검색 인덱스 나열
SearchIndexView.List()
메서드를 사용하여 인덱스 이름을 지정하여 Atlas Search 또는 Atlas Vector Search 인덱스 나열할 수 있습니다.
다음 예시 에서는 지정된 Atlas Search 또는 Atlas Vector Search 인덱스 의 세부 정보를 나열합니다.
// Specifies the index to retrieve const indexName = "myIndex" opts := options.SearchIndexes().SetName(indexName) // Retrieves the details of the specified index cursor, err := coll.SearchIndexes().List(ctx, opts) // Prints the index details to the console as JSON var results []bson.D if err := cursor.All(ctx, &results); err != nil { log.Fatalf("Failed to unmarshal results to bson: %v", err) } res, err := json.Marshal(results) if err != nil { log.Fatalf("Failed to marshal results to json: %v", err) } fmt.Println(res)
검색 인덱스 업데이트
SearchIndexView.UpdateOne()
메서드를 사용하여 인덱스 이름과 새 인덱스 정의를 지정하여 Atlas Search 또는 Atlas Vector Search 인덱스 업데이트 수 있습니다.
다음 예시 인덱스 이름과 새 인덱스 정의를 제공하여 Atlas Vector Search 인덱스 업데이트합니다.
// Specifies the index name and the new index definition const indexName = "vector_search_index" type vectorDefinitionField struct { Type string `bson:"type"` Path string `bson:"path"` NumDimensions int `bson:"numDimensions"` Similarity string `bson:"similarity"` } type vectorDefinition struct { Fields []vectorDefinitionField `bson:"fields"` } definition := vectorDefinition{ Fields: []vectorDefinitionField{ { Type: "vector", Path: "plot_embedding", NumDimensions: 1536, Similarity: "cosine", Quantization: "scalar", }, }, } // Updates the specified index err := coll.SearchIndexes().UpdateOne(ctx, indexName, definition) if err != nil { log.Fatalf("Failed to update the index: %v", err) }
검색 인덱스 삭제
SearchIndexView.DropOne()
메서드를 사용하여 인덱스 이름을 지정하여 Atlas Search 또는 Atlas Vector Search 인덱스 삭제 수 있습니다.
다음 예시 지정된 이름의 Atlas Search 또는 Atlas Vector Search 인덱스 삭제합니다.
// Deletes the specified index err := coll.SearchIndexes().DropOne(ctx, "myIndex") if err != nil { log.Fatalf("Failed to delete the index: %v", err) }
클러스터화된 인덱스
클러스터형 인덱스는 클러스터형 컬렉션에서 삽입과 업데이트 및 삭제 작업의 성능을 향상하는 인덱스입니다. 클러스터형 컬렉션은 클러스터형 인덱스 키 값을 기준으로 정렬된 문서를 저장합니다.
클러스터형 인덱스를 생성하려면 collection을 생성할 때 _id
필드를 키로 사용하고 고유 필드를 true
로 사용하여 클러스터형 인덱스 옵션을 지정하세요.
예시
다음 예시에서는 db.tea
collection의 _id
필드에 클러스터형 인덱스를 생성합니다.
db := client.Database("db") cio := bson.D{{"key", bson.D{{"_id", 1}}}, {"unique", true}} opts := options.CreateCollection().SetClusteredIndex(cio) db.CreateCollection(context.TODO(), "tea", opts)
Text Indexes
텍스트 인덱스는 문자열 콘텐츠에 대한 텍스트 검색 쿼리를 지원합니다. 이 인덱스에는 문자열 필드 또는 문자열 배열이 필요합니다. MongoDB는 여러 언어에 대한 텍스트 검색을 지원합니다. 인덱스를 만들 때 기본 언어를 옵션으로 지정할 수 있습니다.
컬렉션에는 하나의 텍스트 인덱스만 포함할 수 있습니다. 여러 텍스트 필드에 대한 텍스트 인덱스를 만들려면 복합 인덱스를 생성해야 합니다. 텍스트 검색은 복합 인덱스 내의 모든 텍스트 필드에서 실행됩니다.
팁
텍스트 인덱스는 더 강력한 Atlas Full Text Search 인덱스와 다릅니다. Atlas 사용자의 경우 Atlas 검색을 권장합니다.
예시
다음 예시에서는 sample_mflix.movies
컬렉션의 기본 언어로 italian
사용하여 plot
필드에 텍스트 인덱스를 생성합니다.
coll := client.Database("sample_mflix").Collection("movies") indexModel := mongo.IndexModel{Keys: bson.D{{"plot", "text"}, {"default_language", "italian"}}} name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
Name of Index Created: plot_text
지리 공간적 인덱스
MongoDB는 2dsphere 인덱스를 사용하여 지리 공간 좌표 데이터가 포함된 쿼리를 지원합니다. 2dsphere
인덱스가 GeoJSON 객체 필드에 있어야 합니다.
이 인덱스를 사용하면 다음을 수행할 수 있습니다.
지리 공간 데이터를 쿼리하여 포함 여부, 교차점, 근접성 확인
유클리드 평면에서의 거리 계산 및 MongoDB 2.2 이하에서 사용되는 '레거시 좌표 쌍' 구문 작업
예시
sample_mflix.theaters
컬렉션의 문서 내 location.geo
필드는 극장의 좌표를 설명하는 GeoJSON 포인트 객체입니다.
{ "_id" : ObjectId("59a47286cfa9a3a73e51e75c"), "theaterId" : 104, "location" : { "address" : { "street1" : "5000 W 147th St", "city" : "Hawthorne", "state" : "CA", "zipcode" : "90250" }, "geo" : { "type" : "Point", "coordinates" : [ -118.36559, 33.897167 ] } } }
다음 예시에서는 location.geo
필드에 2dsphere
인덱스를 생성합니다.
중요
지리 공간 인덱스에 포함된 필드에 지리 공간 인덱스를 생성하려고 하면 오류가 발생합니다.
indexModel := mongo.IndexModel{ Keys: bson.D{{"location.geo", "2dsphere"}} } name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
location.geo_2dsphere
Unique Indexes
고유 인덱스는 인덱스된 필드에 중복 값이 저장되는 것을 방지합니다. 기본적으로 MongoDB는 _id
필드 생성 시 고유 인덱스를 생성합니다.
고유 인덱스를 생성하려면 중복을 방지하려는 필드 또는 필드 조합을 지정하고 unique
옵션을 true
로 설정합니다.
예시
다음 예시에서는 theaterId
필드에 고유한 내림차순 인덱스를 생성합니다.
indexModel := mongo.IndexModel{ Keys: bson.D{{"theaterId", -1}}, Options: options.Index().SetUnique(true), } name, err := coll.Indexes().CreateOne(context.TODO(), indexModel) if err != nil { panic(err) } fmt.Println("Name of Index Created: " + name)
Name of Index Created: theaterId_-1
인덱스 제거
_id
필드 의 기본값 고유 인덱스 제외한 컬렉션 에서 모든 인덱스 삭제 수 있습니다. 인덱스 제거 하려면 DropOne()
메서드에 인덱스 이름을 전달합니다.
다음 예에서는 title_1
sample_mflix.movies
collection에서 (이)라는 인덱스를 제거합니다.
coll := client.Database("sample_mflix").Collection("movies") err := coll.Indexes().DropOne(context.TODO(), "title_1") if err != nil { panic(err) }
추가 정보
언급된 인덱스에 대해 자세히 알아보려면 다음 가이드를 참조하세요.
언급된 작업에 대해 자세히 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드 에서 설명하는 메서드 및 관련 메서드에 대해 자세히 학습 다음 API 설명서를 참조하세요.