本文介紹如何通過 Go SDK 批量讀取Table Store中的資料,支援查詢多個表的資料。
注意事項
單次批量讀取操作最多支援讀取 100 行資料。
前提條件
方法說明
func (tableStoreClient *TableStoreClient) BatchGetRow(request *BatchGetRowRequest) (*BatchGetRowResponse, error)範例程式碼
以下範例程式碼用於讀取 test_table 表中主索引值為 row1 和 row2 的兩行資料。
func BatchGetRowSample(client *tablestore.TableStoreClient) {
// 構造查詢條件
multiRowQueryCriteria := new(tablestore.MultiRowQueryCriteria)
// 設定表名稱
multiRowQueryCriteria.TableName = "test_table"
// 添加第 1 行主鍵資訊
getPk1 := new(tablestore.PrimaryKey)
getPk1.AddPrimaryKeyColumn("id", "row1")
multiRowQueryCriteria.AddRow(getPk1)
// 添加第 2 行主鍵資訊
getPk2 := new(tablestore.PrimaryKey)
getPk2.AddPrimaryKeyColumn("id", "row2")
multiRowQueryCriteria.AddRow(getPk2)
// 設定查詢版本
multiRowQueryCriteria.MaxVersion = 1
// 調用 BatchGetRow 方法進行批量資料查詢
batchGetRowRequest := new(tablestore.BatchGetRowRequest)
batchGetRowRequest.MultiRowQueryCriteria = append(batchGetRowRequest.MultiRowQueryCriteria, multiRowQueryCriteria)
batchGetRowResponse, err := client.BatchGetRow(batchGetRowRequest)
// 返回結果處理
if err != nil {
fmt.Println("Batch get row failed with error: ", err)
} else {
fmt.Printf("* RequestId: %s \n", batchGetRowResponse.RequestId)
for tableName, rows := range batchGetRowResponse.TableToRowsResult {
fmt.Printf("* Table: %s \n", tableName)
for _, row := range rows {
if row.IsSucceed {
fmt.Printf("Succeeded Row: %v \n", row)
} else {
fmt.Printf("Failed Row: %d | %v \n", row.Index, row.Error)
}
}
}
}
}您可以在批量讀取資料時參考以下範例程式碼進行參數設定。
讀取多張表的資料。批量讀取支援一次讀取多張表的資料,您需要為每張表指定一個MultiRowQueryCriteria。
// 構造第 2 個表的查詢條件 multiRowQueryCriteria1 := new(tablestore.MultiRowQueryCriteria) multiRowQueryCriteria1.TableName = "orders_small" // 添加第 1 行主鍵資訊 getPk3 := new(tablestore.PrimaryKey) getPk3.AddPrimaryKeyColumn("order_id", "90fb478c-1360-11f0-a34d-00163e30a2a9") multiRowQueryCriteria1.AddRow(getPk3) // 設定查詢版本 multiRowQueryCriteria1.MaxVersion = 1 // Request 添加 MultiRowQueryCriteria batchGetRowRequest.MultiRowQueryCriteria = append(batchGetRowRequest.MultiRowQueryCriteria, multiRowQueryCriteria1)設定讀取的資料版本範圍,結果只返回版本範圍內的資料。
// 設定查詢的資料版本範圍為目前時間往前一天 timeRange := new(tablestore.TimeRange) timeRange.Start = int64(time.Now().Unix() * 1000 - 86400 * 1000) timeRange.End = int64(time.Now().Unix() * 1000) multiRowQueryCriteria.TimeRange = timeRange指定讀取的屬性列。
multiRowQueryCriteria.AddColumnToGet("col1")