Kebijakan pengindeksan di Azure Cosmos DB

BERLAKU UNTUK: NoSQL

Di Azure Cosmos DB, data diindeks mengikuti kebijakan pengindeksan yang ditentukan untuk tiap-tiap kontainer. Kebijakan pengindeksan default untuk kontainer yang baru dibuat memberlakukan indeks rentang untuk string atau nomor apa pun. Anda dapat mengambil alih kebijakan ini dengan kebijakan pengindeksan kustom Anda sendiri.

Catatan

Metode memperbarui kebijakan pengindeksan yang dijelaskan dalam artikel ini hanya berlaku untuk Azure Cosmos DB untuk NoSQL. Pelajari tentang pengindeksan di Azure Cosmos DB untuk MongoDB dan Pengindeksan Sekunder di Azure Cosmos DB untuk Apache Cassandra.

Contoh kebijakan pengindeksan

Berikut adalah beberapa contoh kebijakan pengindeksan yang ditampilkan dalam format JSON mereka. Mereka diekspos pada portal Azure dalam format JSON. Parameter yang sama dapat diatur melalui Azure CLI atau SDK apa pun.

Kebijakan Opt-out untuk mengecualikan beberapa jalur properti secara selektif

{
    "indexingMode": "consistent",
    "includedPaths": [
        {
            "path": "/*"
        }
    ],
    "excludedPaths": [
        {
            "path": "/path/to/single/excluded/property/?"
        },
        {
            "path": "/path/to/root/of/multiple/excluded/properties/*"
        }
    ]
}

Kebijakan menolak untuk secara selektif menyertakan beberapa jalur properti

{
    "indexingMode": "consistent",
    "includedPaths": [
        {
            "path": "/path/to/included/property/?"
        },
        {
            "path": "/path/to/root/of/multiple/included/properties/*"
        }
    ],
    "excludedPaths": [
        {
            "path": "/*"
        }
    ]
}

Catatan

Kami umumnya menyarankan agar Anda menggunakan kebijakan pengindeksan penolakan . Azure Cosmos DB secara proaktif mengindeks properti baru apa pun yang mungkin ditambahkan ke model data Anda.

Menggunakan indeks spasial pada jalur properti tertentu saja

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*"
        }
    ],
    "excludedPaths": [
        {
            "path": "/_etag/?"
        }
    ],
    "spatialIndexes": [
        {
            "path": "/path/to/geojson/property/?",
            "types": [
                "Point",
                "Polygon",
                "MultiPolygon",
                "LineString"
            ]
        }
    ]
}

Contoh kebijakan pengindeksan komposit

Selain menyertakan atau mengecualikan jalur untuk properti individual, Anda juga dapat menentukan indeks komposit. Untuk melakukan kueri yang memiliki ORDER BY klausa untuk beberapa properti, indeks komposit diperlukan pada properti tersebut. Jika kueri menyertakan filter bersama dengan pengurutan pada beberapa properti, Anda mungkin memerlukan lebih dari satu indeks komposit.

Indeks komposit juga memiliki manfaat performa untuk kueri yang memiliki beberapa filter atau filter dan klausa ORDER BY.

Catatan

