[C#][.NET Core] Azure Storage Table 手把手從頭開始 - 透過 PartitionKey 取得所有資料
之前有篇文章 Azure Storage Table 手把手從頭開始 - 建立 Table,InsertOrReplace 資料,讀取資料 ,其中我寫入一千筆 User 資料,並且我將 PartitionKey 設定為 GROUP1~ GROUP10 ,基本上在 NoSQL 的資料規劃中, PartitionKey 做得好,會有效的增加搜尋效率,這篇範例就是去撈取之前新增的一千筆資料中 , PartitionKey 為 GROUP4 的資料。
var connectionString = "your_connection_string"; | |
var tableName = "USERSAMPLE"; | |
var CSAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString); | |
var CTClient = CSAccount.CreateCloudTableClient(); | |
var CTable = CTClient.GetTableReference(tableName); | |
var query = new Microsoft.WindowsAzure.Storage.Table.TableQuery<User>(); | |
query.FilterString = Microsoft.WindowsAzure.Storage.Table.TableQuery.GenerateFilterCondition("PartitionKey", Microsoft.WindowsAzure.Storage.Table.QueryComparisons.Equal, "GROUP4"); | |
var res = new System.Collections.Concurrent.ConcurrentBag<User>(); | |
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); | |
stopwatch.Start(); | |
Microsoft.WindowsAzure.Storage.Table.TableContinuationToken continuationToken = null; | |
do | |
{ | |
var page = CTable.ExecuteQuerySegmentedAsync(query, continuationToken).Result; | |
continuationToken = page.ContinuationToken; | |
if (page.Results != null) | |
{ | |
foreach (var obj in page.Results) | |
{ | |
res.Add(obj); | |
} | |
} | |
} | |
while (continuationToken != null); | |
stopwatch.Stop(); | |
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(res)); | |
Console.WriteLine("Count >>" + res.Count); | |
Console.WriteLine(stopwatch.Elapsed.ToString()); |
為何這要獨立寫一篇文章,其實重點是這個 pattern ,看過很多範例,其實很多撈取方法都是 透過一個 continuationToken 然後一直撈取到為 null 為止,每一次撈取都是 1000 筆資料,因為這模式在撈取其他資料都類似,所以獨立記錄成一篇,希望有幫助到你。
如果要查詢是否答案正確可以透過,管理工具中的 Query 來對結果是不是對的。
如果你覺得我寫得太簡單或是寫得不好,歡迎參考 :
https://docs.microsoft.com/zh-tw/dotnet/api/microsoft.windowsazure.storage.table?view=azure-dotnet
https://docs.microsoft.com/zh-tw/dotnet/api/microsoft.windowsazure.storage.table.tableentity?view=azure-dotnet
https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.table.tablequerysegment-1.continuationtoken?view=azure-dotnet