2017-04-25 63 views
5

我正在構建.Net控制檯應用程序以讀取DocumentDB中的信息。控制檯應用程序具有來自EventHub的數據,並在進入雲時插入/更新最近的數據。Azure DocumentDB讀取文檔資源未找到

我想從DocumentDB讀取單數文檔,並且我可以在請求文檔之前確認文檔存在。

if (DocumentDBRepository<DocumentDBItem>.DoesItemExist(name)) 
{ 
    device = await DocumentDBRepository<DocumentDBItem>.GetItemAsync(name); 
} 

我用this教程從微軟關於建立一個存儲庫訪問DocumentDB紀錄,併成功地在使用幾乎所有的方法。我可以更新/刪除/查詢數據庫,但我無法讀取單個項目。

首先它拋出請求PartitionKey的異常。所以我修改了這個方法來將DB使用的PartitionKey添加到請求中。當我加入它拋出一個消息的另一個異常PartitionKey,「資源未找到」

public static async Task<T> GetItemAsync(string id) 
{ 
    try 
    { 
     RequestOptions options = new RequestOptions(); 
     options.PartitionKey = new PartitionKey("DeviceId"); 
     Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), options); 
     return (T)(dynamic)document; 
    } 
    catch (DocumentClientException e) 
    { 
     if (e.StatusCode == HttpStatusCode.NotFound) 
     { 
      return null; 
     } 
     else 
     { 
      throw; 
     } 
    } 
} 

PartitionKeyFromAzure

我已經修改了我的電話使用「GetItemsAsyc」,並得到文件的IEnumerable並獲得列表中的第一項,但它沒有意義,爲什麼我可以使用教程中的所有其他方法,但是這個方法繼續拋出異常,說「找不到資源」。

異常我越來越:

"Message: {\"Errors\":[\"Resource Not Found\"]}\r\nActivityId: e317ae66-6500-476c-b70e-c986c4cbf1d9, Request URI: /apps/e842e452-2347-4a8e-8588-2f5f8b4803ad/services/2c490552-a24d-4a9d-a786-992c07356545/partitions/0281cfdd-0c60-499f-be4a-289723a7dbf9/replicas/131336364114731886s" 
+0

這絕對是您正在尋找的文檔的正確分區鍵,我認爲您需要指定它的值(我在代碼中看不到)?我使用的代碼與您的代碼非常相似,除非沒有分區鍵(因爲我使用的是不支持它的較低優惠吞吐量),並且它工作正常。 –

+0

這是我用於數據庫的唯一分區鍵,並且傳遞給該方法的ID是Key作爲PartitionKey。在這種情況下'DeviceId'。 –

+0

在我的情況下,我將分區鍵保存爲一個整數,但是我將它作爲一個字符串進行搜索,因此無法工作。一旦我修好它的工作正常 – joalcego

回答

6

the documentation所示,您需要提供分區鍵的,存儲分區鍵的字段不是名稱。因此,您需要將設備ID作爲參數添加到您的方法中,並將其值傳遞給構造函數PartitionKey

從例如:

// Read document. Needs the partition key and the ID to be specified 
Document result = await client.ReadDocumentAsync(
    UriFactory.CreateDocumentUri("db", "coll", "XMS-001-FE24C"), 
    new RequestOptions { PartitionKey = new PartitionKey("XMS-0001") }); 

因此,對於你的代碼:

public static async Task<T> GetItemAsync(string id, string deviceId) 
{ 
    try 
    { 
     RequestOptions options = new RequestOptions(); 
     options.PartitionKey = new PartitionKey(deviceId); 
     Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), options); 
     return (T)(dynamic)document; 
    } 
    catch (DocumentClientException e) 
    { 
     if (e.StatusCode == HttpStatusCode.NotFound) 
     { 
      return null; 
     } 
     else 
     { 
      throw; 
     } 
    } 
} 
+1

這是我的問題。在我的情況下,Id和DeviceId是相同的。感謝您的幫助。昨天,我正在撞牆,試圖完成這個任務。 –

0

今天我確切的問題。

在讀取在文檔DB文件,
當格式的文檔鏈接(DBS/DBID ../colls/COLLID .. /文檔/文檔ID ..)

解決方案:
文檔客戶端拋出「資源未找到」2種情況:
1.收集ID錯誤
2. partitionKey給出了一些問題。也就是說,要麼給了不正確的partitionKey,要麼partitionKey不是必需的,而是給出了一個。