The following code retrieves all CrawlResult documents with a specific jobId.
var result = (from c in documentDb.CreateDocumentQuery<Shared.CrawlResult>(collection.SelfLink)
where c.JobId == jobId
select c);
Now I want to delete all documents with this specific jobId. The only way to delete documents I found was:
documentDb.DeleteDocumentAsync(string documentLink)
But how do I get the documentLink to execute the documentDb.DeleteDocumentAsync()
?
To do this, you need to write a SQL query so that you can dynamically access both the internal properties of Document, as well as CrawlResult.
For example, like in the following code:
class CrawlResult
{
[JsonProperty("jobId")]
public string JobId;
}
private async Task QueryAndDelete(DocumentClient client, string collectionLink)
{
await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J123" });
await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J456" });
foreach (Document document in client.CreateDocumentQuery(
collectionLink,
new SqlQuerySpec(
"SELECT * FROM crawlResults r WHERE r.jobId = @jobId",
new SqlParameterCollection(new[] { new SqlParameter { Name = "@jobId", Value = "J123" } })
)))
{
// Optionally, cast to CrawlResult using a dynamic cast
CrawlResult result = (CrawlResult)(dynamic)document;
await client.DeleteDocumentAsync(document.SelfLink);
}
}
Well, the official and efficient way is like follows:
First of all, you should create Client instance
private static DocumentClient Client
{
get
{
if (client == null)
{
string endpoint = ConfigurationManager.AppSettings["endpoint"];
string authKey = ConfigurationManager.AppSettings["authKey"];
Uri endpointUri = new Uri(endpoint);
client = new DocumentClient(endpointUri, authKey);
}
return client;
}
}
Next, you can reach the single document like this
private static Document GetDocument(string id)
{
return Client.CreateDocumentQuery(Collection.DocumentsLink)
.Where(d => d.Id == id)
.AsEnumerable()
.FirstOrDefault();
}
Then you can do every CRUD operators. In this case, you can use this
public static async Task DeleteAsync(string id)
{
Document doc = GetDocument(id);
await Client.DeleteDocumentAsync(doc.SelfLink);
}
To sum up, you can reach the document link after you get the Document instance. After that, you can find SelfLink attribute.
Cheers.
Look like I am a little bit too late, but here're something I've been working with.
public async Task Delete(object key)
{
var result = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(dbName, nameof(TEntity), key as string));
await _client.DeleteDocumentAsync(result.Resource.SelfLink);
}
Hope this help!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With