DynamoDB Joins By Example

Users from traditional RDBMS usually wonder how to do joins in DynamoDB. The simple answer is that you have to do it manually.

That is, get item from table A and use its attribute to query items from table B.

const result = dynamoDb.get({
  Key: {
    id: topicId
  },
  TableName: 'topics'
});

const item = result.Item;
const forumId = item.forumId;

const result2 = dynamoDb.get({
  Key: {
    id: forumId
  },
  TableName: 'forums'
});

// or you may query against a secondary index

const result2 = dynamoDb.query({
  KeyConditionExpression: '#someId = :foreignId',
  ExpressionAttributeNames: { '#someId': 'someId' },
  ExpressionAttributeValues: { ':foreignId': foreignId },
  IndexName: 'mySecondaryIndex',
  TableName: 'myTableB'
})