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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay