إدارة نهج الفهرسة في Azure Cosmos DB

ينطبق على: واجهة برمجة تطبيقات SQL

في Azure Cosmos DB، تُفهرَس البيانات باتباع نهج الفهرسة المحددة لكل حاوية. يفرض نهج الفهرسة الافتراضي للحاويات المكونة حديثاً فهارس نطاقات لأي سلسلة أو رقم. يمكن أن يحل نهج فهرسة مخصص محل هذا النهج.

ملاحظة

لا تُستخدَم طريقة تحديث نهج الفهرسة الموضحة في هذه المقالة إلا على واجهة برمجة التطبيقات لـ SQL (الأساسية) في Azure Cosmos DB. تعرّف على الفهرسة في واجهة برمجة تطبيقات Azure Cosmos DB لـ MongoDB والفهرسة الثانوية في واجهة برمجة تطبيقات Cassandra لـ Azure Cosmos DB.

أمثلة عن نهج الفهرسة

فيما يلي بعض الأمثلة عن نهج الفهرسة الموضحة بتنسيق JSON، الذي يوضح طريقة عرضها على مدخل Microsoft Azure. يمكن تعيين المعلمات نفسها عن طريق CLI Azure أو SDK.

نهج إلغاء الاشتراك لاستبعاد بعض مسارات الخصائص بشكل انتقائي

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

يعادل نهج الفهرسة هذا النهج أدناه الذي عيّن القيم الافتراضية لـ kind وdataType وprecision يدوياً. لم يعد تعيين هذه الخصائص أمراً ضرورياً صراحة ويجب حذفها من نهج الفهرسة بالكامل (كما هو موضح في المثال أعلاه). إذا حاولت تعيين هذه الخصائص، فستُحذف تلقائياً من نهج الفهرسة.

    {
        "indexingMode": "consistent",
        "includedPaths": [
            {
                "path": "/*",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "Number",
                        "precision": -1
                    },
                    {
                        "kind": "Range",
                        "dataType": "String",
                        "precision": -1
                    }
                ]
            }
        ],
        "excludedPaths": [
            {
                "path": "/path/to/single/excluded/property/?"
            },
            {
                "path": "/path/to/root/of/multiple/excluded/properties/*"
            }
        ]
    }

نهج الاشتراك لتضمين بعض مسارات الخصائص بشكل انتقائي

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

يعادل نهج الفهرسة هذا النهج أدناه الذي عيّن القيم الافتراضية لـ kind وdataType وprecision يدوياً. لم يعد تعيين هذه الخصائص أمراً ضرورياً صراحة ويجب حذفها من نهج الفهرسة بالكامل (كما هو موضح في المثال أعلاه). إذا حاولت تعيين هذه الخصائص، فستُحذف تلقائياً من نهج الفهرسة.

    {
        "indexingMode": "consistent",
        "includedPaths": [
            {
                "path": "/path/to/included/property/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "Number"
                    },
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            },
            {
                "path": "/path/to/root/of/multiple/included/properties/*",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "Number"
                    },
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            }
        ],
        "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"
            ]
        }
    ]
}

أمثلة عن نهج الفهرسة المركبة

فضلاً عن تضمين مسارات خصائص فردية أو استبعادها، يمكنك أيضاً تحديد فهرس مُركب. إذا كنت ترغب في إجراء استعلام يحتوي على بند لخصائص متعددة، يلزم وجود ORDER BY على ORDER BY هذه الخصائص. بالإضافة إلى ذلك، ستتميز الفهارس المركبة بميزة أداء للاستعلامات التي تتضمن عوامل تصفية متعددة أو كلاً من عامل تصفية وعبارة ORDER BY.

ملاحظة

