Created
October 24, 2021 06:58
-
-
Save markilott/03d974aee133899e36a3b5d8c47558ae to your computer and use it in GitHub Desktop.
DynamoDB Query Examples in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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