DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

[20 Days of DynamoDB] Day 9 - Query API

Posted - 18/Jan/2024

The Query API is used to model one-to-many relationships in DynamoDB. You can search for items based on (composite) primary key values using Key Condition Expressions. The value for partition key attribute is mandatory - the query returns all items with that partition key value. Additionally, you can also provide a sort key attribute and use a comparison operator to refine the search results.

With the Query API, you can also:

  1. Switch to strongly consistent read (eventual consistent being the default)
  2. Use a projection expression to return only some attributes
  3. Return the consumed Read Capacity Units (RCU)

Here is an example that queries for a specific thread based on the forum name (partition key) and subject (sort key). It only returns the Message attribute:

    resp, err = client.Query(context.Background(), &dynamodb.QueryInput{
        TableName:              aws.String(tableName),
        KeyConditionExpression: aws.String("ForumName = :name and Subject = :sub"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":name": &types.AttributeValueMemberS{Value: forumName},
            ":sub":  &types.AttributeValueMemberS{Value: subject},
        },
        ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
        ConsistentRead:         aws.Bool(true),
        ProjectionExpression:   aws.String("Message"),
    })
Enter fullscreen mode Exit fullscreen mode

Recommended reading:

  1. API documentation
  2. Item Collections
  3. Key Condition Expressions
  4. Composite primary key

Top comments (0)