首页 文章

阅读可能不存在的Azure DocumentDB文档

提问于
浏览
8

我可以从Azure DocumentDB查询单个文档,如下所示:

var response = await client.ReadDocumentAsync( documentUri );

如果文档不存在,则会抛出DocumentClientException . 在我的程序中,我遇到的情况是文档可能存在,也可能不存在 . 是否有任何方法可以在不使用try-catch的情况下查询文档,而无需两次往返服务器,首先查询文档,然后检查文档是否存在?

2 回答

  • 7

    您专门查询给定的文档,并且 ReadDocumentAsync 将在找不到特定文档时返回 DocumentClientException (在状态代码中返回404) . 记录here . 通过捕捉异常(并看到它需要两次往返 .

    要绕过处理此异常,您需要使用 CreateDocumentQuery() 进行查询而不是离散读取 . 然后,您将获得一个可以枚举的结果集(即使该结果集为空) . 例如:

    var collLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
    var querySpec = new SqlQuerySpec { <querytext> };
    
    var itr = client.CreateDocumentQuery(collLink, querySpec).AsDocumentQuery();
    var response = await itr.ExecuteNextAsync<Document>();
    
    foreach (var doc in response.AsEnumerable())
    {
        // ...
    }
    

    使用这种方法,您需要添加 WHERE 子句以通过其ID查询特定文档,您将获得零结果或一个结果 .

  • 7

    遗憾的是没有其他办法,无论是处理异常还是进行2次调用,如果选择第二条路径,这里有一种以性能为导向的检查文档存在的方法:

    public bool ExistsDocument(string id)
    {
        var client = new DocumentClient(DatabaseUri, DatabaseKey);
        var collectionUri = UriFactory.CreateDocumentCollectionUri("dbName", "collectioName");
        var query = client.CreateDocumentQuery<Microsoft.Azure.Documents.Document>(collectionUri, new FeedOptions() { MaxItemCount = 1 });
        return query.Where(x => x.Id == id).Select(x=>x.Id).AsEnumerable().Any(); //using Linq
    }
    

    客户端应该在所有数据库访问方法中共享,但我在那里创建了一个自动足够的示例 .

    new FeedOptions () {MaxItemCount = 1} 将确保查询将针对1个结果进行优化(我们真的不需要更多) .

    如果你没有't specify it and the document exists, it will query and return all it'的信息, Select(x=>x.Id) 将确保没有返回其他数据 .

相关问题