Skip to content

Instantly share code, notes, and snippets.

@markilott
Created October 24, 2021 06:58
Show Gist options
  • Save markilott/03d974aee133899e36a3b5d8c47558ae to your computer and use it in GitHub Desktop.
Save markilott/03d974aee133899e36a3b5d8c47558ae to your computer and use it in GitHub Desktop.
DynamoDB Query Examples in Javascript
const AWS = require('aws-sdk');
const moment = require('moment');
const docClient = new AWS.DynamoDB.DocumentClient({
region: process.env.AWS_REGION,
});
// Query where we have used a Reserved Word as the Partition Key
async function getCollectionList(collection) {
/**
* Get a list of items in a collection
* @param {string} collection
* @returns {object[]}
*/
try {
const params = {
TableName: 'myTable',
KeyConditionExpression: '#c = :c',
ExpressionAttributeValues: {
':c': collection,
},
// ExpressionAttributeNames is required because we have used a reserved word "Collection"
ExpressionAttributeNames: {
'#c': 'Collection',
},
};
const response = await docClient.query(params).promise();
return response.Items;
} catch (err) {
throw err;
}
}
// Query using an index with Partition Key "AssetId" and a date range in a Sort key "LogTime" (an ISO8601 string)
// We are also filtering for an 'ENABLED' AssetStatus
async function getAssetLogs(assetId) {
/**
* Get a list of items from the last 24hrs
* @param {string} assetId
* @returns {object[]}
*/
try {
const now = moment().toISOString();
const start = moment().subtract(hours, '24').toISOString();
const params = {
TableName: 'myTable',
IndexName: 'assetIdx',
KeyConditionExpression: 'AssetId = :s and LogTime between :y and :n',
FilterExpression = 'AssetStatus = :s', // Applied after the KeyConditionExpression
ExpressionAttributeValues: {
':n': now,
':y': start,
':id': assetId,
':s': 'ENABLED'
},
ScanIndexForward: false, // Descending
};
const response = await docClient.query(params).promise();
return response.Items;
} catch (err) {
throw err;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment