Skip to content

Get a Single Item From the DynamoDB Table using Python

Posted on:August 5, 2023 at 05:17 AM

In the last blog, we learned how to put items in the DynamoDB table. In this blog, we will learn how to get a single item from a DynamoDB table using Python and boto3.

Table of contents

Open Table of contents

Prerequisites

Before we read items in the DynamoDB table, ensure you have the below things ready.

  1. I have already created the DynamoDB table in the AWS account. This table is named “orders,” and it has a primary key of “order_id” and a sort key of “order_date.” In this blog, you can learn how to create a DynamoDB table using AWS CDK.
  2. IAM user with the required permission to write data to the DynamoDB table. You can learn how to create an IAM user and attach a policy to this blog.
  3. Configure this IAM user as an AWS profile on your machine. This blog goes through how to configure AWS profiles on your system.
  4. If you do not want to or can not configure the AWS profile on your machine, then you can use the IAM user’s access key ID and secret access key along with Python and botot3. This blog reviews different ways we can use IAM credentials with python boto3.

I will use AWS CLI profile, Python, and boto3 to put items into the DynamoDB table.

Get a single Item from the DynamoDB Table

When we want to read a specific Item from the DynamoDB table, we can use the get_item function. This function needs the primary key and sort key (if the table uses the sort key) of the item we want to read/get from the DynamoDB table. Below, we have code to get a single item from the DynamoDB table.

import boto3
from pprint import pprint

boto3.setup_default_session(profile_name="ah")

table_name = "orders"
dynamodb_resource = boto3.resource("dynamodb")
orders_table = dynamodb_resource.Table(table_name)


def get_item_from_table():
    response = orders_table.get_item(
        Key={
            "order_id": "ord1236",
            "order_date": "2022-08-03",
        }
    )
    pprint(response["Item"])

    # output
    """
    {
     'amount': Decimal('157'),
     'order_date': '2022-08-03',
     'order_id': 'ord1236',
     'user_email': '[email protected]'
     }

In the code, we have passed values for order_id and order_date to the get_item function, which is the primary key and sort key of an item we want to read from the DynamoDB table. When we run this function, we will get an item matching our key, as shown in the output block.

When you pass key for an item that does not exists in DynomoDB table, gte_item function does not raise error. If there is no matching item, get_ietm does not return any data and there will be no Item element in the response.

DynamoDB Boto3 Docs

Get an Item from DynamoDB with Selected Attributes

If you have any experience with SQL, you may have written queries like select column1, column2 from table;. This query will give you data for only two columns, even when a table has hundreds of columns.

Items in the DynamoDB table can have many attributes, and we may need only a few. If we can select only the required attributes, we can have faster reads and not need to send unnecessary data to clients. Can we do something similar with the DynamoDB table?

Of course, we can. We can select the required attributes for an item in DynamoDB by passing the ProjectionExpression parameter to the get_item function. Let us look at its example below.

def get_item_with_specific_attributes():
    response = orders_table.get_item(
        Key={"order_id": "ord1236", "order_date": "2022-08-03"},
        ProjectionExpression="order_id,amount",
    )
    pprint(response["Item"])

    # output
    # {'amount': Decimal('157'), 'order_id': 'ord1236'}

In the above code, we have passed order_id and amount to ProjectionExpression. Hence, in output, we only have values for those two attributes.

Get an Item Using Strongly Consistent Read

DynamoDB supports eventually consistent and strongly consistent reads. You can read more about them here. In short, when you use eventual consistency (the default mode), we may not receive updated data for an item in a DynamoDB table. Therefore, if we want to be sure and always need the most recent data for an item, we must use a Strongly consistent read.

We can use a strongly consistent read with the get_item function by passing the ConsistentRead param as True as shown below.

def get_item_with_strongly_consistent_read():
    response = orders_table.get_item(
        Key={"order_id": "ord1236", "order_date": "2022-08-03"},
        ConsistentRead=True,
    )
    pprint(response["Item"])

Capacity consumed for getting an item from DynamoDB

You might need data on how much capacity has been consumed by your read operations on the DynamoDB table. We can get consumed capacity data by passing the ReturnConsumedCapacity parameter to the get_item function.

def get_item_with_consumed_capacity():
    response = orders_table.get_item(
        Key={"order_id": "ord1236", "order_date": "2022-08-03"},
        ConsistentRead=True,
        ReturnConsumedCapacity="TOTAL",
    )
    pprint(response)

    # output
    """
    'ConsumedCapacity': {'CapacityUnits': 1.0, 'TableName': 'orders'},
 'Item': {'amount': Decimal('157'),
          'order_date': '2022-08-03',
          'order_id': 'ord1236',
          'user_email': '[email protected]'}
    """

Conclusion

This blog taught us how to read a single item from the DynamoDB table. But often, we have to read multiple items in a single API call; for example, we want to list all orders for some customer or all orders placed on some day. In the next blog, we will learn how to query the DynamoDB table. See you soon.