Home > Blockchain >  How to query AWS DynamoDB
How to query AWS DynamoDB

Time:10-25

I wasn't able to find a complete example that clearly demonstrates how to query items of a DynamoDB table.

  • The docs do not specify which property to use (I am guessing a combination of ExpressionAttributeValues and KeyConditionExpression).
  • The other documentation uses an outdated library aws-sdk
  • The explanation here is convoluted, extremely verbose and unclear.
  • And, my preferred resource, the examples repo, do not tie the explanation with a working example.

Lets suppose my table contains the following elements:

| Primary Key | Sort Key             |
|-------------|----------------------|
| **pk**      | **sk**               |
| fruit       | available-pear       |
| fruit       | eaten-apple          |
| fruit       | available-watermelon |
| fruit       | eaten-grape          |
| desert      | eaten-apple-pie      |

I would like to query (not scan) the table by only the available fruits.

I can't even query all the fruits.

import { DynamoDBClient, QueryCommand } from '@aws-sdk/client-dynamodb';

let dynamoClient = new DynamoDBClient({ region: process.env.REGION });

const command = new QueryCommand({
  // The tableName is correct and verified against the CF template
  TableName: tableName,
  ExpressionAttributeValues: {
    ':pk': { S: 'fruit' },
  },
  // I tryied all these variations
  // and also tryied removing ExpressionAttributeValues
  KeyConditionExpression: 'pk = :pk',
  KeyConditionExpression: 'pk = :fruit',
});
const response = dynamoClient.send(command);

console.log('RESPONSE:');
console.log(JSON.stringify(response));

Gives me an empty response

INFO    RESPONSE:
INFO    {}

Any help is much appreciated,

CodePudding user response:

Query all fruit:

const command = new QueryCommand({
    TableName: tableName,
    KeyConditionExpression: 'pk = :pk',
    ExpressionAttributeValues: { ':pk': { S: 'fruit' }},
});

Query available fruit:

const command = new QueryCommand({
    TableName: tableName,
    KeyConditionExpression: '#pk = :pk AND begins_with(#sk, :sk)',
    ExpressionAttributeNames: { '#pk': 'pk', '#sk': 'sk' }, // optional names substitution
    ExpressionAttributeValues: { ':pk': { S: 'fruit' }, ':sk': { S: 'available' } },
});

send reurns a Promise. Make sure to await it, as @zapi says:

const response = await client.send(command);
  • Related