DQL: How to query nodes by array of IDs?

I have an array of IDs to example:

idsArray := [3]string{"a", "b", "c"}

And how do I build a query to get all nodes with those ids using only one query?

dgraphQuery := `{
    queryUser(func: has(id, "$idsArray")) {
        user.name
    }
}`
response, err := client.dgraphClient.NewReadOnlyTxn().QueryWithVars(context.Background(), dgraphQuery, map[string]string{"$idsArray": idsArray}) // error here

Any ideas? Thanks

1 Like

Are these uids like 0x2, 0x3, etc. Or are they values from a different predicate?

If uids, then use the uid(...) function. If predicate values, then use the eq(...) function

1 Like

Its a different predicate. And is it possible to insert an array (last line of code) or I need to use it in another way?

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