How to filter entries by linked references in GraphQL
Tags: javascript, webdev, graphql
Published: 2021-06-16 09:12:44

Have you ever been frustrated by not being able to filter a collection by a linked entry value using the GraphQL API? For example, do you want to filter your blog posts by linked topics such as “javascript” or “tutorial”? Check out this quick guide that shows you how to get the data you need using the linkedFrom field in your query — it’s pretty nice!

Let’s say you’re making great progress on building your new blog site. You’re using Contentful’s GraphQL API and it’s a good time. You’ve written some great blog posts — and now you want a way to categorize them in your front-end application. For example, you want to show posts tagged with “JavaScript” on a single URL. Nice.

You create a new “Topic” content type, which contains text fields for `name` and `slug`.

![Screenshot of a Topic content type in Contentful, showing name and slug fields.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj50x831n3p6glyuch4q.png)

You update your blog post content model with a new field called `topics`, which is an array of linked references (remember `type: Array<Link>` for later).

![A screenshot of a Blog Post content type in Contentful showing a Topic field which is an array of linked references.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dl7h6p1wb6dcezo9h2xn.png)

You add the relevant topics as links to each blog post entry. Beautiful.

![A screenshot of the Topics field on a Blog Post entry, showing the linked topics Jamstack, Tutorials, Contentful and JavaScript.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfsltpijlm917hx3rev9.png)

Here’s how the content model might look, visualized by [contentmodel.io](https://contentmodel.io/). The blog post has a field `topics`, which is a reference to many (n) “Topic” content types, which have fields `name` and `slug`.

![Screenshot of Contentful content model as visualised on contentmodel.io.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0f33ej8et37wq168ymma.png)

Here’s how you might display collections of blog posts per topic in your web application.

![A screenshot of a JavaScript topic page on my blog site.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czxnz52h2ogm342955ua.png)

Now it’s time to construct the GraphQL query. Let’s search the docs to see how we can query the blog post collection and filter by linked topic!

![Screenshot of collection filter Contentful docs.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4f5ehdd07ypdd3ezg9dz.png)
 
But what’s this? [The documentation](https://www.contentful.com/developers/docs/references/graphql/#/reference/collection-filters/limitations) states that it is not possible to filter on fields of Type Array<Link>! **So, what do we do?**

![Screenshot of Contentful GraphQL filter limitations.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yhba5vukszy725aqy1x.png)

### There’s no need to rage quit! 

This type of query is made possible with the **linkedFrom** field! Let’s take a look at how it works.

## Install the GraphQL Playground App

Let’s investigate how we can build this query in the Contentful GraphQL Playground App within the Contentful web app. Install the app by navigating to Apps and follow the instructions for installation. Authorize the app to access your Contentful account and provide it with a Content Preview API key. Click save.

![Screenshot showing how to install GraphQL playground app in Contentful.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtf3adsyw5f988z0s3xe.png)

After installing the GraphQL Playground App, navigate to it via Apps in the navigation.

![Screenshot of Contentful app navigation showing the GraphQL playground link.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwhli54ephbud9knsnxl.png)

What I love about GraphQL is that it’s self-documenting. Tools such as GraphQL Playground allow you to explore what data and types of queries are available on your content model. You can read the provided in-app documentation or use nifty auto-completion (we’ll do that later in the post). All this functionality is made possible by GraphQL Introspection Queries. [Check out this video from Shy on Introspection Queries](https://www.youtube.com/watch?v=udou5eV9QFw) to learn more. It’s definitely worth a watch — I learned a lot!

## How to build a linkedFrom query

I like to think of a linkedFrom query as “reversing” the query you actually want to make. Instead of querying blog posts and filtering the results by linked topic, we’re going to query a single topic and fetch the blog posts that contain that topic as a linked reference.

Let’s start by querying our topicCollection. If you’ve set up the topic content type as described above with the fields `name` and `slug`, paste the query below into the GraphQL Playground App.

```graphql
query {
  topicCollection {
    items {
      name
      slug
    }
  }
}
```

The response will include an array of items containing the name and slug properties as requested.

![Screenshot of the topic collection query in the GraphQL playground app.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1b5wyq07r99lemy47lts.png)

Let’s update the query to fetch a single topic by slug — `javascript`.

```graphql
query {
  topicCollection(where: { slug: "javascript" }, limit: 1) {
    items {
      name
      slug
    }
  }
}
```

Here’s the updated response.

![A screenshot of a topicCollection query by slug javascript in the GraphQL playground.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhcb5w63yybwg0xvqxb7.png)
 
What we really want to return in our query is a list of blog posts that contain the referenced topic `javascript`. Here’s where we can use **linkedFrom** — and thanks to Introspection Queries — the GraphQL Playground gives us some hints!

![Screenshot of linkedfrom popup helper in the GraphQL playground.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wplrqgk1sdtstxt7f3m9.png)

Let’s request some fields from the `blogPostCollection` items that reference the `javascript` topic using the query below:

```graphql
query {
  topicCollection(where: { slug: "javascript" }, limit: 1) {
    items {
    	linkedFrom {
        blogPostCollection {
          total
          items {
            title
            slug
            date
          }
        }
      }
    }
  }
}
```

And here’s the response:

![A screenshot of a linkedFrom query in the GraphQL playground, fetching blog posts that have linked tags of JavaScript.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7ndhogou84z3htzwc91.png)

And there you have it! 

Using the linkedFrom field is an effective way to request all entries that reference entries of Type Array<Link>. I’ve really enjoyed learning about this!

## A real-world example

If you’d like to see the complete query for my topics pages, [take a look at this file in the code](https://github.com/whitep4nth3r/p4nth3rblog/blob/1d4cce53ea440e6dabb1eaa52c4c5322eac08ce4/contentful/BlogPost.js#L381) for my personal blog site. [The statically generated page is available to view here](https://whitep4nth3r.com/topics/javascript).

Is there something you’d like to learn more about to get the most out of Contentful? Come and let us know in the [Community Slack](https://www.contentful.com/slack). We’re a friendly bunch!