Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

# Explicitly Model Schema Relationships with the @relation Directive in neo4j-graphql-js

Matt Ross
Neo4j
GraphQL

We will learn to use the `@relation` directive provided by `neo4j-graphql-js` to make the relationships in our model explicit in our schemas.

### You must be a Member to view code

Access all courses and lessons, track your progress, gain confidence and expertise.

Become a Member
and unlock code for this lesson

### Transcript

Instructor: Let's start out by making sure we don't have any data in our graph, so we can start with a clean slate. Now, we can fill a few nodes representing a person, a species, a planet, and a film. While we create these, we'll also relate them to each other.

We can get a quick look at the graph model we built to see how these nodes relate to each other. A person has a species and homeworld, and appeared in a film. A species appeared in a film, and a planet appeared in a film.

We can see a tidy little graph as the result of that query, which looks like what we can call a subgraph in our model. Let's create schemas in our API to represent the new film and species nodes that we've added.

We'll also fill in the properties and types of our relationships. If we run our API server, we can put together a query to get back all of the nodes we created. What's missing, however, is any indication of the relationships between these nodes.

In typical GraphQL fashion, we could write some resolvers to handle this for us. Instead, we're going to let neo4j-graphql-js do the lifting. Enter the relation directive. We can use this to easily describe within our schema any relationships a type of node has to another node.

We can reference external film nodes by decorating person, planet, and species with relations that go out to a film. That goes the same for a person's homeworld and species properties. Similarly, we can reference these same nodes from a film by describing them on the film schema as relations that come in from some other node.

Now, we can take a look at our updated API and query against these relations. As with any other GraphQL implementation, we can query and hydrate data in an arbitrarily nested structure. Not only do we save some development cycles by not building resolvers, but we also get to keep working in a Graph mindset.

Let's take a look at our API's logged output. Rather than query the database for a person node, read its properties in JavaScript, then go back to the database to hydrate those properties, neo4j-graphql-js will create a single query, and walk the graph in one step to fill in all of the data we need.

The schema tab in our GraphQL playground will also now contain a whole new class of mutations. Now, we can not only create nodes, but also relationships between existing nodes.