未找到 Azure DocumentDB 读取文档资源

Azure DocumentDB Read Document Resource Not Found

我正在构建一个 .Net 控制台应用程序来读取 DocumentDB 中的信息。控制台应用程序有来自 EventHub 的数据和 inserts/updates 进入云端的最新数据。

我正在尝试从 DocumentDB 读取单个文档,并且我可以在请求文档之前确认该文档存在。

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

我使用了 Microsoft 的 this 教程来构建用于访问 DocumentDB 记录的存储库,并且成功地使用了几乎所有的方法。我可以 update/delete/query 数据库,但我无法阅读单个项目。

首先它抛出一个请求 PartitionKey 的异常。所以我修改了方法,将数据库使用的 PartitionKey 添加到请求中。一旦我添加了 PartitionKey,它就会抛出另一个异常并显示一条消息,"Resource Not Found"

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

我已经修改我的调用以使用 "GetItemsAsyc" 并获取 IEnumerable 文档并获取列表中的第一项,但我无法使用所有其他方法来自教程,但这个继续抛出异常说,"Resource Not Found"。

我得到异常:

"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"

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