Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Reading and Writing Items

PutItem and GetItem

Master the two basic DynamoDB operations: PutItem to create or replace an item and GetItem to read one by key, with consistency, projections and CLI and SDK examples.

Almost every application starts with two operations: write an item, read an item. In DynamoDB those are PutItem and GetItem. Both address exactly one item by its full primary key, both complete in a few milliseconds, and both have options that change what they return and what they cost. This lesson covers them completely, including the habits that prevent bugs.

Real calls appear as read-only code (CLI and Python SDK). Runnable stand-ins model the behavior of each option so you can try it.

PutItem: create or replace

PutItem writes a whole item. If no item with that key exists, it creates one. If one does, it replaces it entirely. There is no merge.

Terminal
aws dynamodb put-item \
  --table-name Books \
  --item '{
    "Isbn":   {"S": "978-1-0000-0001-1"},
    "Title":  {"S": "The Quiet Index"},
    "Pages":  {"N": "312"},
    "Tags":   {"SS": ["search", "indexing"]}
  }' \
  --return-values ALL_OLD

Key points:

  • The item must include every key attribute, with the declared type.
  • All other attributes are stored as given. The old item's other attributes are gone.
  • --return-values ALL_OLD returns the item as it was before the write (nothing if it did not exist). The default is NONE.
  • The write is durable once acknowledged: it has been written to a majority of the replicas.
  • Size limits apply: 400 KB per item.

The same call with the Python SDK (boto3), using the resource interface that handles type tags for you:

Python
import boto3

table = boto3.resource("dynamodb").Table("Books")
table.put_item(Item={
    "Isbn": "978-1-0000-0001-1",
    "Title": "The Quiet Index",
    "Pages": 312,
    "Tags": {"search", "indexing"},
})

With the boto3 resource interface, use Decimal for fractional numbers. A Python float is rejected because binary floating point cannot represent every decimal exactly.

GetItem: read one item by key

GetItem returns the item for a full primary key.

Terminal
aws dynamodb get-item \
  --table-name Books \
  --key '{"Isbn": {"S": "978-1-0000-0001-1"}}' \
  --projection-expression "Title, Pages" \
  --consistent-read

Options that matter:

Option Effect
ConsistentRead true returns the latest committed write, at twice the read cost. Default is false (eventually consistent).
ProjectionExpression Return only some attributes, including nested paths such as Address.City.
ExpressionAttributeNames Aliases for reserved words in the projection (see below).
ReturnConsumedCapacity Reports the capacity units the call used.

A missing item produces a response without an Item field. It is not an error, so check for it in your code.

Projection saves bandwidth, not read capacity. DynamoDB still reads the whole item to find the attributes, so the capacity units charged depend on the full item size. A projection only shrinks what is sent to you.

Eventual vs strong consistency

DynamoDB keeps each item on several replicas. An eventually consistent read may hit a replica that has not yet seen your last write, so for a moment it can return the older version. Reads are consistent after typically one second or less. A strongly consistent read always sees the result of every write acknowledged before it, with the trade-offs of higher cost and unavailability during certain network partitions. The consistency lesson later in the course covers when each is worth it.

A stand-in for both operations

This model has the exact semantics we described: replacement, ALL_OLD, projection and empty results. (Consistency is not modelled here.)

Python Stand-in: PutItem replaces, GetItem projects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second put_item returned the old item because of ALL_OLD, and the item afterwards has no Pages attribute: replacement, not merge.

Reserved words and expression attribute names

DynamoDB reserves hundreds of words, such as Name, Status, Date, Year, Size, Count and Comment. If an attribute has such a name you cannot write it directly in an expression. You alias it with ExpressionAttributeNames, whose placeholders start with #.

Terminal
aws dynamodb get-item --table-name Books \
  --key '{"Isbn": {"S": "978-1-0000-0001-1"}}' \
  --projection-expression "#t, #y" \
  --expression-attribute-names '{"#t": "Title", "#y": "Year"}'

Using placeholders for every name from the start is a good habit, since it also protects against names with dots or other special characters.

Python Stand-in: resolve #name placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Idempotency and retries

PutItem is idempotent: sending the same request twice leaves the table in the same state. That makes it safe to retry after a timeout. UpdateItem with ADD (increment) is not idempotent, a difference you will meet in the next lesson.

AWS SDKs retry throttled and transient failures automatically with exponential backoff. You rarely write retry loops yourself, but you should make sure your operations are safe to repeat.

Common mistakes

  • Using PutItem to change one field. It wipes the others. Use UpdateItem, or read, change and write with a condition on a version attribute.
  • Not handling "no item". Code that indexes into response["Item"] crashes for unknown keys.
  • Float values in boto3. Use Decimal or integers.
  • Assuming a strong read is the default. It is not; request it when you need read-after-write.
  • Reading everything to display one field. A projection reduces transfer, but if the item is huge, split it so common reads stay cheap.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does PutItem do when an item with the same key exists?

    PutItem writes the whole item. Unless you add a condition, the previous item is overwritten.
  2. 2. What does GetItem return for a key that does not exist?

    A missing item gives an empty response, so check for the absence of Item.
  3. 3. Does a ProjectionExpression reduce the read capacity consumed?

    DynamoDB reads the whole item, so capacity is based on the item size. The projection only reduces what is returned.
  4. 4. Why use ExpressionAttributeNames?

    Placeholders like #n let you refer to attributes whose names are reserved words or contain special characters.

Summary

  • PutItem creates or fully replaces an item; ReturnValues=ALL_OLD returns the previous version.
  • GetItem needs the full key and returns no Item when nothing matches.
  • Reads are eventually consistent unless you request ConsistentRead, which costs twice as much.
  • Projections reduce transferred data, not consumed capacity.
  • Use #name placeholders for reserved words and special characters.

Next: UpdateItem and Update Expressions