이 페이지에서는 MongoDB 호환성을 갖춘 Firestore의 색인 생성을 설명합니다.
MongoDB 호환성을 갖춘 Firestore는 기본적으로 색인을 생성하지 않습니다. 데이터베이스 성능을 개선하려면 가장 자주 사용되는 쿼리에 대한 색인을 만드세요.
색인은 데이터베이스 성능에 큰 영향을 미칩니다. 쿼리에 대한 색인이 있으면 데이터베이스는 스캔해야 하는 데이터 양을 줄이고 결과를 정렬하는 데 필요한 작업을 줄여 결과를 효율적으로 반환할 수 있습니다. 하지만 색인 항목은 스토리지 비용과 색인이 생성된 필드에 대한 쓰기 작업 중에 실행되는 작업량을 늘립니다.
각 필드의 순서와 정렬 방향은 색인을 고유하게 정의합니다. 예를 들어 다음 색인은 서로 다른 두 개의 색인이며 서로 바꿔 사용할 수 없습니다.
컬렉션
필드
cities
국가 (오름차순), 인구 (내림차순)
cities
인구 (내림차순), 국가 (오름차순),
쿼리를 지원하는 색인을 만들 때는 쿼리와 동일한 순서로 필드를 포함합니다.
색인 밀도
기본적으로 색인 항목은 컬렉션의 모든 문서에서 데이터를 저장합니다. 이를 비희소 색인이라고 합니다. 문서에 색인에 지정된 필드가 포함되어 있는지 여부와 관계없이 문서에 색인 항목이 추가됩니다.
존재하지 않는 필드는 색인 항목을 생성할 때 NULL 값을 갖는 것으로 처리됩니다. 이 동작을 변경하려면 색인을 스파스 색인으로 정의하면 됩니다.
스파스 색인
희소 색인은 색인이 생성된 필드 중 하나 이상에 값 (null 포함)이 포함된 컬렉션의 문서만 색인을 생성합니다. 스파스 색인은 스토리지 비용을 줄이고 성능을 향상시킬 수 있습니다.
배열 값의 멀티 키 색인
배열 값이 포함된 필드에 색인을 만드는 경우 멀티 키 색인을 만들어야 합니다. 일반 색인은 배열 값을 색인화할 수 없습니다. 멀티 키 색인은 색인 정의에서 최대 하나의 배열 필드를 지원하며 배열 값을 순회하는 작업에 사용할 수 있습니다.
배열 값의 색인을 생성해야 하는 경우에만 멀티 키 색인을 사용하세요.
일반 색인은 쿼리를 처리할 때 장점이 있습니다. 예를 들어 일반 색인은 범위 내의 값을 더 효율적으로 필터링할 수 있습니다.
다음과 같은 상황에서는 배열 값과 다중 키 색인을 사용할 때 오류가 발생합니다.
작업에서 일반 색인으로 색인이 생성된 필드에 배열 값을 추가하려고 합니다. 배열 값을 추가하려면 해당 필드의 기존 일반 색인을 삭제하고 다중 키 색인으로 다시 만들어야 합니다.
배열 값을 포함하는 필드에 일반 색인을 만들려고 시도합니다. 멀티 키 색인을 만들거나 배열 값을 삭제해야 합니다.
작업에서 배열 값이 있는 여러 필드의 색인을 생성하려고 합니다. 다중 키 색인에는 배열 값이 있는 필드가 두 개 이상 있을 수 없습니다.
계속하려면 데이터 모델 또는 색인 정의를 수정하세요.
두 필드 경로가 users.posts 및 users.zip과 같은 공통 접두사를 공유하는 멀티키 색인을 만들려고 합니다.
색인 빌드 오류 문제 해결
색인을 관리할 때 색인 빌드 오류가 발생할 수 있습니다. 데이터베이스에서 데이터 문제가 발생하면 색인 생성 작업이 실패할 수 있습니다.
다음과 같은 이유로 색인 작업이 실패할 수 있습니다.
색인 한도에 도달했습니다. 예를 들어 작업이 문서당 최대 색인 항목 수에 도달했을 수 있습니다. 색인 생성이 실패하면 오류 메시지가 표시됩니다. 색인 한도에 도달하지 않은 경우 색인 작업을 다시 시도하세요.
멀티키 색인이 필요합니다. 색인이 생성된 필드 중 하나 이상에 배열 값이 포함되어 있습니다. 계속하려면 다중 키 색인을 사용하거나 배열 값을 삭제해야 합니다.
작업에서 배열 값이 있는 여러 필드의 색인을 생성하려고 합니다. 다중 키 색인에는 배열 값이 있는 필드가 두 개 이상 있을 수 없습니다.
계속하려면 데이터 모델 또는 색인 정의를 수정하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-18(UTC)"],[],[],null,["Indexes overview\n\nThis page describes indexing for Firestore with MongoDB compatibility.\nFirestore with MongoDB compatibility does not create any indexes by default. To improve database\nperformance, create indexes for your most commonly used queries.\n\nIndexes have a large impact on the performance of a database. If an index exists\nfor a query, the database can efficiently return results by reducing the amount\nof data that needs to be scanned and reducing the work needed to sort the\nresults. However, index entries increase storage costs and the amount of work\ndone during a write operation on indexed fields.\n\nIndex definition and structure\n\nAn index consists of the following:\n\n- a collection ID\n- a list of fields in the given collection\n- an order, either ascending or descending, for each field\n\nAn index can also enable the [sparse](#sparse_indexes), [multikey](#multikey), or [unique](#unique_indexes) options.\n\nIndex ordering\n\nThe order and sort direction of each field uniquely defines the index. For\nexample, the following indexes are two distinct indexes and not\ninterchangeable:\n\n| Collection | Fields |\n|------------|-----------------------------------------------|\n| cities | country (ascending), population (descending) |\n| cities | population (descending), country (ascending), |\n\nWhen creating an index to support a query, include the fields in the same order\nas your query.\n\nIndex density\n\nBy default, index entries store data from all documents in a collection. This is\nknown as a non-sparse index. An index entry will be added for a document regardless\nof whether the document contains any of the fields specified in the index.\nNon-existent fields are treated as having a NULL value when generating index\nentries. To change this behavior, you can define the index as a sparse index.\n\nSparse indexes\n\nA sparse index indexes only the documents in the\ncollection that contain a value (including null) for at least one of the indexed\nfields. A sparse index reduces storage costs and can improve performance.\n\nMultikey indexes for array values\n\nIf you are creating an index on a field that contains array values, you must\ncreate a multikey index. A regular index cannot\nindex array values. A multikey index supports up to one array field in the\nindex definition and can be used for operations that traverse array values.\n\nOnly use multikey indexes if you know that you need to index array values.\nRegular indexes have advantages when processing a query. For example, regular\nindexes can filter values within a range more efficiently.\n\nThe following situations lead to errors when working with array values and\nmultikey indexes:\n\n- An operation attempts to add an array value to a field indexed by a regular index. To add the array value, you must delete existing regular indexes on that field, and recreate them as multikey indexes.\n- You attempt to create a regular index on a field that contains an array value. You must either create a multikey index or delete the array values.\n- An operation attempts to index multiple fields with array values. You cannot have more than one field with an array value in a multikey index. To proceed, modify your data model or your index definitions.\n- You attempt to create a multikey index where two field paths share a common prefix like `users.posts` and `users.zip`.\n\nUnique indexes\n\nSet the unique index option to enforce unique values for the indexed fields.\nFor indexes on multiple fields, each combination of values must be unique\nacross the index. The database rejects any update and insert operations that\nattempt to create index entries with duplicate values. If the data\nof the indexed fields contains duplicate values and you attempt\nto create a unique index, then the index build fails with an error message\nin the operation details.\n\nAbsent fields in a unique index\n\nIf you insert a document with missing fields for the unique index, the index\nsets `null` values for the missing fields. The resulting index entry must be\nunique or the operation fails.\n\nFor example, with this index: \n\n```bash\ndb.cities.createIndex( { \"name\": 1 }, { unique: true } )\n```\n\nIf you add the document `{\"abbreviation\": \"LA\"}` to the collection, the unique\nindex creates an entry with `name` set to `null`. If you then try to add the\ndocument `{\"abbreviation\": \"NYC\"}`, the operation fails because the resulting\nentry for the unique index is the same.\n\nThe same behavior applies to unique indexes with multiple fields.\nWhen creating or updating a document, missing\nindexed fields are set to `null` and the resulting index entry must be\nunique in the index.\n\nTroubleshoot index building errors\n\nYou might encounter index building errors when managing your indexes. An\nindexing operation can fail if the database encounters a problem with the data.\nIndexing operations can fail for the following reasons:\n\n- You have reached an index limit. For example, the operation may have reached the maximum number of index entries per document. If index creation fails, you see an error message. If you have not reached an index limit, retry the index operation.\n- A multikey index is required. At least one of the indexed fields contains an array value. To proceed, you must either use a multikey index or delete the array values.\n- An operation attempts to index multiple fields with array values. You cannot have more than one field with an array value in a multikey index. To proceed, modify your data model or your index definitions.\n- You set the unique index option and the data of the indexed fields would create duplicate index entries. To proceed, remove duplicate combinations of values from the data.\n\n| **Warning:** An ongoing index building error might impact creation of new indexes. Resolving the errors before creating indexes under the same collection.\n\nWhat's next\n\n- Learn how to [create and manage indexes](/firestore/mongodb-compatibility/docs/indexing)"]]