Skip to main content

Query Variables

In this section we'll learn how to create and use Query Variables

Defining Query Variable#

This time let's start explaining variables in dqlx starting from a plain DQL statement.

var(func: eq(name, $0)) {
film {
performance {
D AS genre
}
}
}

then you will write the variable this way

variable := dqlx.Variable(dql.EqFn("name", "test")).
Edge("film").
Edge("film->performance", dqlx.Select(`
D AS genre
`))

If you want to add a variable on an edge you'll use EdgeAs() function, For example:

A AS var(func: eq(name, $0)) {
B AS film {
C AS performance {
D AS genre
}
}
}

You'll write

variable := dqlx.Variable(dql.EqFn("name", "test")).
As("A").
EdgeAs("B", "film").
EdgeAs("C", "film->performance", dqlx.Select(`
D AS genre
`))

Use the variable#

To use a variable within a query is super simple, just add the variable to a query using the Variable() method then refer to it with the P function (P stands for Predicate).

variable := dqlx.Variable(dql.EqFn("name", "test")).
Edge("film").
Edge("film->performance", dqlx.Select(`
D AS genre
`))
db.QueryType("Film").
Select("uid").
Filter(dqlx.Eq{
"genre": dqlx.P("D"),
}).
Variable(variable)

Value Variables#

Value Variables

Value variables store scalar values. Value variables are a map from the UIDs of the enclosing block to the corresponding values.
Value variables are used by extracting the values with val(var-name), or by extracting the UIDs with uid(var-name).

To use value variables you can simply use the Val() function

variable := dqlx.Variable(dql.AlloftermsFn("name@en", "The Princess Bride")).
Edge("starring").
EdgeAs("pbActors", "starring->performance.actor", dqlx.Select(
dqlx.As("roles", dqxl.Count("actor.film")),
))
db.Query(dqlx.UIDFn(dqlx.P("pbActors"))).
OrderAsc(dqlx.Val("roles")).
Select(
"name@en",
dqlx.Alias("numRoles", dqlx.Val(roles)),
)