Jalur komposit memiliki implisit /? karena hanya nilai skalar pada jalur tersebut yang diindeks. Wildcard /* tidak didukung dalam jalur komposit. Anda tidak boleh menentukan /? atau /* di dalam jalur komposit. Jalur komposit juga peka huruf besar/kecil.

Indeks komposit didefinisikan untuk (nama asc, usia desc)

{  
    "automatic":true,
    "indexingMode":"Consistent",
    "includedPaths":[  
        {  
            "path":"/*"
        }
    ],
    "excludedPaths":[],
    "compositeIndexes":[  
        [  
            {  
                "path":"/name",
                "order":"ascending"
            },
            {  
                "path":"/age",
                "order":"descending"
            }
        ]
    ]
}

Indeks komposit pada nama dan usia diperlukan untuk kueri berikut:

Kueri #1:

SELECT *
FROM c
ORDER BY c.name ASC, c.age DESC

Kueri #2:

SELECT *
FROM c
ORDER BY c.name DESC, c.age ASC

Indeks komposit ini menguntungkan kueri berikut dan mengoptimalkan filter:

Kueri #3:

SELECT *
FROM c
WHERE c.name = "Tim"
ORDER BY c.name DESC, c.age ASC

Kueri #4:

SELECT *
FROM c
WHERE c.name = "Tim" AND c.age > 18

Indeks komposit yang didefinisikan untuk (nama ASC, usia ASC) dan (nama ASC, usia DESC)

Anda dapat menentukan beberapa indeks komposit dalam kebijakan pengindeksan yang sama.

{  
    "automatic":true,
    "indexingMode":"Consistent",
    "includedPaths":[  
        {  
            "path":"/*"
        }
    ],
    "excludedPaths":[],
    "compositeIndexes":[  
        [  
            {  
                "path":"/name",
                "order":"ascending"
            },
            {  
                "path":"/age",
                "order":"ascending"
            }
        ],
        [  
            {  
                "path":"/name",
                "order":"ascending"
            },
            {  
                "path":"/age",
                "order":"descending"
            }
        ]
    ]
}

Indeks komposit yang ditentukan untuk (nama ASC, usia ASC)

Ini opsional untuk menentukan pesanan. Jika tidak ditentukan, urutan yang digunakan adalah urutan naik.

{  
    "automatic":true,
    "indexingMode":"Consistent",
    "includedPaths":[  
        {  
            "path":"/*"
        }
    ],
    "excludedPaths":[],
    "compositeIndexes":[  
        [  
            {  
               "path":"/name"
            },
            {  
               "path":"/age"
            }
        ]
    ]
}

Mengecualikan semua jalur properti tetapi menjaga pengindeksan tetap aktif

Anda dapat menggunakan kebijakan ini di mana fitur Time-to-Live (TTL) aktif tetapi tidak ada indeks lain yang diperlukan untuk menggunakan Azure Cosmos DB sebagai penyimpanan kunci-nilai murni.

{
    "indexingMode": "consistent",
    "includedPaths": [],
    "excludedPaths": [{
        "path": "/*"
    }]
}

Tidak ada pengindeksan

Kebijakan ini menonaktifkan pengindeksan. Jika indexingMode diatur ke none, Anda tidak dapat mengatur TTL pada kontainer.

{
    "indexingMode": "none"
}

Memperbarui kebijakan pengindeksan

Di Azure Cosmos DB, kebijakan pengindeksan dapat diperbarui menggunakan salah satu metode berikut:

  • Dari Azure portal
  • Menggunakan Cli Azure
  • Menggunakan PowerShell
  • Menggunakan salah satu SDK

Pembaruan kebijakan pengindeksan memicu transformasi indeks. Kemajuan transformasi ini juga dapat dilacak dari SDK.

Catatan

Saat Anda memperbarui kebijakan pengindeksan, penulisan ke Azure Cosmos DB tidak terganggu. Pelajari selengkapnya tentang pengindeksan transformasi

Penting

Menghapus indeks akan segera memengaruhi, sedangkan menambahkan indeks baru membutuhkan waktu karena memerlukan transformasi pengindeksan. Saat mengganti satu indeks dengan indeks lain (misalnya, mengganti indeks properti tunggal dengan indeks komposit) pastikan untuk menambahkan indeks baru terlebih dahulu lalu menunggu transformasi indeks selesai sebelum Anda menghapus indeks sebelumnya dari kebijakan pengindeksan. Jika tidak, ini akan berdampak negatif pada kemampuan Anda untuk mengkueri indeks sebelumnya dan dapat merusak beban kerja aktif apa pun yang mereferensikan indeks sebelumnya.

Menggunakan portal Azure

Kontainer Azure Cosmos DB menyimpan kebijakan pengindeksan mereka sebagai dokumen JSON yang portal Azure memungkinkan Anda mengedit secara langsung.

  1. Masuk ke portal Azure.

  2. Buat akun Azure Cosmos DB baru atau pilih akun yang sudah ada.

  3. Masuk ke panel Data Explorer, lalu pilih kontainer yang ingin Anda kerjakan.

  4. Pilih Skala & Pengaturan.

  5. Ubah dokumen JSON kebijakan pengindeksan, seperti yang ditunjukkan dalam contoh-contoh ini.

  6. Pilih Simpan saat Anda selesai.

Manage Indexing using Azure portal

Menggunakan Azure CLI

Untuk membuat kontainer dengan kebijakan pengindeksan kustom, lihat Membuat kontainer dengan kebijakan indeks kustom menggunakan CLI.

Menggunakan PowerShell

Untuk membuat kontainer dengan kebijakan pengindeksan kustom, lihat Membuat kontainer dengan kebijakan indeks kustom menggunakan PowerShell.

Menggunakan .NET SDK

Objek ContainerProperties dari .NET SDK v3 mengekspos IndexingPolicy properti yang memungkinkan Anda mengubah IndexingMode dan menambahkan atau menghapus IncludedPaths dan ExcludedPaths. Untuk informasi selengkapnya, lihat Mulai Cepat: Azure Cosmos DB untuk pustaka klien NoSQL untuk .NET.

// 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);

Untuk melacak kemajuan transformasi indeks, lewati objek RequestOptions yang mengatur properti PopulateQuotaInfo ke true. Ambil nilai dari x-ms-documentdb-collection-index-transformation-progress header respons.

// 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"]);

API fasih SDK V3 memungkinkan Anda menulis definisi ini dengan cara yang ringkas dan efisien saat menentukan kebijakan pengindeksan kustom saat membuat kontainer baru:

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();

Menggunakan Java SDK

Objek DocumentCollection dari Java SDK mengekspos getIndexingPolicy() metode dan setIndexingPolicy() . Objek IndexingPolicy yang dimanipulasi memungkinkan Anda mengubah mode pengindeksan dan menambahkan atau menghapus jalur yang disertakan dan dikecualikan. Untuk informasi selengkapnya, lihat Mulai Cepat: Membuat aplikasi Java untuk mengelola data Azure Cosmos DB for NoSQL.

// 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);
});

Untuk melacak kemajuan transformasi indeks pada kontainer, berikan RequestOptions objek yang meminta info kuota diisi. Ambil nilai dari x-ms-documentdb-collection-index-transformation-progress header respons.

// 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");
});

Menggunakan Node.js SDK

Antarmuka ContainerDefinition dari Node.js SDK mengekspos indexingPolicy properti yang memungkinkan Anda mengubah indexingMode dan menambahkan atau menghapus includedPaths dan excludedPaths. Untuk informasi selengkapnya, lihat Mulai Cepat - Azure Cosmos DB untuk pustaka klien NoSQL untuk Node.js.

Ambil detail kontainer:

const containerResponse = await client.database('database').container('container').read();

Atur mode pengindeksan ke konsisten:

containerResponse.body.indexingPolicy.indexingMode = "consistent";

Tambahkan jalur yang disertakan termasuk indeks spasial:

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
          }
        ]
      }
    ]
  });

Tambahkan jalur yang dikecualikan:

containerResponse.body.indexingPolicy.excludedPaths.push({ path: '/name/*' });

Perbarui kontainer dengan perubahan:

const replaceResponse = await client.database('database').container('container').replace(containerResponse.body);

Untuk melacak kemajuan transformasi indeks pada kontainer, teruskan RequestOptions objek yang mengatur populateQuotaInfo properti ke true. Ambil nilai dari x-ms-documentdb-collection-index-transformation-progress header respons.

// 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'];

Menggunakan Python SDK

Saat Anda menggunakan Python SDK V3, konfigurasi kontainer dikelola sebagai kamus. Dari kamus ini, Anda dapat mengakses kebijakan pengindeksan dan semua atributnya. Untuk informasi selengkapnya, lihat Mulai Cepat: Azure Cosmos DB untuk pustaka klien NoSQL untuk Python.

Ambil detail kontainer:

containerPath = 'dbs/database/colls/collection'
container = client.ReadContainer(containerPath)

Atur mode pengindeksan ke konsisten:

container['indexingPolicy']['indexingMode'] = 'consistent'

Tentukan kebijakan pengindeksan dengan jalur yang disertakan dan indeks spasial:

container["indexingPolicy"] = {

    "indexingMode":"consistent",
    "spatialIndexes":[
                {"path":"/location/*","types":["Point"]}
             ],
    "includedPaths":[{"path":"/age/*","indexes":[]}],
    "excludedPaths":[{"path":"/*"}]
}

Tentukan kebijakan pengindeksan dengan jalur yang dikecualikan:

container["indexingPolicy"] = {
    "indexingMode":"consistent",
    "includedPaths":[{"path":"/*","indexes":[]}],
    "excludedPaths":[{"path":"/name/*"}]
}

Tambahkan indeks komposit:

container['indexingPolicy']['compositeIndexes'] = [
                [
                    {
                        "path": "/name",
                        "order": "ascending"
                    },
                    {
                        "path": "/age",
                        "order": "descending"
                    }
                ]
                ]

Perbarui kontainer dengan perubahan:

response = client.ReplaceContainer(containerPath, container)

Langkah berikutnya

Baca selengkapnya tentang pengindeksan di dalam artikel berikut ini: