Dgraph GraphQL Tour
Basic
Hello World
For the following queries to run, you should have completed the introduction to setup your backend, define your schema, and insert the sample data. To learn more, see the GraphQL tour introduction.
Let’s have a look at a “hello world” query in GraphQL.
Each query has at least one named root function, and query results are labeled accordingly.
Dgraph generates these functions based on a schema that you provide. In the
GraphQL tour introduction, we looked at an example
schema that consisted of two types: Person
and Animal
. For each type, Dgraph
can generate three GraphQL queries, get<Type>
, query<Type>
, and
aggregate<Type>
. So, from the two types we provided Dgraph generated the
following queries:
getPerson
queryPerson
aggregatePerson
getAnimal
queryAnimal
aggregateAnimal
The getPerson
and getAnimal
queries require an input identifying the single
node of that type to return. If you are new to graph databases, think of GraphQL
types as similar to tables, and think of nodes as similar to table rows (or
records). The queryPerson
and queryAnimal
queries return all of the nodes of
that type (by default). These queries can be provided inputs to filter, order,
and paginate through query results. The aggregatePerson
and aggregateAnimal
queries return aggregated calculations but do not return the results (nodes)
themselves. The most common use cases for aggregate queries is to count the
number of nodes. Aggregate queries can accept a filter argument to aggregate a
filtered selection of nodes.
Dgraph identifies each node with a unique internal id, its UID
. This UID
can
be mapped to a field in the GraphQL schema by using the ID
scalar. In the
GraphQL schema, Dgraph also provides a mechanism for referencing nodes by
external ids, XID
. You can map an XID
to a field in the schema by using the
@id
directive. In our example schema, we mapped the UID to the id
field and
the XID to the xid
field of each type. You do not need to use either of these
to perform query<Type>
queries, but to use the get<Type>
queries you will
need to use at least one of these id mechanisms. Because Dgraph maps between
UIDs and XIDs, you can use get<Type>
queries with either of these identifying
fields.
You select fields for your query by providing a list of desired fields in your
GraphQL query syntax. In our example query, we request the id
, xid
, name
,
and age
fields. For any field that does not have a set value, null
is
returned.
Run the query example provided here to see the results returned.
You will see right away that the results are in JSON format and take the same shape as the query itself.
Something to try: Change the query to select someone else. You can check the sample data again.
The tutorial covers connecting the client to the GraphQL API, so just focus on the query syntax for now.