How to retrieve entities by passing array of IDs as input in Google datastore?

Viewed 256

I am trying to implement the following SQL logic in the datastore,

SELECT * from table where id in [1,2,3,4,5]

Implementing this in datastore, I want to retrieve all the corresponding entities with these IDs as an array.

let employees = []
try {
  for (let id of idArray) {
    const employee = await employeeRepo.getOneById(workspace, id)
    employees.push(employee)
  }
} catch (e) {
  throw e;
 }

This is the naive logic of the function, and I am trying to reduce it to a single query.

2 Answers

It's possible to do by using get as mentioned in the documentation

Here's an example of how to do it based on your code:

const employee1 = this.datastore.key(['Employee', 1]);
const employee2 = this.datastore.key(['Employee', 2]);
const employee3 = this.datastore.key(['Employee', 3]);

const keys = [employee1, employee2, employee3];

try {
    const [employees] = await datastore.get(keys);
} catch (e) {
    throw e;
}
Related