4

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.

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Amy
  • 136
  • 1
  • 4

2 Answers2

0

Are you using the Node.js library referenced here: https://cloud.google.com/datastore/docs/reference/libraries

There is a function get where you can pass in an array of keys and it will return the array of entities.

https://googleapis.dev/nodejs/datastore/latest/Datastore.html#get

Alex
  • 5,141
  • 12
  • 26
0

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;
}
Emmanuel
  • 1,436
  • 1
  • 11
  • 17