DynamoDB Query in Python (boto3)

query reads every item that shares one partition key, optionally narrowing by the sort key. With the boto3 resource API you build the condition with the Key helper from boto3.dynamodb.conditions — no hand-written expression strings.

Code

import boto3
from boto3.dynamodb.conditions import Key

dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("Music")

def query_songs_by_artist(artist):
    items = []
    kwargs = {
        "KeyConditionExpression": Key("Artist").eq(artist)
        & Key("SongTitle").begins_with("C"),
        "ScanIndexForward": True,  # False = descending
        "Limit": 100,
    }

    while True:
        response = table.query(**kwargs)
        items.extend(response["Items"])

        # Paginate: stop when there's no continuation key
        if "LastEvaluatedKey" not in response:
            break
        kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]

    print(f"Found {len(items)} songs")
    return items

if __name__ == "__main__":
    query_songs_by_artist("Arturo Sandoval")

Explanation

  • Key("Artist").eq(artist) — the required partition-key equality. Chain one sort-key condition with & (.begins_with, .between, .lt, .gt, etc.). The Key helper generates the expression, names, and values for you.
  • ScanIndexForwardTrue (default) is ascending sort-key order; False reverses it.
  • Limit — items per page, applied before any FilterExpression.
  • Pagination — one query returns at most 1 MB. When more remains, response["LastEvaluatedKey"] is present; feed it back as ExclusiveStartKey until it's gone. The loop collects the whole result set.
  • Query a secondary index by adding IndexName="...".
  • Numeric attributes in the returned items are decimal.Decimal.

Do it visually

The DynamoDB Expression Builder assembles the key condition and copies runnable code, so you don't hand-write Key(...) chains.

To run queries against real tables in a GUI — key-condition form, paginated grid, copy the generated boto3 code — download DynoTable.

无需控制台即可使用 DynamoDB

DynoTable 是面向 DynamoDB 的快速桌面客户端 —— 浏览表、运行 SQL 风格的查询,并在本地编辑项。