Share via


在 Azure AI 搜尋中針對查詢編制來自 NoSQL 的 Azure Cosmos DB 索引數據

在本文中,了解如何設定索引子,從 Azure Cosmos DB for NoSQL 匯入內容,並使其可在 Azure AI 搜尋服務中搜尋。

本文提供 Cosmos DB 的特定資訊,用於補充建立索引子。 其中使用 REST API 來示範所有索引子通用的三部分工作流程:建立資料來源、建立索引、建立索引子。 提交建立索引子要求時會擷取資料。

因為術語可能會令人混淆,所以請注意 Azure Cosmos DB 編製索引Azure AI 搜尋服務編製索引是不同的作業。 Azure AI 搜尋服務中的編製索引會在您的搜尋服務上建立並載入搜尋索引。

必要條件

定義資料來源

資料來源定義指定要編製索引的資料、認證,以及用於識別資料變更的原則。 資料來源是獨立的資源,可供多個索引子使用。

  1. 建立或更新資料來源以設定其定義:

    POST https://[service name].search.windows.net/datasources?api-version=2023-11-01
    Content-Type: application/json
    api-key: [Search service admin key]
    {
        "name": "[my-cosmosdb-ds]",
        "type": "cosmosdb",
        "credentials": {
          "connectionString": "AccountEndpoint=https://[cosmos-account-name].documents.azure.com;AccountKey=[cosmos-account-key];Database=[cosmos-database-name]"
        },
        "container": {
          "name": "[my-cosmos-db-collection]",
          "query": null
        },
        "dataChangeDetectionPolicy": {
          "@odata.type": "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy",
        "  highWaterMarkColumnName": "_ts"
        },
        "dataDeletionDetectionPolicy": null,
        "encryptionKey": null,
        "identity": null
    }
    
  2. 將 "type" 設定為 "cosmosdb" (必要)。 如果您使用較舊的搜尋 API 版本 2017-11-11,則 "type" 的語法為 "documentdb"。 否則,若是 2019-05-06 和更新版本,則請使用 "cosmosdb"

  3. 將 "credentials" 設定為連接字串。 下一節說明支援的格式。

  4. 將 "container" 設定為集合。 需要 "name" 屬性,並指定要編製索引的資料庫集合識別碼。 「query」是選擇性屬性。 此屬性可用來壓平合併任意 JSON 文件,使其成為 Azure AI 搜尋服務可以編製索引的一般結構描述。

  5. 如果資料具有變動性,而且您希望索引子在後續執行時只挑選最新和更新的項目,請設定「dataChangeDetectionPolicy」

  6. 如果希望來源項目刪除後從搜尋索引中移除搜尋檔,請設定 "dataDeletionDetectionPolicy"

支援的認證和連接字串

索引子可以使用下列連線來連線到集合。

請避免在端點 URL 中使用連接埠號碼。 如果您包含埠號碼,連線將會失敗。

完整存取連接字串
{ "connectionString" : "AccountEndpoint=https://<Cosmos DB account name>.documents.azure.com;AccountKey=<Cosmos DB auth key>;Database=<Cosmos DB database id>" }'
您可以從 Azure 入口網站的 [Azure Cosmos DB 帳戶] 頁面,在左側瀏覽窗格中選取 [金鑰],以取得連接字串。 請務必選取完整的連接字串,而不只是金鑰。
受控識別連接字串
{ "connectionString" : "ResourceId=/subscriptions/<your subscription ID>/resourceGroups/<your resource group name>/providers/Microsoft.DocumentDB/databaseAccounts/<your cosmos db account name>/;(ApiKind=[api-kind];)/(IdentityAuthType=[identity-auth-type])" }
此連接字串不需要帳戶金鑰,但您必須具有一個可以使用受控識別連線的搜尋服務。 針對以 SQL API 為目標的連線,您可以從連接字串中省略 ApiKind。 如需 ApiKindIdentityAuthType 的詳細資訊,請參閱使用受控識別設定 Azure Cosmos DB 資料庫的索引子連線

使用查詢來形塑索引的資料

在 "container" 底下的 "query" 屬性中,您可以指定 SQL 查詢來壓平合併巢狀屬性或陣列、投影 JSON 屬性,以及篩選要編製索引的資料。

範例文件︰

    {
        "userId": 10001,
        "contact": {
            "firstName": "andy",
            "lastName": "hoh"
        },
        "company": "microsoft",
        "tags": ["azure", "cosmosdb", "search"]
    }

篩選查詢:

SELECT * FROM c WHERE c.company = "microsoft" and c._ts >= @HighWaterMark ORDER BY c._ts

壓平合併查詢︰

SELECT c.id, c.userId, c.contact.firstName, c.contact.lastName, c.company, c._ts FROM c WHERE c._ts >= @HighWaterMark ORDER BY c._ts

投影查詢:

