Dgraph GraphQL Tour

Schema

Query with Reverse Edges

In the previous lesson, you saw a schema that includes two-way relationships or bidirectional edges. Now, you can run some more advanced queries that use the bidirectional edges that you have set up so far in your database.

With balanced inverse relationships, you can query which company a specific person works for, and also query which employees work at a specific company.

With a data graph that flows in both directions along these bidirectional edges, you can develop a multitude of applications. In this query we want to know who works for “Company ABC” without having to add extra edges. In the same operation, we are also getting a single person, Jack, and getting his employers.

The power of inverse relationships might not be very evident with this small example dataset. But, if you imagine a large dataset where you have thousands of people and thousands of companies, you can see how having only one-way relationships would make some queries less efficient.

On the topic of query efficiency, you should know that using the @cascade directive repeatedly in a query is not always the most efficient query method. This is because @cascade is a post-query filter run before results are returned, which causes all of the nodes to be read by the query even if they are removed from the response.

The following queries return the same nodes as the query in the editor, but do so with less efficiency by repeatedly relying on the @cascade directive.

{
  queryPerson @cascade(fields:["employers"]) {
    xid
    name
    employers(filter: { name: { eq: "CompanyABC" } }) @cascade(fields:["id"]) {
      id
      name
    }
  }
  queryCompany @cascade(fields:["employees"]) {
    id
    name
    employees @cascade(fields:["xid"]) {
      xid
      name
    }
  }
}

The query operation above uses the parameterized cascade syntax to require only specific fields.

3.5 Query with Reverse Edges