Read an Azure DocumentDB Document That May Not Exist

I can request one document from Azure DocumentDB as follows:

var response = await client.ReadDocumentAsync( documentUri ); 

If the document does not exist, this will throw a DocumentClientException. In my program, I have a situation where a document may or may not exist. Is there a way to request a document without using try-catch and without two calls to the server, first to request a document, and the second to receive a document, if one exists?

+5
source share
2 answers

You specifically request for this document, and ReadDocumentAsync throw this DocumentClientException when it cannot find a specific document (returning 404 in the status code). This is described here . Having caught the exception (and seeing that it is 404), you will not need two round trip trips.

To get around this exception, you need to make a query instead of discrete reading with CreateDocumentQuery() . Then you just get a result set that you can list (even if this result set is empty). For instance:

 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()) { // ... } 

With this approach, you will not get any answers. In your specific case, where you will add a WHERE to request a specific document by its identifier, you will either get zero results, or one result.

+4
source

Unfortunately, there is no other way: either you handle the exception, or make 2 calls if you choose the second path, here is one way to check for the existence of a document:

 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 } 

The client should be split between all your DB-accesing methods, but I created it there to have an autosave example.

new FeedOptions () {MaxItemCount = 1} will ensure that the request is optimized for 1 result (we really don't need any more).

Select(x=>x.Id) guarantees that no other data will be returned, if you do not specify it and the document exists, it will request and return all the information.

+6
source

Source: https://habr.com/ru/post/1243318/


All Articles