Created
May 21, 2022 15:37
-
-
Save joaobispo2077/9f34f2beb7add19887009ba131dcbf83 to your computer and use it in GitHub Desktop.
Dynamo DB, Query Global Secondary Index (GSI) with DynamoDB Toolbox and with AWS SDK in Node.js
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
"use strict"; | |
require("dotenv/config"); // Load environment variables from .env file | |
// 1. Table definition | |
const DynamoDB = require('aws-sdk/clients/dynamodb'); | |
const { Table } = require('dynamodb-toolbox'); | |
const DocumentClient = new DynamoDB.DocumentClient(); | |
const GLOBAL_SECONDARY_INDEX_NAME = '_et-pk-index'; | |
const usersTable = new Table({ | |
name: process.env.DYNAMODB_TABLE_NAME, | |
partitionKey: 'pk', | |
sortKey: 'sk', | |
indexes: { | |
[GLOBAL_SECONDARY_INDEX_NAME]: { | |
partitionKey: '_et', | |
sortKey: 'pk', | |
}, | |
}, | |
DocumentClient, | |
}); | |
/* I have a database with users that _et (Entity) has "User" data */ | |
// 2. Query global secondary index with DynamoDBToolbox | |
const users = await usersTable.query('User', { | |
...options, | |
index: '_et-pk-index', | |
}); | |
console.info('users.Items', users.Items); | |
// 3. Query global secondary index with AWS SDK | |
const result = await DocumentClient | |
.query({ | |
TableName: process.env.DYNAMODB_TABLE_NAME, | |
IndexName: GLOBAL_SECONDARY_INDEX_NAME, | |
Limit: 10, | |
ScanIndexForward: true, | |
KeyConditionExpression: '#_et = :et', | |
ExpressionAttributeNames: { | |
'#_et': '_et', | |
}, | |
ExpressionAttributeValues: { | |
':et': 'User', | |
}, | |
}) | |
.promise(); | |
console.info('result', result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment