Search code examples
typescriptamazon-web-servicesamazon-dynamodbtypescript2.0

How to query AWS DynamoDb using GSI Index and FilterExpression


My DynamoDB database table is as follows. It has primary key(ID) and sort key (receivedTime).

  ID(primary key)   receivedTime(sort key)     Data
  ID1               1670739188                  3
  ID2               1670723198                  5
  ID2               1674785188                  7
  ID3               1670721388                  5

I want to query by ID and received time in range: -
example :
ID - ID2,
range - 1670723188 to 1673723188

I created GSI Index and Primary key is ID. I write query code like this,

 ID const params = {
    IndexName: 'Query-ID-index',
    KeyConditionExpression: '#ID = :ID',
    FilterExpression:
      '#receivedTime BETWEEN :startTime AND :endTime ',
    ExpressionAttributeNames: {
      '#ID': 'ID',
      '#receivedTime': 'receivedTime',
    },
    ExpressionAttributeValues: {
      ':ID': id,
      ':startTime': startTime,
      ':endTime': endTime,
    },
    TableName: 'tableName',
  };
  const data = await docClient.query(params).promise();

But data.Item is empty. Any one can help how to solve.


Solution

  • Why do you need an index? Do the Query from your main table:

    const params = {
        KeyConditionExpression: '#ID = :ID AND #receivedTime BETWEEN :startTime AND :endTime',
        ExpressionAttributeNames: {
          '#ID': 'ID',
          '#receivedTime': 'receivedTime',
        },
        ExpressionAttributeValues: {
          ':ID': id,
          ':startTime': startTime,
          ':endTime': endTime,
        },
        TableName: 'tableName',
      };
      const data = await docClient.query(params).promise();