Posted in JavaScript

[AWS] How to do Scan / Query in AWS DynamoDb for JS

aws_logo

For query items from DymanoDb, AWS supports some ways: Scan, Query, BatchGetItem

Below are some examples:

If I have a table ‘GtfsStopTime’ with 2 primaries (tripId & index)

  • Scan items from a list of id:
async getGtfsStopTimeListByTripIds (tripIds) {
    try {
      var list = []
      const attributeValueList = []
      for (let tripId of tripIds) {
        attributeValueList.push({
          S: tripId
        })
      }

      const param = {
        TableName: this._getTableName(),
        ScanFilter: {
          'tripId': {
            'AttributeValueList': attributeValueList,
            'ComparisonOperator': 'IN'
          }
        }
      }

      const data = await this.dynamoDB.scan(param).promise()
      list = data.Items
      return list
    } catch (err) {
      console.error('Error happen')
    }
  }

Note: We cannot apply BatchGetItem in this case because the BatchGetItem require all primary keys of table (in this case, we only query by one primary key – tripId )

  • Query items in DynamoDb using BatchGetItem

Below is example code to fetch items in ‘GtfsStop’ table by list of stopId as input which has stopId is primary key

async getGtfsStopListByIds (stopIdList) {
    const keys = stopIdList.map(function (stopId) {
      return {
        'stopId': {
          S: stopId
        }
      }
    })

    try {
      const params = {
        RequestItems: {
          'GtfsStop': { Keys: keys }
        }
      }
      const fetchedResponse = await this.dynamoDB.batchGetItem(params).promise()
      const gtfsStopItems = fetchedResponse.Responses.GtfsStop
      return gtfsStopItems
    } catch (err) {
      throw new Error(err)
    }
  }
  • Others

 

Hope this topic is useful for you 🙂

Advertisements