DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

1 1

[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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay