13 DynamoDB PHP Query Examples
Written by Ravindu Perera
Published on May 18th, 2022
- Setup
- Create Table
- Update Table
- List Tables
- Delete Table
- Add Item
- Get Item
- Update Item
- Delete Item
- Get Multiple Items
- Batch Write to Update Multiple Records
- Create a Table Using a Global Secondary Index
- Querying for Global Secondary Index
- Conclusion
Time to 10x your DynamoDB productivity with Dynobase [learn more]
DynamoDB is a cloud-hosted NoSQL database from Amazon Web Services (AWS). It offers dependable performance, a fully managed environment, and easy API access to interact with it. DynamoDB is designed to handle high-scale applications with low latency and high availability.
This article will help you perform various queries in DynamoDB with PHP.
If you're looking for a similar guide but for Node.js, Rust, and Python/Boto3, we have those as well.
Table of Contents
- Setup
- Create Table
- Update Table
- List Tables
- Delete Table
- Add Item
- Get Item
- Update Item
- Delete Item
- Get Multiple Items
- Batch Write to Update Multiple Records
- Create a Table Using a Global Secondary Index
- Querying for Global Secondary Index
Setup
You can easily install AWS SDK for PHP using 3 methods:
- As a dependency via Composer.
- As a prepackaged phar of the SDK.
- As a ZIP file of the SDK.
Please refer to the AWS documentation to find more about these 3 methods.
After installation, you can create a new database client like the below:
Create Table
You can easily create a DynamoDB table using the createTable
method from the AWS-SDK. It accepts multiple parameters as inputs, including table name, attribute definitions, billing mode, local secondary indexes, global secondary indexes, provisioned throughput, etc.
However, you need to ensure that the table name is unique within the AWS region you select. If all the parameters are in place, the createTable
method will immediately return the TableStatus
as CREATING
. Once the table is created, the status will be updated to ACTIVE
. Then you can start performing read and write requests on the table.
You can also use Dynobase to create tables.
Update Table
You can use the updateTable
method to update existing DynamoDB tables. It allows updating provisioned throughput, enabling or disabling streams, and creating or removing global secondary indexes. However, you will be only allowed to perform one of the above operations at once.
The below example shows how to update the provisioned throughput using the updateTable
method.
List Tables
You can use the listTables
method to retrieve the details of existing DynamoDB tables. There, you need to define the start table name and the number of tables you need to retrieve. DynamoDB will return a paginated response with 100 table names per page.
The first table name this operation will evaluate is the value returned for LastEvaluatedTableName
in a previous operation.
Delete Table
You can easily delete a DynamoDB table using the deleteTable
method. You only need to provide the table name:
Add Item
DynamoDB uses the putItem
method to add items to a DynamoDB table.
DynamoDB's putItem
method will create a new item or replace an item with the same primary key. You can also use conditions in the putItem
method.
The use of empty string and binary attribute values is permitted. However, if the attribute is used as a key attribute for a table or index, attribute values for data types must have a length larger than zero. In addition, there can't be any empty set type attributes. A validation exception will be thrown for invalid requests with empty values.
Get Item
When you need to access the data item in the table, you can quickly call the getItem
method to access any item from the table. The primary key should be specified to get the relevant item.
Update Item
You can use the updateItem
method to update an item in a DynamoDB table.
In the above example, a new attribute called jobId is added and set to 001, the salary is reduced by 2000, and the address attribute is removed from the table. Finally, the updated change will be applied to the record where the eid is 1, and the name is emp 01.
You can also use a conditional expression to update an item with a condition. For that, you need to invoke the ConditionExpression
method.
In the above code snippet, the salary will update to 60000 where the salary is greater than 50000 in the given record. This conditional expression will ensure that you do the exact change to the exact attribute.
Delete Item
You can delete an item from a DynamoDB table using the deleteItem
method.
Once you delete an item, you cannot retrieve that value again. As mentioned in updating items, you can also use ConditionExpression
to delete a specific attribute after executing a particular condition. For example, if you want to delete employee details that are allocated in another company, you can use the below code:
Get Multiple Items
You can use batchGetItem
to get multiple items from a table. However, batchGetItem
method execution is parallel. Therefore, you cannot guarantee the order of the retrieved items.
Batch Write to Update Multiple Records
To update multiple records in one instance, you need to invoke the batchWriteItem
method by defining the keys of records you need to put or delete in your DynamoDB table.
The BatchWriteItem
operation can write or remove up to 16 MB of data in a single operation. If one or more tables do not exist, if the request contains more than 25 items, if any of the items are more than 400 KB, or if the overall data size exceeds 16 MB, the BatchWriteItem
operation will be refused.
There is no method to recover data that has been destroyed.
Create a Table Using a Global Secondary Index
A global secondary index is an index with a partition key and sort key different from the keys on the base table. Let's see how to create a table using a secondary index.
For that, you need to specify AttributeDefinitions
, KeySchema
, and GlobalSecondaryIndex
. In the employeeTable
, we will use eid
and name
as primary indexes, while department
and address
as the hash and range keys for GlobalSecondaryIndex
.
Querying for Global Secondary Index
Here, you have to invoke the query
method on the DynamoDB client by specifying secondary index keys which you used to perform the query. In the below example, we fetch all the data where the department is Dep 1.
DynamoDB replicates the data to secondary indexes and creates a hash and range indexing on the duplicated data. All requests for this index are forwarded to the secondary index itself when we query for it.
Conclusion
DynamoDB is a powerful NoSQL database service provided by AWS, designed to handle large-scale applications with ease. By leveraging the AWS SDK for PHP, you can perform a wide range of operations on your DynamoDB tables, from creating and updating tables to querying and managing items. Understanding these operations and how to implement them in PHP can significantly enhance your ability to build robust and scalable applications. For more advanced use cases, consider exploring features like DynamoDB Streams, Transactions, and the integration with other AWS services such as Lambda and API Gateway.