Azure Cosmos DB에서 데이터는 각 컨테이너에 대해 정의된 인덱싱 정책에 따라 인덱싱 됩니다. 새로 만든 컨테이너에 대한 기본 인덱싱 정책은 모든 문자열 또는 숫자에 대해 범위 인덱스를 적용합니다. 이 정책을 사용자 지정 인덱싱 정책으로 재정의할 수 있습니다.
비고
이 문서에서 설명하는 인덱싱 정책 업데이트 방법은 Azure Cosmos DB for NoSQL에만 적용됩니다. Azure Cosmos DB for MongoDB의 인덱싱 및 Apache Cassandra용 Azure Cosmos DB의 보조 인덱싱에 대해 알아봅니다.
인덱싱 정책 예제
다음은 JSON 형식으로 표시된 인덱싱 정책의 몇 가지 예입니다. JSON 형식으로 Azure Portal에 노출됩니다. Azure CLI 또는 모든 SDK를 사용하여 동일한 매개 변수를 설정할 수 있습니다.
일부 속성 경로를 선택적으로 제외하는 옵트아웃 정책
{
"indexingMode": "consistent",
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/path/to/single/excluded/property/?"
},
{
"path": "/path/to/root/of/multiple/excluded/properties/*"
}
]
}
비고
- 파티션 키는 (또한
/id이 아닌 경우) 인덱싱되지 않으며 인덱스에 포함되어야 합니다. - 시스템 속성
id와_ts는 cosmos 계정의 인덱싱 모드가consistent일 때 항상 인덱싱됩니다. - 시스템 속성
id이며_ts컨테이너 정책의 인덱싱된 경로 설명에 포함되지 않습니다. 이러한 시스템 속성은 기본적으로 인덱싱되고 이 동작을 사용하지 않도록 설정할 수 없으므로 이는 의도적으로 수행됩니다.
일부 속성 경로를 선택적으로 포함하는 옵트인 정책
{
"indexingMode": "consistent",
"includedPaths": [
{
"path": "/path/to/included/property/?"
},
{
"path": "/path/to/root/of/multiple/included/properties/*"
}
],
"excludedPaths": [
{
"path": "/*"
}
]
}
비고
일반적으로 옵트아웃 인덱싱 정책을 사용하는 것이 좋습니다. Azure Cosmos DB는 데이터 모델에 추가될 수 있는 모든 새 속성을 적극적으로 인덱싱합니다.
특정 속성 경로에만 공간 인덱스 사용
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/_etag/?"
}
],
"spatialIndexes": [
{
"path": "/path/to/geojson/property/?",
"types": [
"Point",
"Polygon",
"MultiPolygon",
"LineString"
]
}
]
}
벡터 인덱싱 정책 예
개별 속성에 대한 경로를 포함하거나 제외하는 것 외에도 벡터 인덱스를 지정할 수도 있습니다. 일반적으로 쿼리 벡터와 벡터 속성 간의 유사성을 측정하기 위해 VectorDistance 시스템 함수를 사용할 때마다 벡터 인덱스를 지정해야 합니다.
비고
계속하기 전에 Azure Cosmos DB NoSQL 벡터 인덱싱 및 검색을 사용하도록 설정해야 합니다.
중요합니다
벡터 인덱싱 정책은 컨테이너의 벡터 정책에 정의된 것과 동일한 경로에 있어야 합니다. 자세한 내용은 컨테이너 벡터 정책을 참조하세요.
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/_etag/?"
}
],
"vectorIndexes": [
{
"path": "/vector",
"type": "quantizedFlat"
}
]
}
중요합니다
배열 내에 중첩된 와일드카드 문자(*, []) 및 벡터 경로는 현재 벡터 정책 또는 벡터 인덱스에서 지원되지 않습니다.
중요합니다
현재 벡터 정책 및 벡터 인덱스는 만든 후에 변경할 수 없습니다. 변경하려면 새 컬렉션을 만듭니다.
다음 형식의 벡터 인덱스 정책을 정의할 수 있습니다.
| 유형 | Description | 최대 크기 |
|---|---|---|
flat |
다른 인덱싱된 속성과 동일한 인덱스에 벡터를 저장합니다. | 505 |
quantizedFlat |
인덱스에 저장하기 전에 벡터를 양자화(압축)합니다. 이는 약간의 정확도를 희생하면서 대기 시간과 처리량을 개선할 수 있습니다. | 4096 |
diskANN |
DiskANN을 기반으로 빠르고 효율적인 근사 검색을 위한 인덱스를 만듭니다. | 4096 |
flat 및 quantizedFlat 인덱스 형식은 Azure Cosmos DB의 인덱스를 사용하여 벡터 검색을 수행할 때 각 벡터를 저장하고 읽습니다.
flat 인덱스를 사용한 벡터 검색은 무차별 검색이며 100% 정확도를 제공합니다. 그러나 플랫 인덱스의 벡터에는 505 차원의 제한이 있습니다.
quantizedFlat 인덱스는 인덱스에 양자화되거나 압축된 벡터를 저장합니다.
quantizedFlat 인덱스를 사용한 벡터 검색도 무차별 검색이지만 벡터가 인덱스에 추가되기 전에 양자화되므로 정확도가 100%보다 약간 낮을 수 있습니다. 그러나 quantized flat을 사용한 벡터 검색은 flat 인덱스의 벡터 검색보다 대기 시간이 짧고 처리량이 높으며 RU 비용이 낮아야 합니다. 쿼리 필터를 사용하여 벡터 검색 범위를 비교적 작은 벡터 집합으로 좁히는 시나리오에 적합한 옵션입니다.
인덱스는 diskANN Microsoft Research에서 개발한 고성능 벡터 인덱싱 알고리즘 모음인 DiskANN을 사용하는 벡터용으로 특별히 정의된 별도의 인덱스입니다. DiskANN 인덱스는 대기 시간이 가장 짧고 QPS(초당 쿼리 수) 및 가장 낮은 RU 비용 쿼리를 높은 정확도로 제공할 수 있습니다. 그러나 DiskANN은 ANN(Approximous Nearest Neighbors) 인덱스이므로 정확도가 quantizedFlat 또는 flat보다 낮을 수 있습니다.
diskANN 및 quantizedFlat 인덱스는 모든 ANN 벡터 인덱스에 적용되는 정확도와 대기 시간 간의 균형을 조정하는 데 사용할 수 있는 선택적인 인덱스 빌드 매개 변수를 포함할 수 있습니다.
-
quantizationByteSize: 제품 양자화의 크기(바이트)를 설정합니다. Min=1, Default=dynamic(시스템 결정), Max=512. 이렇게 크게 설정하면 더 높은 RU 비용과 더 높은 대기 시간을 희생하여 정확도 벡터 검색이 높아질 수 있습니다. 이는quantizedFlat및DiskANN인덱스 형식 모두에 적용됩니다. -
indexingSearchListSize: 인덱스 빌드 생성 중에 검색할 벡터 수를 설정합니다. Min=10, Default=100, Max=500. 이 값을 크게 설정하면 인덱스 빌드 시간이 길고 벡터 수집 대기 시간이 길어질수록 정확도 벡터 검색이 높아질 수 있습니다.DiskANN인덱스에만 적용됩니다.
분할된 DiskANN 사용
분할된 DiskANN을 사용하면 DiskANN 인덱스를 더 작고 관리하기 쉬운 조각으로 분할하여 대규모 벡터 검색을 최적화할 수 있습니다. 컨테이너의 인덱싱 정책에서 VectorIndexShardKey를 지정하여 선택한 문서 속성의 각 고유 값에 하나씩 여러 DiskANN 인덱스를 만들 수 있습니다.
이 방법을 사용하면 특히 높은 카디널리티 데이터로 작업할 때 더 빠른 쿼리 성능, 향상된 회수 및 낮은 RU 비용이 발생할 수 있습니다. 권장 사항 엔진, 의미 체계 검색 또는 지능형 에이전트를 빌드하는 경우 분할된 DiskANN을 사용하면 벡터 인덱싱이 구조화되고 실행되는 방식을 보다 세세하게 제어할 수 있습니다.
여기서는 tenantID 속성을 기반으로 샤드 키를 정의하는 예제를 볼 수 있습니다. 이 속성은 데이터 항목의 모든 속성일 수 있으며 파티션 키도 될 수 있습니다. 단일 문자열을 배열로 묶어야 합니다. 자세한 내용은 분할된 DiskANN: 포커스가 있는 벡터 검색을 참조하세요.
"vectorIndexes": [
{
"path": "/vector2",
"type": "DiskANN",
"vectorIndexShardKey": ["/tenantID"]
}
]
튜플 인덱싱 정책 예제
이 인덱싱 정책 예제는 events.name 및 events.category 에 대한 튜플 인덱스를 정의합니다.
{
"automatic":true,
"indexingMode":"Consistent",
"includedPaths":[
{"path":"/*"},
{"path":"/events/[]/{name,category}/?"}
],
"excludedPaths":[],
"compositeIndexes":[]
}
위의 인덱스는 다음 쿼리에 사용됩니다.
SELECT *
FROM root r
WHERE
EXISTS (SELECT VALUE 1 FROM ev IN r.events
WHERE ev.name = 'M&M' AND ev.category = 'Candy')
복합 인덱싱 정책 예제
개별 속성에 대한 경로를 포함 또는 제외하는 것 외에, 복합 인덱스를 지정할 수도 있습니다. 여러 속성에 대한 절이 있는 쿼리를 ORDER BY 수행하려면 해당 속성에 복합 인덱스가 필요합니다. 쿼리에 여러 속성에 대한 정렬과 함께 필터가 포함된 경우 둘 이상의 복합 인덱스가 필요할 수 있습니다.
또한 복합 인덱스는 여러 필터가 있거나 필터와 ORDER BY 절이 모두 있는 쿼리에 대한 성능상의 이점이 있습니다.
비고
복합 경로는 해당 /? 경로의 스칼라 값만 인덱싱되므로 암시적입니다. 와일드카드는 /* 복합 경로에서 지원되지 않습니다.
/? 또는 /* 를 복합 경로에 지정하면 안 됩니다. 복합 경로도 대/소문자를 구분합니다.
(name asc, age desc)에 대해 정의된 복합 인덱스
{
"automatic":true,
"indexingMode":"Consistent",
"includedPaths":[
{
"path":"/*"
}
],
"excludedPaths":[],
"compositeIndexes":[
[
{
"path":"/name",
"order":"ascending"
},
{
"path":"/age",
"order":"descending"
}
]
]
}
다음 쿼리에는 이름과 나이에 대한 복합 인덱스가 필요합니다.
쿼리 #1:
SELECT *
FROM c
ORDER BY c.name ASC, c.age DESC
쿼리 #2:
SELECT *
FROM c
ORDER BY c.name DESC, c.age ASC
이 복합 인덱스는 다음 쿼리에 이점을 제공하고 필터를 최적화합니다.
쿼리 #3:
SELECT *
FROM c
WHERE c.name = "Tim"
ORDER BY c.name DESC, c.age ASC
쿼리 #4:
SELECT *
FROM c
WHERE c.name = "Tim" AND c.age > 18
(name ASC, age ASC) 및 (name ASC, age DESC)에 대해 정의된 복합 인덱스
동일한 인덱싱 정책 내에서 여러 복합 인덱스를 정의할 수 있습니다.
{
"automatic":true,
"indexingMode":"Consistent",
"includedPaths":[
{
"path":"/*"
}
],
"excludedPaths":[],
"compositeIndexes":[
[
{
"path":"/name",
"order":"ascending"
},
{
"path":"/age",
"order":"ascending"
}
],
[
{
"path":"/name",
"order":"ascending"
},
{
"path":"/age",
"order":"descending"
}
]
]
}
(name ASC, age ASC)에 대해 정의된 복합 인덱스
순서를 지정하는 것은 선택 사항입니다. 지정하지 않으면 순서는 오름차순입니다.
{
"automatic":true,
"indexingMode":"Consistent",
"includedPaths":[
{
"path":"/*"
}
],
"excludedPaths":[],
"compositeIndexes":[
[
{
"path":"/name"
},
{
"path":"/age"
}
]
]
}
모든 속성 경로를 제외하지만 인덱싱을 활성 상태로 유지
TTL(Time to Live) 기능이 활성화되어 있지만 Azure Cosmos DB를 순수 키-값 저장소로 사용하는 데 다른 인덱스가 필요하지 않은 경우 이 정책을 사용할 수 있습니다.
{
"indexingMode": "consistent",
"includedPaths": [],
"excludedPaths": [{
"path": "/*"
}]
}
인덱싱 안 함
이 정책은 인덱싱을 해제합니다.
indexingMode가 none으로 설정된 경우 컨테이너에 TTL을 설정할 수 없습니다.
{
"indexingMode": "none"
}
인덱싱 정책 업데이트
Azure Cosmos DB에서 다음 방법 중 하나를 사용하여 인덱싱 정책을 업데이트할 수 있습니다.
- Azure Portal에서
- Azure CLI 사용
- PowerShell 사용
- SDK 중 하나 사용
인덱싱 정책 업데이트는 인덱스 변환을 트리거합니다. SDK를 사용하여 이 변환의 진행률을 추적할 수도 있습니다.
비고
인덱싱 정책을 업데이트하면 Azure Cosmos DB에 대한 쓰기가 중단되지 않습니다. 인덱싱 변환에 대해 자세히 알아봅니다.
중요합니다
인덱스 제거는 즉시 적용되는 반면 새 인덱스를 추가하려면 인덱싱 변환이 필요하기 때문에 다소 시간이 걸립니다. 한 인덱을 다른 인덱스로 바꾸는 경우(예: 단일 속성 인덱스가 복합 인덱스로 바뀐 경우) 먼저 새 인덱을 추가한 다음 인덱스 변환이 완료되기 를 기다렸다가 인덱싱 정책에서 이전 인덱스가 제거됩니다. 그렇지 않으면 이전 인덱스를 쿼리하는 기능에 부정적인 영향을 미치며 이전 인덱스를 참조하는 활성 워크로드가 중단될 수 있습니다.
Azure Portal 사용
Azure Cosmos DB 컨테이너는 자체의 인덱싱 정책을 Azure Portal에서 직접 편집할 수 있는 JSON 문서로 저장합니다.
Azure Portal에 로그인합니다.
새 Azure Cosmos DB 계정을 만들거나 기존 계정을 선택합니다.
데이터 탐색기 창을 열고 작업할 컨테이너를 선택합니다.
설정을 선택한 다음, 인덱싱 정책을 선택합니다.
다음 예제와 같이 인덱싱 정책 JSON 문서를 수정 합니다.
완료되면 저장을 선택합니다.
Azure CLI 사용
사용자 지정 인덱싱 정책을 사용하여 컨테이너를 만들려면 CLI를 사용하여 사용자 지정 인덱스 정책을 사용하여 컨테이너 만들기를 참조하세요.
PowerShell 사용
사용자 지정 인덱싱 정책을 사용하여 컨테이너를 만들려면 PowerShell을 사용하여 사용자 지정 인덱스 정책을 사용하여 컨테이너 만들기를 참조하세요.
.NET SDK 사용
ContainerProperties 개체에서 .NET SDK v3의 IndexingPolicy 속성을 노출하여 IndexingMode를 변경하고 IncludedPaths와 ExcludedPaths를 추가하거나 제거할 수 있습니다. 자세한 내용은 빠른 시작: .NET용 Azure SDK와 함께 NoSQL용 Azure Cosmos DB 사용
// Retrieve the container's details
ContainerResponse containerResponse = await client.GetContainer("database", "container").ReadContainerAsync();
// Set the indexing mode to consistent
containerResponse.Resource.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
// Add an included path
containerResponse.Resource.IndexingPolicy.IncludedPaths.Add(new IncludedPath { Path = "/*" });
// Add an excluded path
containerResponse.Resource.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/name/*" });
// Add a spatial index
SpatialPath spatialPath = new SpatialPath
{
Path = "/locations/*"
};
spatialPath.SpatialTypes.Add(SpatialType.Point);
containerResponse.Resource.IndexingPolicy.SpatialIndexes.Add(spatialPath);
// Add a composite index
containerResponse.Resource.IndexingPolicy.CompositeIndexes.Add(new Collection<CompositePath> { new CompositePath() { Path = "/name", Order = CompositePathSortOrder.Ascending }, new CompositePath() { Path = "/age", Order = CompositePathSortOrder.Descending } });
// Update container with changes
await client.GetContainer("database", "container").ReplaceContainerAsync(containerResponse.Resource);
인덱스 변환 진행률을 추적하려면 RequestOptions 속성을 PopulateQuotaInfo로 설정하는 true 개체를 전달합니다.
x-ms-documentdb-collection-index-transformation-progress 응답 헤더에서 값을 검색합니다.
// retrieve the container's details
ContainerResponse containerResponse = await client.GetContainer("database", "container").ReadContainerAsync(new ContainerRequestOptions { PopulateQuotaInfo = true });
// retrieve the index transformation progress from the result
long indexTransformationProgress = long.Parse(containerResponse.Headers["x-ms-documentdb-collection-index-transformation-progress"]);
새 컨테이너를 만드는 동안 사용자 지정 인덱싱 정책을 정의할 때 SDK V3의 흐름 API를 사용하여 간결하고 효율적인 방식으로 이 정의를 작성할 수 있습니다.
await client.GetDatabase("database").DefineContainer(name: "container", partitionKeyPath: "/myPartitionKey")
.WithIndexingPolicy()
.WithIncludedPaths()
.Path("/*")
.Attach()
.WithExcludedPaths()
.Path("/name/*")
.Attach()
.WithSpatialIndex()
.Path("/locations/*", SpatialType.Point)
.Attach()
.WithCompositeIndex()
.Path("/name", CompositePathSortOrder.Ascending)
.Path("/age", CompositePathSortOrder.Descending)
.Attach()
.Attach()
.CreateIfNotExistsAsync();
Java SDK 사용
DocumentCollection의 개체는 getIndexingPolicy() 및 setIndexingPolicy() 메서드를 노출합니다. 해당 메서드가 조작하는 IndexingPolicy 개체를 사용하여 인덱싱 모드를 변경하고 포함된 경로 및 제외된 경로를 추가 또는 제거할 수 있습니다. 자세한 내용은 빠른 시작을 참조하세요. Java용 Azure SDK와 함께 NoSQL용 Azure Cosmos DB 사용
// Retrieve the container's details
Observable<ResourceResponse<DocumentCollection>> containerResponse = client.readCollection(String.format("/dbs/%s/colls/%s", "database", "container"), null);
containerResponse.subscribe(result -> {
DocumentCollection container = result.getResource();
IndexingPolicy indexingPolicy = container.getIndexingPolicy();
// Set the indexing mode to consistent
indexingPolicy.setIndexingMode(IndexingMode.Consistent);
// Add an included path
Collection<IncludedPath> includedPaths = new ArrayList<>();
IncludedPath includedPath = new IncludedPath();
includedPath.setPath("/*");
includedPaths.add(includedPath);
indexingPolicy.setIncludedPaths(includedPaths);
// Add an excluded path
Collection<ExcludedPath> excludedPaths = new ArrayList<>();
ExcludedPath excludedPath = new ExcludedPath();
excludedPath.setPath("/name/*");
excludedPaths.add(excludedPath);
indexingPolicy.setExcludedPaths(excludedPaths);
// Add a spatial index
Collection<SpatialSpec> spatialIndexes = new ArrayList<SpatialSpec>();
Collection<SpatialType> collectionOfSpatialTypes = new ArrayList<SpatialType>();
SpatialSpec spec = new SpatialSpec();
spec.setPath("/locations/*");
collectionOfSpatialTypes.add(SpatialType.Point);
spec.setSpatialTypes(collectionOfSpatialTypes);
spatialIndexes.add(spec);
indexingPolicy.setSpatialIndexes(spatialIndexes);
// Add a composite index
Collection<ArrayList<CompositePath>> compositeIndexes = new ArrayList<>();
ArrayList<CompositePath> compositePaths = new ArrayList<>();
CompositePath nameCompositePath = new CompositePath();
nameCompositePath.setPath("/name");
nameCompositePath.setOrder(CompositePathSortOrder.Ascending);
CompositePath ageCompositePath = new CompositePath();
ageCompositePath.setPath("/age");
ageCompositePath.setOrder(CompositePathSortOrder.Descending);
compositePaths.add(ageCompositePath);
compositePaths.add(nameCompositePath);
compositeIndexes.add(compositePaths);
indexingPolicy.setCompositeIndexes(compositeIndexes);
// Update the container with changes
client.replaceCollection(container, null);
});
컨테이너에서 인덱스 변환 진행률을 추적하려면 채워질 할당량 정보를 요청하는 RequestOptions 개체를 전달합니다.
x-ms-documentdb-collection-index-transformation-progress 응답 헤더에서 값을 검색합니다.
// set the RequestOptions object
RequestOptions requestOptions = new RequestOptions();
requestOptions.setPopulateQuotaInfo(true);
// retrieve the container's details
Observable<ResourceResponse<DocumentCollection>> containerResponse = client.readCollection(String.format("/dbs/%s/colls/%s", "database", "container"), requestOptions);
containerResponse.subscribe(result -> {
// retrieve the index transformation progress from the response headers
String indexTransformationProgress = result.getResponseHeaders().get("x-ms-documentdb-collection-index-transformation-progress");
});
Node.js SDK 사용
ContainerDefinition의 인터페이스는 indexingPolicy를 변경하고 indexingMode 및 includedPaths를 추가하거나 제거할 수 있는 excludedPaths 속성을 노출합니다. 자세한 내용은 빠른 시작을 참조하세요. Node.jsAzure SDK와 함께 NoSQL용 Azure Cosmos DB를 사용합니다 .
컨테이너의 세부 정보 검색:
const containerResponse = await client.database('database').container('container').read();
인덱싱 모드를 일관되게 설정:
containerResponse.body.indexingPolicy.indexingMode = "consistent";
공간 인덱스를 포함하여 포함된 경로 추가:
containerResponse.body.indexingPolicy.includedPaths.push({
includedPaths: [
{
path: "/age/*",
indexes: [
{
kind: cosmos.DocumentBase.IndexKind.Range,
dataType: cosmos.DocumentBase.DataType.String
},
{
kind: cosmos.DocumentBase.IndexKind.Range,
dataType: cosmos.DocumentBase.DataType.Number
}
]
},
{
path: "/locations/*",
indexes: [
{
kind: cosmos.DocumentBase.IndexKind.Spatial,
dataType: cosmos.DocumentBase.DataType.Point
}
]
}
]
});
제외된 경로 추가:
containerResponse.body.indexingPolicy.excludedPaths.push({ path: '/name/*' });
변경 내용으로 컨테이너 업데이트:
const replaceResponse = await client.database('database').container('container').replace(containerResponse.body);
컨테이너에서 인덱스 변환 진행률을 추적하려면 RequestOptions 속성을 populateQuotaInfo로 설정하는 true 개체를 전달합니다.
x-ms-documentdb-collection-index-transformation-progress 응답 헤더에서 값을 검색합니다.
// retrieve the container's details
const containerResponse = await client.database('database').container('container').read({
populateQuotaInfo: true
});
// retrieve the index transformation progress from the response headers
const indexTransformationProgress = replaceResponse.headers['x-ms-documentdb-collection-index-transformation-progress'];
복합 인덱스 추가:
console.log("create container with composite indexes");
const containerDefWithCompositeIndexes = {
id: "containerWithCompositeIndexingPolicy",
indexingPolicy: {
automatic: true,
indexingMode: IndexingMode.consistent,
includedPaths: [
{
path: "/*",
},
],
excludedPaths: [
{
path: '/"systemMetadata"/*',
},
],
compositeIndexes: [
[
{ path: "/field", order: "ascending" },
{ path: "/key", order: "ascending" },
],
],
},
};
const containerWithCompositeIndexes = (
await database.containers.create(containerDefWithCompositeIndexes)
).container;
Go SDK 사용
IndexingPolicy 구조체는 컨테이너에 대한 인덱싱 정책을 정의합니다. 새 컨테이너를 만들거나 기존 컨테이너를다시 구성할 때 사용할 수 있습니다.
db, _ := client.NewDatabase("demodb")
pkDefinition := azcosmos.PartitionKeyDefinition{
Paths: []string{"/state"},
Kind: azcosmos.PartitionKeyKindHash,
}
indexingPolicy := &azcosmos.IndexingPolicy{
IndexingMode: azcosmos.IndexingModeConsistent,
// add an included path
IncludedPaths: []azcosmos.IncludedPath{
{Path: "/*"},
},
// add an excluded path
ExcludedPaths: []azcosmos.ExcludedPath{
{Path: "/address/*"},
},
// add composite indices
CompositeIndexes: [][]azcosmos.CompositeIndex{
{
{
Path: "/name",
Order: azcosmos.CompositeIndexAscending,
},
{
Path: "/age",
Order: azcosmos.CompositeIndexDescending,
},
},
}
db.CreateContainer(context.Background(), azcosmos.ContainerProperties{
ID: "demo_container",
PartitionKeyDefinition: pkDefinition,
IndexingPolicy: indexingPolicy,
}, nil)
Python SDK 사용
Python SDK V3를 사용하면 컨테이너 구성이 사전으로 관리됩니다. 이 사전에서 인덱싱 정책 및 모든 특성에 액세스할 수 있습니다. 자세한 내용은 빠른 시작: Python용 Azure SDK와 함께 NoSQL용 Azure Cosmos DB 사용
컨테이너의 세부 정보 검색:
containerPath = 'dbs/database/colls/collection'
container = client.ReadContainer(containerPath)
인덱싱 모드를 일관되게 설정:
container['indexingPolicy']['indexingMode'] = 'consistent'
포함된 경로 및 공간 인덱스를 통해 인덱싱 정책 정의:
container["indexingPolicy"] = {
"indexingMode":"consistent",
"spatialIndexes":[
{"path":"/location/*","types":["Point"]}
],
"includedPaths":[{"path":"/age/*","indexes":[]}],
"excludedPaths":[{"path":"/*"}]
}
제외된 경로를 사용하여 인덱싱 정책 정의:
container["indexingPolicy"] = {
"indexingMode":"consistent",
"includedPaths":[{"path":"/*","indexes":[]}],
"excludedPaths":[{"path":"/name/*"}]
}
복합 인덱스 추가:
container['indexingPolicy']['compositeIndexes'] = [
[
{
"path": "/name",
"order": "ascending"
},
{
"path": "/age",
"order": "descending"
}
]
]
변경 내용으로 컨테이너 업데이트:
response = client.ReplaceContainer(containerPath, container)