'dynamodb query multiple values from GSI

I have a dynamo DB table (id(pk),name(sk),email,date,itemId(number)) and GSI on (itemId pk, date(sk) trying to query for an array of itemIds [1,2,3,4] but getting error using the IN statement in KeyExperssionValue when doing

aws.DocClient.query

 const IdsArrat = [1,2,3,4,5];
 const query: {
  IndexName: 'accountId-createdAt-index',
  KeyConditionExpression: 'itemId IN (:a1,:a2,:a3)',
  ExpressionAttributeValues: {
    {
        ':a1':1,
        ':a2':2,
          .......
    }
  },
  ScanIndexForward: false,
},

getting error using the IN statement in.

This it possible to query for multiple values on GSI in dynamoDb ?



Solution 1:[1]

You're trying to query for multiple different partition key's in a GSI. This can only be done by doing multiple individual queries (3 in the example). It's also possible with a GSI that multiple values would get returned for a single Partition key lookup, so it's better to query the partition key "itemId" individually.

See the following for reference: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-KeyConditionExpression

Solution 2:[2]

It's not possible to have a IN and join multiple values in a query , but it's possible to use BatchGetItem to request multiple queries that are solved in parallel . This is actually very close to the IN solution you want.

The result will be a list of the elements in the table.

There are limits in the number of queries in the size of the result set < 16 MB and the number of queries < 100.

Please check this document for details : https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 puji
Solution 2 detzu