Introduction:
Modern applications require powerful, reliable, scalable and low-latency database solutions. There are many factors to consider in database selection, such as performance, value, scalability, and more. AWS DynamoDB is a fully managed, non-relational database designed to handle Internet-scale big data collections, providing low-latency and scalable storage and retrieval capabilities. In this article, we’ll take an in-depth look at AWS DynamoDB, focusing on how to use it in the Go language.
1. Introduction to DynamoDB
AWS DynamoDB is part of the AWS cloud service and is a fully managed, non-relational database that can seamlessly handle large-scale data collections. Its convenient API interface, low latency and high throughput capabilities that can be expanded on demand allow any application to use it. DynamoDB's biggest advantage over other database providers is the speed at which it stores and reads data. It uses SSD (Solid State Drive) as the default storage method, which makes it very fast to read and write.
DynamoDB has a simple interface and supports a large number of programming languages and platforms, such as Java, JavaScript, Python, Ruby, etc., including Go language. DynamoDB supports data storage and query operations using multiple data models based on documents, Key-Value, graphs, etc. DynamoDB's data storage is in the form of tables. Each table can contain multiple projects, and each project can contain multiple attributes.
The use of DynamoDB can be done with the help of the AWS Management Console or the AWS SDK. At the same time, running the AWS SDK requires placing your own AWS access credentials in the code or using unsafe environment variables. This way of writing has security risks and is not convenient for team development. Therefore, we can develop using the AWS SDK for Go, which provides a more elegant and secure solution.
2. Use AWS SDK for Go to connect to DynamoDB
1. Install AWS SDK for Go
Run the following command in the terminal to install Go’s AWS SDK:
$ go get -u github.com/aws/aws-sdk-go
2. Configure AWS SDK for Go
Before connecting to DynamoDB, you need to configure the AWS access key and region used by AWS SDK for Go. To do this, add the following code to your code:
sess := session.Must(session.NewSession(&aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials( "YOUR_ACCESS_KEY_ID", "YOUR_SECRET_ACCESS_KEY", ""), }))
Where Region and Credentials are required options. In the Region property, you can specify the AWS region. Credentials are an authentication mechanism used to connect to AWS services. If you don't have an AWS access certificate assigned, you can create a new one on the AWS Management page.
3. Create and delete tables
In DynamoDB, a table is a collection of items with the same attributes that can be used to store and retrieve data. In order to create a new table, attributes such as table name, primary key, and capacity units need to be determined. The following code demonstrates how to use the AWS SDK for Go to create a DynamoDB table:
svc := dynamodb.New(sess) input := &dynamodb.CreateTableInput{ AttributeDefinitions: []*dynamodb.AttributeDefinition{ { AttributeName: aws.String("ID"), AttributeType: aws.String("N"), }, { AttributeName: aws.String("Name"), AttributeType: aws.String("S"), }, }, KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("ID"), KeyType: aws.String("HASH"), }, { AttributeName: aws.String("Name"), KeyType: aws.String("RANGE"), }, }, ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(5), WriteCapacityUnits: aws.Int64(5), }, TableName: aws.String("TableName"), } result, err := svc.CreateTable(input) if err != nil { fmt.Println(err) return } fmt.Println(result)
After the creation is successful, you can view the newly created table in the DynamoDB console. If you want to delete the table, please use the following code:
svc := dynamodb.New(sess) input := &dynamodb.DeleteTableInput{ TableName: aws.String("TableName"), } result, err := svc.DeleteTable(input) if err != nil { fmt.Println(err) return } fmt.Println(result)
4. Add, read and delete data
1. Add data
The following code demonstrates how to use the AWS SDK for Go Add data to DynamoDB table:
svc := dynamodb.New(sess) input := &dynamodb.PutItemInput{ Item: map[string]*dynamodb.AttributeValue{ "ID": { N: aws.String("123"), }, "Name": { S: aws.String("John"), }, "Age": { N: aws.String("29"), }, }, TableName: aws.String("TableName"), } _, err := svc.PutItem(input) if err != nil { fmt.Println(err) return }
In the PutItemInput interface, the Item property is used to specify the item to be added to the table, and the TableName property is used to specify the table name.
2. Read data
The following code demonstrates how to use AWS SDK for Go to read data from a DynamoDB table:
svc := dynamodb.New(sess) input := &dynamodb.GetItemInput{ Key: map[string]*dynamodb.AttributeValue{ "ID": { N: aws.String("123"), }, "Name": { S: aws.String("John"), }, }, TableName: aws.String("TableName"), } result, err := svc.GetItem(input) if err != nil { fmt.Println(err) return } for key, value := range result.Item { fmt.Println( key, ":", value.S, value.N, value.BOOL, ) }
In the GetItemInput interface, the Key attribute is used For specifying items to retrieve from a table, the TableName property is used to specify the table name. The obtained data is stored in the Item property of the return result. You can use a loop to traverse the obtained data and print it out.
3. Delete data
The following code shows how to use AWS SDK for Go to delete data in the DynamoDB table:
svc := dynamodb.New(sess) input := &dynamodb.DeleteItemInput{ Key: map[string]*dynamodb.AttributeValue{ "ID": { N: aws.String("123"), }, "Name": { S: aws.String("John"), }, }, TableName: aws.String("TableName"), } _, err := svc.DeleteItem(input) if err != nil { fmt.Println(err) return }
In DeleteItemInput, the Key attribute is used to specify the For deleted items, the TableName property is used to specify the table name.
5. Use conditional expressions
AWS DynamoDB is quite powerful and supports the use of conditional expressions to query, update and delete data. Conditional expressions use logical operators such as AND operator, OR operator, relational operator, function, etc. to build conditions. The following code demonstrates how to use AWS SDK for Go to query data in a DynamoDB table based on specific conditions:
svc := dynamodb.New(sess) input := &dynamodb.QueryInput{ KeyConditionExpression: aws.String("ID = :idval"), ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":idval": { S: aws.String("123"), }, }, TableName: aws.String("TableName"), } result, err := svc.Query(input) if err != nil { fmt.Println(err) return } for _, item := range result.Items { fmt.Println(item) }
In the QueryInput interface, KeyConditionExpression is used to specify the conditions of the query, ExpressionAttributeValues is used to specify the value of the condition, TableName The attribute specifies the table name.
6. Using transaction control in DynamoDB
AWS DynamoDB provides a transaction control function that can ensure the integrity of transaction logical units when in read and write states. DynamoDB transactions need to meet the following characteristics:
The following code demonstrates how to use transactions in Go:
sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) db := dynamodb.New(sess) tableName := aws.String("product") txOps := []*dynamodb.TransactWriteItem{ { Delete: &dynamodb.Delete{ TableName: aws.String(*tableName), Key: map[string]*dynamodb.AttributeValue{ "product_id": {N: aws.String("1")}, }, }, }, } txCtxt := &dynamodb.TransactWriteItemsInput{ TransactItems: txOps, } result, err := db.TransactWriteItems(txCtxt) if err != nil { fmt.Println("failed to delete product 1") return } fmt.Println(result)
In the above code, we first create the DynamoDB client and specify the table to process. Then, a transaction operation is defined that deletes the product data record with key "1". Finally, define a DynamoDB transaction context object and pass the transaction operations to be performed to the TransactWriteItems method.
7. Use DynamoDB to conditionally update data
条件更新是将新值写回项目时使用的一种机制。当特定条件被给定时,更新操作将执行。要使用条件更新,必须满足以下条件:
下面是一个条件更新的示例:
updateInput := &dynamodb.UpdateItemInput{ TableName: aws.String("product"), Key: map[string]*dynamodb.AttributeValue{ "product_id": {N: aws.String("2")}, }, UpdateExpression: aws.String("set productName = :n"), ConditionExpression: aws.String("attribute_exists(product_id)"), ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":n": {S: aws.String("product_name_new")}, }, } _, err = db.UpdateItem(updateInput) if err != nil { fmt.Println(err) return }
上述示例是使用条件更新更新了产品ID为“2”的产品名称。在条件表达式中,我们使用了attribute_exists
函数来检查该项目是否存在。
八、总结
在本文中,我们深入介绍了 DynamoDB 及其在Go语言中的使用方法。我们讨论了配置 AWS SDK for Go,创建和删除表,添加、读取和删除数据,使用条件表达式,事务控制以及条件更新数据。由于 DynamoDB 具有可伸缩性、高可用性和良好的性能,因此可以成为处理大规模数据集合的首选数据库解决方案之一。
如果您想开始使用 AWS DynamoDB 和 Go,强烈建议您参考 AWS 官方文档 以便获得更详细的信息和 API 示例。
The above is the detailed content of Using AWS DynamoDB in Go: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!