0

I have a Posts table which has the following fields:

  • id (PK - STRING)
  • title
  • detail
  • created_at

I have an array containing a list of post.id:

const ids = [];

How can I retrieve all the posts whose id is in my ids variable?

Best Regards

jonathan
  • 105
  • 7
  • 1
    Does this answer your question? [dynamoDB - Get multiple items from DB by array of primary keys](https://stackoverflow.com/questions/34508726/dynamodb-get-multiple-items-from-db-by-array-of-primary-keys) – Maurice Sep 05 '22 at 05:40

1 Answers1

0

There is two ways I can think of, the first being a BatchGetItem which can return up to 100 items per request:

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB({ region: 'eu-west-1' });

const ids = ["1", "2", "3", "4"];


var keys = [];
ids.map((id)=>{
    keys.push({"id":{"S": id}})
});

let params = {
    "RequestItems": {
        "ExampleTable": {
            "Keys": keys
        }
    }
}

ddb.batchGetItem(params)
    .promise()
    .then(res => console.log(JSON.stringify(res)))
    .catch(err => console.log(err))

We can also use ExecuteStatement API provided by the PartiQL wrapper, in which you can pass in up to 50 ids:

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB({ region: 'eu-west-1' });

const exStatement = (statement, params) => {

    ddb.executeStatement({
        Statement: statement,
        Parameters: params.map(id => ({ "S": id }))
    })
        .promise()
        .then(res => {
            console.log(JSON.stringify(res))
        })
        .catch(err => console.log(err))
}

const ids = ["1", "2", "3", "4"];

exStatement(`SELECT * FROM ExampleTable WHERE "id" IN [${ids.map(() => '?').join(',')}]`, ids);
Leeroy Hannigan
  • 11,409
  • 3
  • 14
  • 31