DynamoDBClientの読み込みコマンドは、GetItemCommand、QueryCommand、ScanCommand、BatchGetItemCommand があります。

参考

QueryCommand

参考

ここでは、以下のサンプルで書き込んだデータを読み込みます。

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

interface TestItem {
  pk: string;
  datetime: string;
  count: number;
}

const getDynamoDBTableName = () => {
  return 'dynamodb-test-table';
}

const getDynamoDBClient = () => {
  const client = new DynamoDBClient({
    region: 'ap-northeast-1',
  });
  return client;
}

const getItem = async () => {
  const tableName = getDynamoDBTableName();
  const client = getDynamoDBClient();

  const params: QueryCommandInput = {
    TableName: tableName,
    KeyConditionExpression: 'pk = :PK AND ( #datetime BETWEEN :sortKeyBegin AND :sortKeyEnd )',

    // KeyConditionExpressionのプレースフォルダの値を指定
    ExpressionAttributeValues: {
      ':PK': { S: '東京都新宿区2024-05-01'},
      ':sortKeyBegin': { S: '2024-05-01T03:00:00.000Z' },
      ':sortKeyEnd': { S: '2024-05-01T05:00:00.000Z' },
    },

    // DynamoDBではカラム名が予約後と同じ場合、別の名称に置き換える必要がある。
    // 置き換え後の名称の先頭は必ず "#" になっている必要がある。
    // これはSQLのASのようなもの。カラム名のエスケープは無い。
    ExpressionAttributeNames: {
      '#datetime': 'datetime',
      '#count': 'count'
    },

    // 取得データに含まれるカラムを制限する場合は、ProjectionExpressionで指定する。
    // カラム名は予約後の場合、ExpressionAttributeNamesで置き換えた名称を指定する。
    ProjectionExpression: '#datetime, #count',
  };

  try {
	const command = new QueryCommand(params);
    const result = await client.send(command);
    return result;
  } catch (err) {
    console.log(err);
    throw err;
  };
}

const readItems = async () => {
  const result = await getItem();
  console.log("result: %o", result);
  console.log(result.Items);
}

/**
 * 実行方法
 *  npx ts-node others\samples\ReadSample.ts
 * 
 */
(async () => {
  await readItems();
})();