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

时间:2015-02-04 16:54:45

标签: azure-search

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

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

3 个答案:

答案 0 :(得分:5)

不,目前无法从索引中删除所有文档。因为您怀疑删除并重新创建索引是要走的路。对于非常小的索引,您可以考虑单独删除文档,但考虑到应用程序通常具有用于创建索引的代码,删除/重新创建是最快的路径。

答案 1 :(得分:3)

有一种方法:查询所有文档,并使用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))}");
        }
    }

答案 2 :(得分:1)

    //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;
            }
        }
    }