[Azure] C# 使用 Azure.Search.Documents Azure Blob 搜尋中的 JSON 資料 -刪除索引子資料

2022-07-19

上一篇文章,我們新增資料(上傳一個檔案),索引會自動加入該編號,只是我們多加上了重新執行索引,而不是等待原本的設定時間

今天,我們來討論一下,如果刪除資料(刪除該檔案)怎麼辦?


1. 首先我們要按照這文章建立資料 使用 Azure.Search.Documents Azure Blob 搜尋中的 JSON 資料 -建立環境 ,這裡面重要的是這兩步

索引鍵 設定為 Id ,還有這在最後一步

把 Base-64 編碼金鑰取消勾選,當然這不是必須,只是方便撰寫。


2.刪除資料,就是直接刪除 Blob 上面的資料,這邊我大概提供程式碼,我刪除 Id : USER994 的資料

private static void DeleteOneData() { var i = 994; var blobClient = new Azure.Storage.Blobs.BlobClient(ConnectionString, "test1000", "data/" + "data" + i + ".json"); var res = blobClient.DeleteIfExists().Value; Console.WriteLine("Delete Result:" + res); }




刪除後,我們重新再 Azure  後臺跑一次,執行索引子,發現其實沒有更新任何資料,這時候我們用程式跑一下搜尋 USER99開頭資料,你會發現

USER994 還在,目前唯一作法就是直接刪除索引子中的該資料

C# Delete Azure Search Indexer Data:


private static void DeleteOneDataIndex() { var indexClient = new Azure.Search.Documents.Indexes.SearchIndexClient(new Uri(SearchServiceEndPoint), new Azure.AzureKeyCredential(AdminApiKey)); var res = indexClient.GetSearchClient("azureblob-index").Search<User>("Id USER994"); var r = indexClient.GetSearchClient("azureblob-index").DeleteDocuments("Id", new string[] { "USER994" }); Console.WriteLine(r); }

這樣刪除後 USER994 就查不到了,不知道為什麼,寫到這的資料很少,是不是因為我的設計方式跟大家不太一樣總之大概就是這樣,

如果你建立環境,如果 base64編碼金鑰打勾的話,Id 資料會變成 Base64這邊要注意。

大概就是這樣,這個我測試一段時間了,筆記一下,給之後要踩雷的人..


reference:

https://stackoverflow.com/questions/28327003/how-to-remove-all-documents-in-index

https://stackoverflow.com/questions/54670922/azure-search-index-rebuild-strategy-using-c-sharp

https://docs.microsoft.com/zh-tw/azure/search/search-howto-reindex

https://docs.microsoft.com/zh-tw/azure/search/search-howto-create-indexers?tabs=portal


當麻許的碎念筆記 2014 | Donma Hsu Design.