Complex GraphQL Filtering With neo4j-graphql.js

Use filtering in your GraphQL queries without writing any resolvers

--

The recently released version 2.5.0 of neo4j-graphql.js includes support for handling complex filtering in GraphQL queries. The filter functionality is exposed by adding a filter argument with associated inputs based on the GraphQL type definitions that expose filtering criteria. This complex filtering functionality is available in neo4j-graphql.js, neo4j-graphql-java, and the Neo4j GraphQL database plugin.

This article assumes some level of familiarity with the Neo4j GraphQL integrations, please see this page for an overview.

Let’s take a look at some examples of using complex filtering with a movies dataset. It’s important to note that for these examples we write very little code besides our GraphQL type definitions. The neo4j-graphql.js library is handling data fetching through its generated resolvers, including the logic for these complex filters.

Given the following GraphQL type definitions, let’s see how we can make use of these filters:

GraphQL type definitions for a simple movie API. See it in action at https://codesandbox.io/s/r047mmrnln

You can see the code for this movies GraphQL API in the Codesandbox embedded at the bottom of this post or available in Codesandbox here.

Filter argument

When we create a GraphQL schema with neo4j-graphql.js, a generated API is created which exposes a filter field argument. First, a simple example: find movies released after 1920:

This results in a generated Cypher query like this:

We can combine filter inputs:

which are then combined in an AND operator in the generated Cypher query:

Nested Filter

To filter based on the results of nested fields applied to the root, we can nest our filters. For example, to search for movies whose title starts with “River” and has at least one actor whose name contains “Brad”:

This generated Cypher query is a bit more complex because we need to filter based on the properties of actor nodes connected to movies:

Logical Operators: AND, OR

Filters can be wrapped in logical operators OR and AND For example:

We can also nest these AND and ORs. This query is searching for zombie Comedy movies that either star Jesse Eisenberg or are not animated:

Filtering In Selections

Filters can be also be used throughout the selection set to apply the filter at the level of the selection. For example:

Check out the neo4j-graphql.js docs for more examples and a list of the filtering criteria available.

Try It Out!

Try out this powerful filter functionality using this Codesandbox example:

Share your story

Are you building something cool with GraphQL? Consider sharing your story by submitting a talk to GraphQL Summit in San Francisco.

--

--