SELECT VALUE { "id":c.id, "Name":c.contact.firstName, "Company":c.company, "_ts":c._ts } FROM c WHERE c._ts >= @HighWaterMark ORDER BY c._ts

陣列壓平合併查詢︰

SELECT c.id, c.userId, tag, c._ts FROM c JOIN tag IN c.tags WHERE c._ts >= @HighWaterMark ORDER BY c._ts

不受支援的查詢 (DISTINCT 和 GROUP BY)

不支援使用 DISTINCT 關鍵字GROUP BY 子句的查詢。 Azure AI 搜尋服務依賴 SQL 查詢分頁來完整列舉查詢的結果。 DISTINCT 關鍵字或 GROUP BY 子句都無法與用來將結果分頁的接續權杖相容。

不受支援的查詢範例:

SELECT DISTINCT c.id, c.userId, c._ts FROM c WHERE c._ts >= @HighWaterMark ORDER BY c._ts

SELECT DISTINCT VALUE c.name FROM c ORDER BY c.name

SELECT TOP 4 COUNT(1) AS foodGroupCount, f.foodGroup FROM Food f GROUP BY f.foodGroup

雖然 Azure Cosmos DB 有因應措施可支援使用 ORDER BY 子句與 DISTINCT 關鍵字來進行 SQL 查詢分頁,但此因應措施無法與 Azure AI 搜尋服務相容。 查詢會傳回單一 JSON 值,但 Azure AI 搜尋服務預期的是 JSON 物件。

-- The following query returns a single JSON value and isn't supported by Azure AI Search
SELECT DISTINCT VALUE c.name FROM c ORDER BY c.name

新增搜尋欄位至索引

搜尋索引中,新增欄位以接受來源 JSON 文件或自訂查詢投影的輸出。 確定搜尋索引結構描述與來源資料相容。 針對 Azure Cosmos DB 中的內容,您的搜尋索引結構描述應對應至資料來源中的 Azure Cosmos DB 項目

  1. 建立或更新索引,以定義儲存資料的搜尋欄位:

    POST https://[service name].search.windows.net/indexes?api-version=2023-11-01
    Content-Type: application/json
    api-key: [Search service admin key]
    {
        "name": "mysearchindex",
        "fields": [{
            "name": "rid",
            "type": "Edm.String",
            "key": true,
            "searchable": false
        }, 
        {
            "name": "description",
            "type": "Edm.String",
            "filterable": false,
            "searchable": true,
            "sortable": false,
            "facetable": false,
            "suggestions": true
        }
      ]
    }
    
  2. 建立文件索引鍵欄位 ("key": true)。 針對分割的集合,預設文件索引鍵是 Azure Cosmos DB 的 _rid 屬性,Azure AI 搜尋服務會自動將該屬性重新命名為 rid,因為欄位名稱不能以底線字元開頭。 此外,Azure Cosmos DB _rid 值包含 Azure AI 搜尋服務索引鍵中無效的字元。 因此,_rid 值採用 Base64 編碼。

  3. 建立更多欄位以取得更多可搜尋的內容。 如需詳細資訊,請參閱建立索引

對應資料類型

JSON 資料類型 Azure AI 搜尋服務欄位類型
Bool Edm.Boolean、Edm.String
看起來像是整數的數字 Edm.Int32、Edm.Int64、Edm.String
看起來像是浮點的數字 Edm.Double、Edm.String
String Edm.String
基本類型的陣列,例如 ["a"、"b"、"c"] Collection(Edm.String)
看起來像是日期的字串 Edm.DateTimeOffset、Edm.String
GeoJSON 物件,例如 { "type": "Point", "coordinates": [long, lat] } Edm.GeographyPoint
其他 JSON 物件 N/A

設定和執行適用於 NoSQL 的 Azure Cosmos DB 索引器

建立索引與資料來源之後,您就可以開始建立索引子。 索引子會設定指定輸入、參數和屬性,控制執行階段行為。

  1. 建立或更新索引子,指定其名稱並參考資料來源和目標索引:

    POST https://[service name].search.windows.net/indexers?api-version=2023-11-01
    Content-Type: application/json
    api-key: [search service admin key]
    {
        "name" : "[my-cosmosdb-indexer]",
        "dataSourceName" : "[my-cosmosdb-ds]",
        "targetIndexName" : "[my-search-index]",
        "disabled": null,
        "schedule": null,
        "parameters": {
            "batchSize": null,
            "maxFailedItems": 0,
            "maxFailedItemsPerBatch": 0,
            "base64EncodeKeys": false,
            "configuration": {}
            },
        "fieldMappings": [],
        "encryptionKey": null
    }
    
  2. 如果欄位名稱或類型有差異,或如果您在搜尋索引中需要來源欄位的多個版本,請指定欄位對應

  3. 如需其他屬性的詳細資訊,請參閱建立索引子

索引子建立後會自動執行。 您可以將「停用」設為 true 避免此情況。 若要控制索引子執行,請視需要執行索引子排程執行索引子

檢查索引子狀態

