How to remove all documents in index
There is a way: query all documents, and use IndexBatch to delete these guys.
public void DeleteAllDocuments()
{
// Get index
SearchIndexClient indexClient = new SearchIndexClient(SearchServiceName, SearchServiceIndex, new SearchCredentials(SearchServiceQueryApiKey));
// Query all
DocumentSearchResult<Document> searchResult;
try
{
searchResult = indexClient.Documents.Search<Document>(string.Empty);
}
catch (Exception ex)
{
throw new Exception("Error during AzureSearch");
}
List<string> azureDocsToDelete =
searchResult
.Results
.Select(r => r.Document["id"].ToString())
.ToList();
// Delete all
try
{
IndexBatch batch = IndexBatch.Delete("id", azureDocsToDelete);
var result = indexClient.Documents.Index(batch);
}
catch (IndexBatchException ex)
{
throw new Exception($"Failed to delete documents: {string.Join(", ", ex.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key))}");
}
}
No, currently there's no way to delete all the documents from an index. As you suspected deleting and re-creating the index is the way to go. For really small indexes you could consider deleting documents individually but given that often apps have code for index creation already, delete/recreate is the quickest path.