تتضمن المسارات المركبة /? ضمنية بسبب عدم فهرسة سوى القيمة العددية في هذا المسار فقط. الحرف البدل /* غير معتمد في المسارات المركبة. لا يجب تحديد /? أو /* في مسار مركب.

مؤشر مركب محدد لـ (الاسم تصاعدي، والعمر تنازلي):

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

يلزم توفير الفهرس المركب أعلاه على الاسم والعمر للاستعلامين رقم 1 و2:

الاستعلام رقم 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 و4 ويحسِّن عمل عوامل التصفية:

الاستعلام رقم 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

مؤشر مركب محدد لـ (الاسم تصاعدي، والعمر تصاعدي) و(الاسم تصاعدي، والعمر تنازلي):

يمكنك تحديد بعض الفهارس المركبة المختلفة المتعددة ضمن نهج الفهرسة نفسه.

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

مؤشر مركب محدد لـ (الاسم تصاعدي، والعمر تصاعدي):

إن تحديد الترتيب أمر اختياري. في حالة عدم تحديد الترتيب، يكون تصاعديًا.

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

استبعاد جميع مسارات الخصائص مع الإبقاء على الفهرسة نشطة

يمكن استخدام هذا النهج في الحالات التي تكون فيها ميزة فترة البقاء (TTL) نشطة لكن لا يلزم استخدام فهارس إضافية (لاستخدام Azure Cosmos DB كمخزن خالص لقيمة المفتاح).

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

لا توجد فهرسة

سيؤدي هذا النهج إلى إيقاف الفهرسة. في حالة تعيين indexingMode على none، لا يمكنك تعيين TTL في الحاوية.

    {
        "indexingMode": "none"
    }

تحديث نهج الفهرسة

في Azure Cosmos DB، يمكن تحديث نهج الفهرسة باستخدام أيٍّ من الطرق التالية:

  • من مدخل Azure
  • باستخدام Azure CLI
  • باستخدام PowerShell
  • باستخدام إحدى أدوات SDK

يؤدي تحديث نهج الفهرسة إلى بدء تحويل الفهرس. ويمكن أيضا تتبع تقدم هذا التحول من أدوات SDK.

ملاحظة

عند تحديث نهج الفهرسة، سيتم الكتابة إلى Azure Cosmos DB دون انقطاع. معرفة المزيد عن تحويلات الفهرسة

استخدام مدخل Microsoft Azure

تخزن حاويات Azure Cosmos نهج الفهرسة كمستند JSON يسمح لك مدخل Azure تحريره مباشرة.

  1. تسجيل الدخول إلى ⁧⁩مدخل Azure⁧⁩.

  2. أنشئ حساب Azure Cosmos جديدا أو حدد حسابا موجودا.

  3. افتح جزء مستكشف البيانات وحدد الحاوية التي تريد العمل عليها.

  4. انقر على مقياس الإعدادات.

  5. تعديل مستند JSON لنهج الفهرسة (انظر الأمثلة أدناه)

  6. انقر على "Save" عند الانتهاء.

Manage Indexing using Azure portal

استخدام Azure CLI

لإنشاء حاوية تحتوي على نهج فهرسة مخصص راجع إنشاء حاوية تحتوي على نهج فهرس مخصص باستخدام CLI

استخدام PowerShell

لإنشاء حاوية تحتوي على نهج فهرسة مخصص راجع إنشاء حاوية تحتوي على نهج فهرس مخصص باستخدام PowerShell

استخدم .NET SDK

يعرض الكائن DocumentCollection من . DocumentCollection خاصية IndexingPolicy تتيح لك تغيير IndexingMode وإضافة أو إزالة IncludedPaths و ExcludedPaths.

// Retrieve the container's details
ResourceResponse<DocumentCollection> containerResponse = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("database", "container"));
// 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
containerResponse.Resource.IndexingPolicy.SpatialIndexes.Add(new SpatialSpec() { Path = "/locations/*", SpatialTypes = new Collection<SpatialType>() { SpatialType.Point } } );
// 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.ReplaceDocumentCollectionAsync(containerResponse.Resource);

لتعقب تقدم تحويل الفهرس، مرر كائن RequestOptions الذي يعيِّن الخاصية PopulateQuotaInfo على true .

// retrieve the container's details
ResourceResponse<DocumentCollection> container = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("database", "container"), new RequestOptions { PopulateQuotaInfo = true });
// retrieve the index transformation progress from the result
long indexTransformationProgress = container.IndexTransformationProgress;

استخدام Java SDK

يعرض الكائن DocumentCollection من DocumentCollection (راجع هذا Quickstart فيما يتعلق باستخدامه) وأساليبهsetIndexingPolicy(). يسمح لك الكائن IndexingPolicy الذي يعالجونه تغيير وضع الفهرسة وإضافة مسارات مضمنة ومستبعدة أو إزالتها.

// 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 تعرض الواجهة من ContainerDefinition (راجع هذا التشغيل السريع فيما يتعلق باستخدامه) خاصية تتيح لك تغيير indexingMode وإضافة أو إزالة includedPaths و excludedPaths.

استرداد تفاصيل الحاوية

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

استخدام Python SDK

عند استخدام V3 SDK Python (راجع هذا التشغيل السريع فيما يتعلق باستخدامه)، يُدار تكوين الحاوية باعتباره قاموساً. ومن هذا القاموس، يمكن الوصول إلى نهج الفهرسة وجميع سماته.

استرداد تفاصيل الحاوية

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)

الخطوات التالية

قراءة المزيد عن الفهرسة في المقالات التالية: