### Install Tunnel Client Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/tunnel/README.md Use 'go get' to download the tunnel client source code. ```bash go get github.com/aliyun/aliyun-tablestore-go-sdk/tunnel ``` -------------------------------- ### Install Dependencies with Go Get Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/tunnel/README.md Alternatively, use 'go get' to install all necessary dependencies for the tunnel client. ```bash go get -u go.uber.org/zap go get -u github.com/cenkalti/backoff go get -u github.com/golang/protobuf/proto go get -u github.com/satori/go-uuid go get -u github.com/stretchr/testify/assert go get -u github.com/smartystreets/goconvey/convey go get -u github.com/golang/mock/gomock go get -u gopkg.in/natefinch/lumberjack.v2 ``` -------------------------------- ### Install Aliyun Tablestore Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/timeline/README.md Use this command to install the Aliyun Tablestore Go SDK, which is a prerequisite for using the timeline package. ```bash go get github.com/aliyun/aliyun-tablestore-go-sdk ``` -------------------------------- ### Complete Stream Processing Example in Go Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md This example demonstrates a complete stream processing workflow using the Aliyun Table Store Go SDK. It includes listing streams for a table, describing a stream to get its shards, and then iterating through each shard to read and process stream records in batches. It also includes basic error handling and a time-based backoff mechanism between batch reads. ```go package main import ( "log" "time" "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore" ) func main() { client := tablestore.NewClient( "https://myinstance.cn-hangzhou.ots.aliyuncs.com", "myinstance", "access-key-id", "access-key-secret", ) // List streams for the table streams, err := client.ListStream(&tablestore.ListStreamRequest{ TableName: "users", }) if err != nil { log.Fatal(err) } if len(streams.Streams) == 0 { log.Fatal("No streams found") } streamId := streams.Streams[0].StreamId // Describe stream to get shards streamDesc, err := client.DescribeStream(&tablestore.DescribeStreamRequest{ TableName: "users", StreamId: streamId, }) if err != nil { log.Fatal(err) } // Process each shard for _, shard := range streamDesc.Shards { // Get iterator for shard iterResp, err := client.GetShardIterator(&tablestore.GetShardIteratorRequest{ TableName: "users", StreamId: streamId, ShardId: shard.ShardId, IteratorType: tablestore.TRIM_HORIZON, }) if err != nil { log.Fatal(err) } iterator := iterResp.ShardIterator // Read records in batches for iterator != "" { recordResp, err := client.GetStreamRecord(&tablestore.GetStreamRecordRequest{ TableName: "users", StreamId: streamId, ShardIterator: iterator, Limit: 100, }) if err != nil { log.Fatal(err) } // Process records for _, record := range recordResp.Records { log.Printf("Type: %v, PK: %v, Seq: %d\n", record.Type, record.PrimaryKey, record.SequenceNumber) } iterator = recordResp.NextShardIterator if iterator == "" { break } // Backoff before next batch time.Sleep(1 * time.Second) } } } ``` -------------------------------- ### Complete Local Transaction Example in Go Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Demonstrates how to perform a complete local transaction for transferring funds between two accounts. It includes starting the transaction, debiting the source account, crediting the destination account, and committing the transaction. If any step fails, the transaction is aborted. ```go package main import ( "log" "proto" "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore" ) func transferFunds(client *tablestore.TableStoreClient, fromAccount, toAccount string, amount int64) error { // Start transaction txnResp, err := client.StartLocalTransaction(&tablestore.StartLocalTransactionRequest{ TableName: "accounts", PartitionKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ {ColumnName: "account_id", Value: fromAccount}, }, }, }) if err != nil { return err } txnId := txnResp.TransactionId // Debit from source account debitReq := &tablestore.UpdateRowRequest{ TableName: "accounts", TransactionId: &txnId, PrimaryKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ {ColumnName: "account_id", Value: fromAccount}, }, }, ColumnsToUpdate: []*tablestore.ColumnToUpdate{ { ColumnName: "balance", Value: -amount, // Decrement Type: tablestore.AttributeType_INTEGER, HasType: true, HasTimestamp: true, Timestamp: int64(time.Now().Unix() * 1000), }, }, } if _, err := client.UpdateRow(debitReq); err != nil { client.AbortTransaction(&tablestore.AbortTransactionRequest{TransactionId: txnId}) return err } // Credit to destination account creditReq := &tablestore.UpdateRowRequest{ TableName: "accounts", TransactionId: &txnId, PrimaryKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ {ColumnName: "account_id", Value: toAccount}, }, }, ColumnsToUpdate: []*tablestore.ColumnToUpdate{ { ColumnName: "balance", Value: amount, // Increment Type: tablestore.AttributeType_INTEGER, HasType: true, HasTimestamp: true, Timestamp: int64(time.Now().Unix() * 1000), }, }, } if _, err := client.UpdateRow(creditReq); err != nil { client.AbortTransaction(&tablestore.AbortTransactionRequest{TransactionId: txnId}) return err } // Commit transaction if _, err := client.CommitTransaction(&tablestore.CommitTransactionRequest{ TransactionId: txnId, }); err != nil { return err } log.Printf("Transfer successful: %d from %s to %s", amount, fromAccount, toAccount) return nil } ``` -------------------------------- ### Configuration Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to configure the Table Store client for different scenarios, including setting timeouts and other HTTP-related parameters. ```go config := &TableStoreConfig{ Instance: "your_instance_id", AccessKeyID: "your_access_key_id", AccessKeySecret: "your_access_key_secret", HTTPEndpoint: "your_endpoint", HTTPTimeout: &HTTPTimeout{ ConnectionTimeout: 10000, // 10 seconds ResponseTimeout: 10000, // 10 seconds }, } client, err := NewClientWithConfig(config) if err != nil { // handle error } ``` -------------------------------- ### Install Dependencies with Dep Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/tunnel/README.md Install dependencies using 'dep ensure -v' after downloading the tunnel client source code. ```bash dep ensure -v ``` -------------------------------- ### Client Constructors Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates various ways to create a client instance for Aliyun Table Store. Use NewClient for basic setup, NewClientWithConfig for detailed configuration, and NewClientWithCredentialsProvider for custom credential management. Similar options are available for timeseries clients. ```go client := NewClient("your_endpoint", "your_instance_id", "your_access_key_id", "your_access_key_secret") config := &TableStoreConfig{ Instance: "your_instance_id", AccessKeyID: "your_access_key_id", AccessKeySecret: "your_access_key_secret", HTTPEndpoint: "your_endpoint", // ... other configurations } client, err := NewClientWithConfig(config) // For timeseries client timeseriesClient, err := NewTimeseriesClientWithConfig(config) ``` -------------------------------- ### TermQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use TermQuery for exact matches on keyword fields. It is case-sensitive and does not perform analysis. ```go search.TermQuery{ FieldName: "status", Term: "available", } ``` -------------------------------- ### BoolQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Combine multiple queries using BoolQuery with 'Must', 'Should', 'MustNot', and 'Filter' clauses for complex search logic. ```go search.BoolQuery{ MustQueries: []*search.Query{ &search.MatchQuery{FieldName: "category", Text: "electronics"}, }, MustNotQueries: []*search.Query{ &search.TermQuery{FieldName: "status", Term: "discontinued"}, }, } ``` -------------------------------- ### Unbind Global Table Go Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Removes one or more regions from a global table replication setup. Use `IsForce` only for testing purposes. ```go request := &tablestore.UnbindGlobalTableRequest{ GlobalTableId: "gt-123456", GlobalTableName: "users", Removals: []*tablestore.Removal{ { RegionId: "cn-shenzhen", InstanceName: "instance3", }, }, } response, err := client.UnbindGlobalTable(request) if err != nil { log.Fatalf("Failed to unbind global table: %v", err) } ``` -------------------------------- ### PrefixQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use PrefixQuery to find documents where a field's value begins with a specified prefix. ```go search.PrefixQuery{ FieldName: "name", Prefix: "Apple", } ``` -------------------------------- ### CountAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use CountAggregation to count the total number of documents that match the query. ```go search.Aggregation{ Name: "total_count", AggType: search.AggType_COUNT, AggBody: &search.CountAggregation{ FieldName: "*", }, } ``` -------------------------------- ### Start Local Transaction Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Begins a local transaction for atomic multi-row operations. Requires a table name and partition key. ```go request := &tablestore.StartLocalTransactionRequest{ TableName: "accounts", PartitionKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ { ColumnName: "account_id", Value: "user123", }, }, }, } response, err := client.StartLocalTransaction(request) if err != nil { log.Fatalf("Failed to start transaction: %v", err) } transactionId := response.TransactionId ``` -------------------------------- ### Bind Global Table Go Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Binds an existing local table to a global table. Ensure the global table and regions are pre-configured. ```go request := &tablestore.BindGlobalTableRequest{ GlobalTableId: "gt-123456", GlobalTableName: "users", Placements: []*tablestore.Placement{ { RegionId: "ap-singapore", InstanceName: "instance-sg", Writable: true, }, }, } response, err := client.BindGlobalTable(request) if err != nil { log.Fatalf("Failed to bind global table: %v", err) } ``` -------------------------------- ### Delete Search Index Example Go Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Example of how to delete a search index using the Table Store client. Ensure you handle potential errors. ```go request := &tablestore.DeleteSearchIndexRequest{ TableName: "products", IndexName: "product_search", } response, err := client.DeleteSearchIndex(request) if err != nil { log.Fatalf("Failed to delete search index: %v", err) } ``` -------------------------------- ### Table Operations: CreateTable Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of creating a new table in Aliyun Table Store. Requires defining the table's metadata, including its name and primary key schema. ```go tableName := "my_table" primaryKey := []*ColumnSchema{ { Name: "id", Type: PrimaryKeyType_STRING, Option: PrimaryKeyOption_NOT_NULL, }, } err := client.CreateTable(&CreateTableRequest{ TableName: tableName, PrimaryKey: primaryKey, // ... other table options like TableMeta, TimeToLive, etc. }) if err != nil { // handle error } ``` -------------------------------- ### WildcardQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use WildcardQuery for pattern matching within field values using '*' (zero or more characters) and '?' (a single character). ```go search.WildcardQuery{ FieldName: "sku", Value: "PROD-*", } ``` -------------------------------- ### Process Streams with Aliyun Table Store Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Provides a comprehensive example of stream processing, including listing streams, describing stream shards, obtaining a shard iterator, and reading records from a stream. It demonstrates how to iterate through shards and process individual records. ```go // List streams streams, err := client.ListStream(&tablestore.ListStreamRequest{TableName: "users"}) if len(streams.Streams) > 0 { streamId := streams.Streams[0].StreamId // Describe stream shards streamDesc, _ := client.DescribeStream(&tablestore.DescribeStreamRequest{ TableName: "users", StreamId: streamId, }) // Process each shard for _, shard := range streamDesc.Shards { // Get iterator iterResp, _ := client.GetShardIterator(&tablestore.GetShardIteratorRequest{ TableName: "users", StreamId: streamId, ShardId: shard.ShardId, IteratorType: tablestore.TRIM_HORIZON, }) // Read records recordResp, _ := client.GetStreamRecord(&tablestore.GetStreamRecordRequest{ TableName: "users", StreamId: streamId, ShardIterator: iterResp.ShardIterator, Limit: 100, }) for _, record := range recordResp.Records { fmt.Printf("Operation: %v, Seq: %d\n", record.Type, record.SequenceNumber) } } } ``` -------------------------------- ### MaxAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use MaxAggregation to find the maximum value of a numeric field across matching documents. ```go search.Aggregation{ Name: "max_price", AggType: search.AggType_MAX, AggBody: &search.MaxAggregation{ FieldName: "price", }, } ``` -------------------------------- ### MinAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use MinAggregation to find the minimum value of a numeric field across matching documents. ```go search.Aggregation{ Name: "min_price", AggType: search.AggType_MIN, AggBody: &search.MinAggregation{ FieldName: "price", }, } ``` -------------------------------- ### SumAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use SumAggregation to calculate the sum of values for a numeric field across matching documents. ```go search.Aggregation{ Name: "total_sales", AggType: search.AggType_SUM, AggBody: &search.SumAggregation{ FieldName: "amount", }, } ``` -------------------------------- ### AvgAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use AvgAggregation to calculate the average value of a numeric field across matching documents. ```go search.Aggregation{ Name: "avg_price", AggType: search.AggType_AVG, AggBody: &search.AvgAggregation{ FieldName: "price", }, } ``` -------------------------------- ### SQL Operations: SQLQuery Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of executing a SQL query against Table Store. This allows you to use familiar SQL syntax for data retrieval and manipulation. ```go sql := "SELECT * FROM my_table WHERE "col1" = 'some_value'" resp, err := client.SQLQuery(&SQLQueryRequest{ TableName: "my_table", SQL: sql, }) if err != nil { // handle error } // Process results from resp.Rows ``` -------------------------------- ### NewDefaultTableStoreConfig Function Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/configuration.md Creates a new `TableStoreConfig` with default values for common settings. Use this as a starting point for custom configurations. ```go func NewDefaultTableStoreConfig() *TableStoreConfig { return &TableStoreConfig{ RetryTimes: 10, HTTPTimeout: HTTPTimeout{ ConnectionTimeout: 15 * time.Second, RequestTimeout: 30 * time.Second, }, MaxRetryTime: 5 * time.Second, MaxIdleConnections: 2000, IdleConnTimeout: 25 * time.Second, DefaultRetryInterval: 50 * time.Millisecond, MaxRetryInterval: 1000 * time.Millisecond, } } ``` -------------------------------- ### Error Handling Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to handle potential errors returned by the Table Store SDK. It's crucial to check for specific error codes and implement appropriate retry or fallback logic. ```go err := client.PutRow(request) if err != nil { switch err.(type) { case *OTSServerBusy: // Implement retry logic with exponential backoff fmt.Println("Server is busy, retrying...") case *OTSNotEnoughCapacityUnit: fmt.Println("Not enough capacity, consider scaling up.") case *OTSAccessDenied: fmt.Println("Authentication failed.") default: fmt.Printf("An unexpected error occurred: %v\n", err) } return } ``` -------------------------------- ### MatchQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use MatchQuery to find documents where a field contains specific text. Suitable for full-text search on text fields. ```go search.MatchQuery{ FieldName: "description", Text: "high performance", } ``` -------------------------------- ### Perform Range Queries with Aliyun Table Store Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Illustrates how to query a range of rows within a table using `GetRangeRequest`. This example specifies inclusive and exclusive primary key bounds and retrieves up to 100 rows. ```go request := &tablestore.GetRangeRequest{ TableName: "users", Direction: tablestore.FORWARD, InclusiveStartPrimaryKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ {ColumnName: "id", Value: "", PrimaryKeyOption: tablestore.MIN}, }, }, ExclusiveEndPrimaryKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ {ColumnName: "id", Value: "", PrimaryKeyOption: tablestore.MAX}, }, }, MaxVersions: 1, Limit: 100, } response, err := client.GetRange(request) for _, row := range response.Rows { fmt.Printf("Row: %v\n", row.PrimaryKey) } ``` -------------------------------- ### Execute SQL SELECT Query Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Use SQLQuery to execute a SELECT statement against Table Store data. This example demonstrates querying users with age greater than 30 and limiting results. ```go request := &tablestore.SQLQueryRequest{ Query: "SELECT id, name, age FROM users WHERE age > 30 LIMIT 10", } response, err := client.SQLQuery(request) if err != nil { log.Fatalf("SQL query failed: %v", err) } for _, row := range response.Rows { for _, col := range row.Columns { fmt.Printf("%s: %v\n", col.ColumnName, col.Value) } } ``` -------------------------------- ### RangeQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use RangeQuery to filter documents based on a numeric or date range. Specify 'From', 'To', and whether to include the boundaries. ```go search.RangeQuery{ FieldName: "price", From: proto.Float64(100.0), To: proto.Float64(1000.0), IncludeLower: proto.Bool(true), IncludeUpper: proto.Bool(true), } ``` -------------------------------- ### Perform Batch Get Rows with Aliyun Table Store Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Shows how to retrieve multiple rows in a single request using `BatchGetRowRequest`. It iterates through the response to check the success of each row retrieval and prints any errors. ```go request := &tablestore.BatchGetRowRequest{ Tables: []*tablestore.BatchGetRowRequestForTable{ { TableName: "users", PrimaryKeys: []*tablestore.PrimaryKey{ {PrimaryKeys: []*tablestore.PrimaryKeyColumn{{ColumnName: "id", Value: "user1"}}}, {PrimaryKeys: []*tablestore.PrimaryKeyColumn{{ColumnName: "id", Value: "user2"}}}, {PrimaryKeys: []*tablestore.PrimaryKeyColumn{{ColumnName: "id", Value: "user3"}}}, }, }, }, } response, err := client.BatchGetRow(request) for _, tableResult := range response.Tables { for i, rowResult := range tableResult.Rows { if rowResult.IsOk { fmt.Printf("Row %d retrieved successfully\n", i) } else { fmt.Printf("Row %d failed: %v\n", i, rowResult.Error) } } } ``` -------------------------------- ### Batch Operations: BatchGetRow Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example for retrieving multiple rows in a single request. This is more efficient than multiple individual GetRow calls. Specify the table name and a list of primary keys for the rows to retrieve. ```go tableName := "my_table" resp, err := client.BatchGetRow(&BatchGetRowRequest{ TableNames: []string{tableName}, PrimaryKeys: [][]*PrimaryKeyValue{ { { Value: "row1" }, }, { { Value: "row2" }, }, }, }) if err != nil { // handle error } // Process rows from resp.Responses ``` -------------------------------- ### Query Row with Error Handling Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/START_HERE.txt Execute a GetRow request and handle potential errors. This example demonstrates how to differentiate between Tablestore-specific errors (OtsError) and general network errors. ```go response, err := client.GetRow(request) if err != nil { if otsErr, ok := err.(*tablestore.OtsError); ok { // Handle TableStore errors } else { // Handle network errors } } ``` -------------------------------- ### Execute SQL INSERT Operation Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Use SQLQuery to execute an INSERT statement for adding new rows to a table. This example inserts a new user record. ```go request := &tablestore.SQLQueryRequest{ Query: `INSERT INTO users (id, name, age) VALUES ('user123', 'John Doe', 30)`, } response, err := client.SQLQuery(request) if err != nil { log.Fatalf("SQL insert failed: %v", err) } ``` -------------------------------- ### Update Global Table Go Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Updates configuration of a physical table within a global table, such as write eligibility or primary role. Specify the `RegionId` and `InstanceName` for the target physical table. ```go request := &tablestore.UpdateGlobalTableRequest{ GlobalTableId: "gt-123456", GlobalTableName: "users", PhyTable: tablestore.UpdatePhyTable{ RegionId: "cn-beijing", InstanceName: "instance2", TableName: "users", Writable: proto.Bool(true), PrimaryEligible: proto.Bool(true), }, } response, err := client.UpdateGlobalTable(request) if err != nil { log.Fatalf("Failed to update global table: %v", err) } ``` -------------------------------- ### Handle Errors with Aliyun Table Store Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Demonstrates how to check for errors after an operation and specifically handle `OtsError` by inspecting its code and message. It includes examples for handling specific error codes like 'OTSObjectNotExist' and 'OTSQuotaExhausted'. ```go response, err := client.GetRow(request) if err != nil { if otsErr, ok := err.(*tablestore.OtsError); ok { fmt.Printf("Error: %s - %s\n", otsErr.Code, otsErr.Message) // Handle specific error codes switch otsErr.Code { case "OTSObjectNotExist": // Handle table not found case "OTSQuotaExhausted": // Handle capacity exceeded default: // Handle other errors } } else { // Handle network or other errors fmt.Printf("Network error: %v\n", err) } } ``` -------------------------------- ### Initialize Table Store Client Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Create a new client instance to connect to Aliyun Table Store. Ensure you replace placeholder values with your actual endpoint, instance name, and credentials. ```go client := tablestore.NewClient( "https://myinstance.cn-hangzhou.ots.aliyuncs.com", "myinstance", "your-access-key-id", "your-access-key-secret", ) ``` -------------------------------- ### Get Row Data Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Retrieve a specific row from a table using its primary key. The example demonstrates how to access and print the column values from the retrieved row. ```go request := &tablestore.GetRowRequest{ TableName: "users", PrimaryKey: &tablestore.PrimaryKey{ PrimaryKeys: []*tablestore.PrimaryKeyColumn{ { ColumnName: "id", Value: "user123", }, }, }, } response, err := client.GetRow(request) if err == nil && response.Row != nil { for _, column := range response.Row.Columns { fmt.Printf("%s: %v\n", column.ColumnName, column.Value) } } ``` -------------------------------- ### Get Stream Record Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Retrieves stream records from a shard using an iterator. This is useful for processing changes to rows in a table. Ensure you have a valid ShardIterator obtained from GetShardIterator. ```go request := &tablestore.GetStreamRecordRequest{ TableName: "users", StreamId: "20230101000000000000000001", ShardIterator: iterator, Limit: 100, } response, err := client.GetStreamRecord(request) if err != nil { log.Fatalf("Failed to get stream records: %v", err) } for _, record := range response.Records { fmt.Printf("Operation: %s, Seq: %d\n", record.Type, record.SequenceNumber) for _, col := range record.Columns { fmt.Printf(" %s: %v\n", col.ColumnName, col.Value) } } // Use NextShardIterator for pagination if response.NextShardIterator != "" { // Fetch next batch } ``` -------------------------------- ### Basic Tablestore Client Configuration Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/configuration.md Use this for standard configurations. It initializes the client with default settings. ```go config := tablestore.NewDefaultTableStoreConfig() client := tablestore.NewClientWithConfig( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "access-key-id", "access-key-secret", "", config, ) ``` -------------------------------- ### Get Shard Iterator Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Obtain a token to read records from a specific shard within a stream. You can specify the starting position using sequence number, timestamp, or by using predefined types like TRIM_HORIZON or LATEST. ```go request := &tablestore.GetShardIteratorRequest{ TableName: "users", StreamId: "20230101000000000000000001", ShardId: "shard-0", IteratorType: tablestore.TRIM_HORIZON, } response, err := client.GetShardIterator(request) if err != nil { log.Fatalf("Failed to get shard iterator: %v", err) } fmt.Printf("Iterator: %s\n", response.ShardIterator) ``` -------------------------------- ### Run IM Application Demo Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/timeline/README.md Navigate to the IM sample directory and run the main and im.go files to execute the IM application demo. ```bash cd timeline/sample/im go run main.go im.go ``` -------------------------------- ### Create Timeseries Client with Configuration Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Create a timeseries client with custom configurations, including default TableStore configurations and specific timeseries settings. ```go config := tablestore.NewDefaultTableStoreConfig() timeseriesConfig := tablestore.NewTimeseriesConfiguration() client := tablestore.NewTimeseriesClientWithConfig( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "access-key-id", "access-key-secret", "", config, timeseriesConfig, ) ``` -------------------------------- ### Initialize Tablestore Client Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/START_HERE.txt Instantiate a new Tablestore client with the provided endpoint, instance name, and access credentials. Ensure your credentials and endpoint are correct for your region. ```go client := tablestore.NewClient( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "access-key-id", "access-key-secret", ) ``` -------------------------------- ### Run Feed Stream Application Demo Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/timeline/README.md Navigate to the feed sample directory and run the main and feed.go files to execute the feed stream application demo. ```bash cd timeline/sample/feed go run main.go feed.go ``` -------------------------------- ### Initialize Client with Static Credentials Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/configuration.md Initialize the Tablestore client using static access key ID and secret. ```go client := tablestore.NewClient( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", ) ``` -------------------------------- ### Import Aliyun Table Store Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Import the necessary package to use the Aliyun Table Store Go SDK. ```go import "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore" ``` -------------------------------- ### GeoDistanceQuery Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use GeoDistanceQuery to find documents within a specified radius from a central geographic point. ```go search.GeoDistanceQuery{ FieldName: "location", CenterPoint: "10.5,20.5", Distance: "100km", } ``` -------------------------------- ### Initialize Tunnel Client Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/tunnel/README.md Create a new TunnelClient instance using your endpoint, instance name, and access key credentials. ```go tunnelClient := tunnel.NewTunnelClient(endpoint, instance, accessKeyId, accessKeySecret) ``` -------------------------------- ### DistinctCountAggregation Example Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/search-api.md Use DistinctCountAggregation to count the number of unique values for a specific field across matching documents. ```go search.Aggregation{ Name: "unique_categories", AggType: search.AggType_DISTINCT_COUNT, AggBody: &search.DistinctCountAggregation{ FieldName: "category", }, } ``` -------------------------------- ### Create a Table Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Define and create a new table in Aliyun Table Store. This includes specifying the table schema, options like TimeToAlive and MaxVersion, and reserved throughput for read and write capacity. ```go request := &tablestore.CreateTableRequest{ TableMeta: &tablestore.TableMeta{ TableName: "users", SchemaEntry: []*tablestore.PrimaryKeySchema{ { Name: proto.String("id"), Type: tablestore.PrimaryKeyType_STRING.Enum(), }, }, }, TableOption: &tablestore.TableOption{ TimeToAlive: -1, MaxVersion: 1, }, ReservedThroughput: &tablestore.ReservedThroughput{ Readcap: 100, Writecap: 100, }, } response, err := client.CreateTable(request) ``` -------------------------------- ### Initialize Client with Custom Credentials Provider Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/configuration.md Initialize the Tablestore client using a custom credentials provider for dynamic credential refresh. ```go type DynamicCredentialsProvider struct { // Your implementation } func (d *DynamicCredentialsProvider) GetCredentials() common.Credentials { // Return current credentials, potentially refreshing them return &common.DefaultCredentials{ AccessKeyID: d.getAccessKeyID(), AccessKeySecret: d.getAccessKeySecret(), SecurityToken: d.getSecurityToken(), } } provider := &DynamicCredentialsProvider{} client := tablestore.NewClientWithCredentialsProvider( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", provider, nil, ) ``` -------------------------------- ### TimeRange Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/types.md Defines a time range for filtering column versions, specifying start and end timestamps in milliseconds, or a specific timestamp. ```APIDOC ## TimeRange ### Description Time range filter for column versioning queries. ### Fields - **Start** (int64) - Start timestamp in milliseconds (inclusive) - **End** (int64) - End timestamp in milliseconds (exclusive) - **Specific** (int64) - Specific timestamp to query (if set, overrides Start/End) ``` -------------------------------- ### Create TableStoreClient with Advanced Configuration Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md Creates a TableStoreClient with advanced configuration options, including security token support and custom HTTP settings. Useful for fine-tuning connection, retry, and timeout behavior. ```go config := &tablestore.TableStoreConfig{ RetryTimes: 10, MaxRetryTime: 5 * time.Second, MaxIdleConnections: 2000, HTTPTimeout: tablestore.HTTPTimeout{ ConnectionTimeout: 15 * time.Second, RequestTimeout: 30 * time.Second, }, } client := tablestore.NewClientWithConfig( "https://myinstance.cn-hangzhou.ots.aliyuncs.com", "myinstance", "access-key-id", "access-key-secret", "security-token", config, ) ``` -------------------------------- ### Client Constructors Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/INDEX.md Initialize and configure your TableStore client instances with various options. ```APIDOC ## Client Constructors ### Description Provides functions for creating and configuring TableStore client instances. ### Functions - NewClient - NewClientWithConfig - NewClientWithCredentialsProvider - NewTimeseriesClient - NewTimeseriesClientWithConfig - NewTimeseriesClientWithCredentialsProvider ``` -------------------------------- ### GetShardIterator Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/global-table-and-streams.md Obtains an iterator for reading records from a specific shard. You can specify the starting point using sequence number or timestamp. ```APIDOC ## GetShardIterator ### Description Obtains an iterator for reading records from a specific shard. Iterator position is controlled by sequence number or timestamp. ### Method POST ### Endpoint /GetShardIterator ### Parameters #### Request Body - **TableName** (string) - Required - Name of the table - **StreamId** (string) - Required - ID of the stream - **ShardId** (string) - Required - ID of the shard to iterate - **IteratorType** (ShardIteratorType) - Required - Start position (TRIM_HORIZON, LATEST, AT_SEQUENCE_NUMBER, AT_TIMESTAMP) - **SequenceNumber** (int64) - Conditional - Sequence number (required for AT_SEQUENCE_NUMBER) - **Timestamp** (int64) - Conditional - Timestamp in milliseconds (required for AT_TIMESTAMP) **ShardIteratorType Enum**: - `TRIM_HORIZON` - Start from earliest available record - `LATEST` - Start from newest record - `AT_SEQUENCE_NUMBER` - Start at specific sequence number - `AT_TIMESTAMP` - Start at records from specific timestamp onwards ### Request Example ```json { "TableName": "users", "StreamId": "20230101000000000000000001", "ShardId": "shard-0", "IteratorType": "TRIM_HORIZON" } ``` ### Response #### Success Response (200) - **ShardIterator** (string) - Token for retrieving records from this position - **RequestId** (string) - Request identifier #### Response Example ```json { "ShardIterator": "some-iterator-token", "RequestId": "some-request-id" } ``` ``` -------------------------------- ### Create Timeseries Client Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Instantiate a dedicated client for timeseries operations using endpoint, instance name, and credentials. ```go client := tablestore.NewTimeseriesClient( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "access-key-id", "access-key-secret", ) ``` -------------------------------- ### Transaction Operations: AbortTransaction Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Aborts a previously started local transaction. All operations performed under the given transaction ID will be discarded. ```go err := client.AbortTransaction(&AbortTransactionRequest{ TableName: "my_table", TransactionID: "your_transaction_id", }) if err != nil { // handle error } ``` -------------------------------- ### Initialize Client with STS Credentials Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/configuration.md Initialize the Tablestore client using static credentials along with a security token (STS). ```go client := tablestore.NewClientWithConfig( "https://instance.cn-hangzhou.ots.aliyuncs.com", "instance", "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "FwoGZXIvYXdzEFb...", // STS token nil, ) ``` -------------------------------- ### Transaction Operations: CommitTransaction Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Commits a previously started local transaction. All operations performed under the given transaction ID will be finalized. ```go err := client.CommitTransaction(&CommitTransactionRequest{ TableName: "my_table", TransactionID: "your_transaction_id", }) if err != nil { // handle error } ``` -------------------------------- ### Row Operations Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/INDEX.md Perform CRUD operations on individual rows within your tables, including putting, getting, updating, and deleting rows. ```APIDOC ## Row Operations ### Description Enables direct manipulation of rows within a table. ### Methods - PutRow - GetRow - UpdateRow - DeleteRow ``` -------------------------------- ### Create Table with TableStore Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md Use this snippet to create a new table in TableStore. Specify the table name, primary key schema, and optional configurations like Time-To-Live (TTL), maximum versions, and reserved throughput. Ensure the client is initialized before calling this function. ```go request := &tablestore.CreateTableRequest{ TableMeta: &tablestore.TableMeta{ TableName: "users", SchemaEntry: []*tablestore.PrimaryKeySchema{ { Name: proto.String("id"), Type: tablestore.PrimaryKeyType_STRING.Enum(), }, }, }, TableOption: &tablestore.TableOption{ TimeToAlive: -1, MaxVersion: 1, }, ReservedThroughput: &tablestore.ReservedThroughput{ Readcap: 100, Writecap: 100, }, } response, err := client.CreateTable(request) if err != nil { log.Fatalf("Failed to create table: %v", err) } ``` -------------------------------- ### NewClientWithConfig Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md Creates a TableStoreClient with advanced configuration options, including security token support and custom HTTP settings. It accepts endpoint, instance name, access key ID, access key secret, security token, a TableStoreConfig, and optional client options. ```APIDOC ## NewClientWithConfig ### Description Creates a TableStoreClient with advanced configuration options, including security token support and custom HTTP settings. It accepts endpoint, instance name, access key ID, access key secret, security token, a TableStoreConfig, and optional client options. ### Function Signature ```go func NewClientWithConfig( endPoint string, instanceName string, accessKeyId string, accessKeySecret string, securityToken string, config *TableStoreConfig, options ...ClientOption ) *TableStoreClient ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **endPoint** (string) - Required - The address of the TableStore service endpoint - **instanceName** (string) - Required - The instance name for the TableStore service - **accessKeyId** (string) - Required - The Access Key ID for authentication - **accessKeySecret** (string) - Required - The Access Key Secret for signing requests - **securityToken** (string) - Optional - Security token for temporary credentials (STS) - **config** (*TableStoreConfig) - Optional - Custom HTTP timeout, retry, and connection settings - **options** (...ClientOption) - Optional - Optional client configuration options ### Returns - ** *TableStoreClient** - A configured client instance ### Example ```go config := &tablestore.TableStoreConfig{ RetryTimes: 10, MaxRetryTime: 5 * time.Second, MaxIdleConnections: 2000, HTTPTimeout: tablestore.HTTPTimeout{ ConnectionTimeout: 15 * time.Second, RequestTimeout: 30 * time.Second, }, } client := tablestore.NewClientWithConfig( "https://myinstance.cn-hangzhou.ots.aliyuncs.com", "myinstance", "access-key-id", "access-key-secret", "security-token", config, ) ``` ``` -------------------------------- ### NewClient Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md Creates a basic TableStoreClient with minimal configuration. It takes endpoint, instance name, access key ID, access key secret, and optional client options as parameters. ```APIDOC ## NewClient ### Description Creates a basic TableStoreClient with minimal configuration. It takes endpoint, instance name, access key ID, access key secret, and optional client options as parameters. ### Function Signature ```go func NewClient( endPoint string, instanceName string, accessKeyId string, accessKeySecret string, options ...ClientOption ) *TableStoreClient ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **endPoint** (string) - Required - The address of the TableStore service endpoint (e.g., "https://instance.cn-hangzhou.ots.aliyuncs.com") - **instanceName** (string) - Required - The instance name for the TableStore service - **accessKeyId** (string) - Required - The Access Key ID for authentication - **accessKeySecret** (string) - Required - The Access Key Secret for signing requests - **options** (...ClientOption) - Optional - Optional client configuration options ### Returns - ** *TableStoreClient** - A configured client instance ### Example ```go client := tablestore.NewClient( "https://myinstance.cn-hangzhou.ots.aliyuncs.com", "myinstance", "your-access-key-id", "your-access-key-secret", ) ``` ``` -------------------------------- ### Execute SQL DELETE Operation Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Use SQLQuery to execute a DELETE statement for removing rows. This example deletes a user by ID. ```go request := &tablestore.SQLQueryRequest{ Query: `DELETE FROM users WHERE id = 'user123'`, } response, err := client.SQLQuery(request) if err != nil { log.Fatalf("SQL delete failed: %v", err) } ``` -------------------------------- ### Handling Go Network Errors with TableStore SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/errors.md Demonstrates how to check for temporary network errors, connection closures, refused connections, and I/O timeouts when using the TableStore Go SDK. ```go response, err := client.GetRow(request) if err != nil { if netErr, ok := err.(net.Error); ok && netErr.Temporary() { // Temporary network error, can retry } else if err == io.EOF || err == io.ErrUnexpectedEOF { // Connection closed by server } else if strings.Contains(err.Error(), "connection refused") { // Connection actively refused by server } else if strings.Contains(err.Error(), "i/o timeout") { // I/O operation timed out } } ``` -------------------------------- ### Commit Transaction Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Commits all operations within a transaction, applying changes atomically. Requires the transaction ID obtained from starting the transaction. ```go request := &tablestore.CommitTransactionRequest{ TransactionId: transactionId, } response, err := client.CommitTransaction(request) if err != nil { log.Fatalf("Failed to commit transaction: %v", err) } ``` -------------------------------- ### List Tables with TableStore Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md This snippet demonstrates how to retrieve a list of all table names within your TableStore instance. It requires an initialized client and handles potential errors during the API call. The response contains a slice of table names. ```go response, err := client.ListTable() if err != nil { log.Fatalf("Failed to list tables: %v", err) } for _, tableName := range response.TableNames { fmt.Println("Table:", tableName) } ``` -------------------------------- ### Execute SQL UPDATE Operation Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/special-operations.md Use SQLQuery to execute an UPDATE statement for modifying existing rows. This example updates a user's age. ```go request := &tablestore.SQLQueryRequest{ Query: `UPDATE users SET age = 31 WHERE id = 'user123'`, } response, err := client.SQLQuery(request) if err != nil { log.Fatalf("SQL update failed: %v", err) } ``` -------------------------------- ### Create and Use Search Index Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/errors.md Resolve 'Search index not found' errors by first creating the search index using `CreateSearchIndex` and then performing searches with `SearchRequest`. Ensure the index name matches between creation and search operations. ```go // Create search index first createReq := &tablestore.CreateSearchIndexRequest{ TableName: "my_table", IndexName: "my_index", IndexSchema: &tablestore.IndexSchema{ FieldSchemas: []*tablestore.FieldSchema{ { FieldName: proto.String("text_field"), FieldType: tablestore.FieldType_TEXT.Enum(), }, }, }, } if _, err := client.CreateSearchIndex(createReq); err != nil { log.Fatal(err) } // Now search will work searchReq := &tablestore.SearchRequest{ TableName: "my_table", IndexName: "my_index", // Must match SearchQuery: &search.SearchQuery{ Query: &search.MatchQuery{ FieldName: "text_field", Text: "search term", }, }, } ``` -------------------------------- ### Describe Table with TableStore Go SDK Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/api-reference/tablestorec-client.md Use this code to fetch detailed metadata for a specific table, including its schema, options, and throughput settings. Provide the table name in the request. The response object contains comprehensive information about the table's configuration. ```go request := &tablestore.DescribeTableRequest{ TableName: "users", } response, err := client.DescribeTable(request) if err != nil { log.Fatalf("Failed to describe table: %v", err) } fmt.Printf("Table: %s\n", response.TableMeta.TableName) fmt.Printf("Max Versions: %d\n", response.TableOption.MaxVersion) ``` -------------------------------- ### Search with Full-Text Index Source: https://github.com/aliyun/aliyun-tablestore-go-sdk/blob/master/_autodocs/README.md Perform a full-text search on a specified index within a table. This example searches for documents where the 'title' field contains the term 'laptop'. ```go request := &tablestore.SearchRequest{ TableName: "products", IndexName: "product_search", SearchQuery: &search.SearchQuery{ Offset: proto.Int32(0), Limit: proto.Int32(10), Query: &search.MatchQuery{ FieldName: "title", Text: "laptop", }, }, } response, err := client.Search(request) ```