如何删除索引中的所有文档

How to remove all documents in index

是否有任何简单的方法可以从 Azure 搜索索引中删除所有文档(或筛选列表或文档)?

我知道显而易见的答案是删除并重新创建索引,但我想知道是否还有其他选择。

不,目前无法从索引中删除所有文档。正如您所怀疑的那样,删除并重新创建索引是可行的方法。对于非常小的索引,您可以考虑单独删除文档,但考虑到应用程序通常已经有用于创建索引的代码,delete/recreate 是最快的路径。

有办法:查询所有文档,用IndexBatch删除这些家伙。

    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))}");
        }
    }
    //searchIndex - Index Name
    //KeyCol - Key column in the index
    public static void ResetIndex(string searchIndex, string KeyCol)
    {
        while (true)
        {
            SearchIndexClient indexClient = new SearchIndexClient(searchServiceName, searchIndex, new SearchCredentials(apiKey));
            DocumentSearchResult<Document> searchResult = indexClient.Documents.Search<Document>(string.Empty);
            List<string> azureDocsToDelete =
            searchResult
                .Results
                .Select(r => r.Document[KeyCol].ToString())
                .ToList();
            if(azureDocsToDelete.Count != 0)
            {
                try
                {
                    IndexBatch batch = IndexBatch.Delete(KeyCol, azureDocsToDelete);
                    var result = indexClient.Documents.Index(batch);
                }
                catch (IndexBatchException ex)
                {
                    throw new Exception($"Failed to reset the index: {string.Join(", ", ex.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key))}");
                }
            }
            else
            {
                break;
            }
        }
    }