DQL: How to query nodes by array of IDs?

Without seeing your schema, this is a guess. I am assuming this schema:

type User {
  id: Int! @id
  name
}

If you are using id: ID! then those are actual Dgraph uids not a different predicate.

References:

https://dgraph.io/docs/query-language/functions/#equal-to

https://dgraph.io/docs/query-language/graphql-variables/

The query syntax without variables would be:

{
  queryUser(func: eq(User.id, ["a","b","c"])) {
    uid
    id: User.id
    name: User.name
  }
}

If you are using a specific array size then you can use variables like:

query queryUser($a: string, $b: string, $c: string) {
  queryUser(func: eq(User.id, [$a, $b, $c])) {
    uid
    id: User.id
    name: User.name
  }
}

To use a variable size array, it becomes weird because this is stated as supported by this note from the docs:

Note If you want to input a list of uids as a GraphQL variable value, you can have the variable as string type and have the value surrounded by square brackets like ["13", "14"] .

But that is specifically stated a "list of uids", so is a list of strings also supported, idk. You will have to test this of find someone else who has done this. Myself, I would just use template strings to make this work, even though that would be ugly and prone to query injection if you don’t check this input first.

// JavaScript
const idsArray = ["a","b","c"]
const dgraphQuery = `{
  queryUser(func: eq(User.id, ${JSON.stringify(idsArray)})) {
    uid
    id: User.id
    name: User.name
  }
}`
const res = await dgraphClient.newTxn().query(dgraphQuery);
3 Likes