Search code examples
c#azure.net-coreazure-cognitive-search

.Net Core Azure cognitive search delete document


I am using Azure.Search.Documents package in my .Net Core 3.1 application to implement azure cognitive search. I have requirement where I have to delete existing data from document. I tried few ways by referring docs but none of them is working.

I have tried below approaches

Approach 1

var searchIndexClient = new SearchIndexClient(new Uri(<URI>), new AzureKeyCredential("XYZ"));

var searchClient = searchIndexClient.GetSearchClient(indexName);
var options = new IndexDocumentsOptions { ThrowOnAnyError = true };
var res = await searchClient.DeleteDocumentsAsync("Id", new List<string> { "1", "2", "3"}, options);

Approach 2:

var searchIndexClient = new SearchIndexClient(new Uri(<URI>), new AzureKeyCredential("XYZ"));

var searchClient = searchIndexClient.GetSearchClient(indexName);

var batch = IndexDocumentsBatch.Delete("Id", documents);

var options = new IndexDocumentsOptions { ThrowOnAnyError = true };
var res = await searchClient.IndexDocumentsAsync(batch, options);

When I am trying these approaches I am getting below error:

{
    "error": {
        "code": "MissingRequiredParameter",
        "message": "The request is invalid. Details: actions : No indexing actions found in the request. Please include between 1 and 32000 indexing actions in your request.",
        "details": [{
                "code": "MissingIndexDocumentsActions",
                "message": "No indexing actions found in the request. Please include between 1 and 32000 indexing actions in your request. Parameters: actions"
            }
        ]
    }
}

Any help is appreciated , Note : I want to do this using SDK only not with Rest API


Solution

  • DeleteDocumentsAsync will delete a complete document or a document in batch. IndexDocumentsBatch.Delete will perform document deletion in batch based on the key or a string value in the index.

    None of those methods will delete a document field values, only delete the full doc. If you need to delete existing fields from a document, consider IndexDocumentsAction.Merge and make sure the fields you would like to delete are null so the merge add nulls in the required fields and leave the rest as they are.

    More information here: https://learn.microsoft.com/azure/search/search-howto-dotnet-sdk