简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM