DynamoDB GetItem in Node.js (AWS SDK v3)

GetItem reads a single item by its full primary key. In AWS SDK v3 you send a GetItemCommand on a DynamoDBClient; the key values use the low-level attribute-value format ({ S: "..." }, { N: "..." }).

Code

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

const client = new DynamoDBClient({region: 'us-east-1'});

async function getSong() {
  const command = new GetItemCommand({
    TableName: 'Music',
    Key: {
      Artist: {S: 'Arturo Sandoval'},
      SongTitle: {S: 'Cubano Chant'}
    },
    // Optional: return only the attributes you need
    ProjectionExpression: 'Artist, SongTitle, AlbumTitle, #yr',
    ExpressionAttributeNames: {'#yr': 'Year'}
  });

  const response = await client.send(command);

  if (!response.Item) {
    console.log('Item not found');
    return null;
  }

  console.log(response.Item);
  // { Artist: { S: 'Arturo Sandoval' }, SongTitle: { S: 'Cubano Chant' }, ... }
  return response.Item;
}

getSong();

To get plain JavaScript values instead of { S: "..." } wrappers, pass response.Item through unmarshall from @aws-sdk/util-dynamodb, or use the DynamoDBDocumentClient from @aws-sdk/lib-dynamodb.

Explanation

  • TableName — the table to read from.
  • Key — must include every primary-key attribute: the partition key alone for a simple key, or partition and sort key for a composite key. GetItem will not accept a partial key.
  • ProjectionExpression — optional; limits which attributes come back (saves bandwidth, not read cost). Year is a reserved word, so it's aliased via ExpressionAttributeNames (#yr).
  • response.Itemundefined when no item matches; always check before using it.
  • By default reads are eventually consistent. Add ConsistentRead: true for a strongly-consistent read (costs 2× the RCU, base table only).

Do it visually

Building the projection or a conditional read by hand? Use the free DynamoDB Expression Builder to assemble the expression and copy the exact ProjectionExpression / ExpressionAttributeNames values.

To browse tables and run GetItem in a GUI — key form, results grid, one-click copy of the generated code — download DynoTable.

Console なしで DynamoDB を扱う

DynoTable は DynamoDB 向けの高速なデスクトップクライアントです — テーブルを閲覧し、SQL スタイルのクエリを実行し、アイテムをローカルで編集できます。