若要監視索引子狀態和執行歷程記錄,請傳送取得索引子狀態要求:

GET https://myservice.search.windows.net/indexers/myindexer/status?api-version=2023-11-01
  Content-Type: application/json  
  api-key: [admin key]

回應包含狀態和已處理的項目數目。 回應會類似於下列範例:

    {
        "status":"running",
        "lastResult": {
            "status":"success",
            "errorMessage":null,
            "startTime":"2022-02-21T00:23:24.957Z",
            "endTime":"2022-02-21T00:36:47.752Z",
            "errors":[],
            "itemsProcessed":1599501,
            "itemsFailed":0,
            "initialTrackingState":null,
            "finalTrackingState":null
        },
        "executionHistory":
        [
            {
                "status":"success",
                "errorMessage":null,
                "startTime":"2022-02-21T00:23:24.957Z",
                "endTime":"2022-02-21T00:36:47.752Z",
                "errors":[],
                "itemsProcessed":1599501,
                "itemsFailed":0,
                "initialTrackingState":null,
                "finalTrackingState":null
            },
            ... earlier history items
        ]
    }

執行歷程記錄包含最多 50 個最近完成的執行,以顛倒的時序排序,因此最後的執行最先出現。

編製新增和已變更文件的索引

在索引子完全填入搜尋索引之後,您可能希望後續的索引子以增量方式,為資料庫中新增和變更的文件編製索引。

若要啟用遞增索引編製,請在資料來源定義中設定「dataChangeDetectionPolicy」屬性。 這個屬性會告知索引子在您的資料上要使用哪種變更追蹤機制。

針對 Azure Cosmos DB 索引子,唯一支援的原則是使用 _ts (時間戳記) Azure Cosmos DB 所提供屬性的 HighWaterMarkChangeDetectionPolicy

下列範例顯示具有變更偵測原則的資料來源定義

"dataChangeDetectionPolicy": {
    "@odata.type": "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy",
"  highWaterMarkColumnName": "_ts"
},

累加式索引編製與自訂查詢

如果您使用自訂查詢來擷取文件,請確定查詢會依 _ts 資料行來排序結果。 如此會啟用定期檢查點設置,出現失敗時,Azure AI 搜尋服務會以此提供累加進度來應對。

在某些情況下,即使您的查詢含有 ORDER BY [collection alias]._ts 子句,Azure AI 搜尋服務仍可能無法推斷此查詢是否依 _ts 排序。 您可以設定 assumeOrderByHighWaterMarkColumn 組態屬性,告知 Azure AI 搜尋服務已排序結果。

若要指定這項提示,請依下列指示建立或更新您的索引子定義

{
    ... other indexer definition properties
    "parameters" : {
        "configuration" : { "assumeOrderByHighWaterMarkColumn" : true } }
} 

索引已刪除的文件

從集合中刪除資料列時,通常也會想刪除搜尋索引內的那些資料列。 資料刪除偵測原則可用來有效識別刪除的資料項目。 目前,唯一支援的原則是「Soft Delete」原則 (刪除會標示為某種形式的旗標),在資料來源定義中指定方式如下:

"dataDeletionDetectionPolicy"": {
    "@odata.type" : "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy",
    "softDeleteColumnName" : "the property that specifies whether a document was deleted",
    "softDeleteMarkerValue" : "the value that identifies a document as deleted"
}

如果您使用自訂查詢,請確定查詢有投射到 softDeleteColumnName 參考的屬性。

softDeleteColumnName必須是索引中的最上層欄位。 不支援在複雜數據類型 softDeleteColumnName 中使用巢狀欄位。

下列範例會建立包含虛刪除原則的資料來源:

POST https://[service name].search.windows.net/datasources?api-version=2023-11-01
Content-Type: application/json
api-key: [Search service admin key]

{
    "name": "[my-cosmosdb-ds]",
    "type": "cosmosdb",
    "credentials": {
        "connectionString": "AccountEndpoint=https://[cosmos-account-name].documents.azure.com;AccountKey=[cosmos-account-key];Database=[cosmos-database-name]"
    },
    "container": { "name": "[my-cosmos-collection]" },
    "dataChangeDetectionPolicy": {
        "@odata.type": "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy",
        "highWaterMarkColumnName": "_ts"
    },
    "dataDeletionDetectionPolicy": {
        "@odata.type": "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy",
        "softDeleteColumnName": "isDeleted",
        "softDeleteMarkerValue": "true"
    }
}

使用 .NET

針對透過 SQL API 通訊協定來存取的資料,您可以使用 .NET SDK 來透過索引子進行自動化。 建議您檢閱先前的 REST API 章節,以了解其概念、工作流程和需求。 然後,您可以參閱下列 .NET API 參考文件,以在受控程式碼中實作 JSON 索引子:

下一步

您現在可以控制如何執行索引子監視狀態排程索引子執行。 下列文章適用於從 Azure Cosmos DB 提取內容的索引子: