Skip to main content

GraphQL Reference

Intro

This page will walk you through a series of GraphQL queries, each designed to demonstrate a particular feature of GraphQL. You’ll be querying the real schema used on graphql-reference example so feel free to experiment and poke around the innards of the site! You can also open the Codesandbox version of it.

You’ll be using GraphiQL, an interactive editor you can also use while building your Gatsby site.

For more information, read about why Gatsby uses GraphQL.

Basic query

Let’s start with the basics, pulling up the site title from your gatsby-config.js’s siteMetaData. Here the query is on the left and the results are on the right.

Try editing the query to include the description from siteMetadata. When typing in the query editor you can use Ctrl + Space to see autocomplete options and Ctrl + Enter to run the current query.

A longer query

Gatsby structures its content as collections of nodes, which are connected to each other with edges. In this query you ask for the total count of plugins in this Gatsby site, along with specific information about each one.

Try using the editor’s autocomplete (Ctrl + Space) to get extended details from the packageJson nodes.

Limit

There are several ways to reduce the number of results from a query. Here totalCount tells you there’s 8 results, but limit is used to show only the first three.

Skip

Skip over a number of results. In this query skip is used to omit the first 3 results.

Filter

In this query filter and the ne (not equals) operator is used to show only results that have a title. A good video tutorial on this is here.

Gatsby relies on Sift to enable MongoDB-like query syntax for object filtering. This allows Gatsby to support operators like eq, ne, in, regex and querying nested fields through the __ connector.

It is also possible to filter on multiple fields - just separate the individual filters by a comma (works as an AND):

filter: { contentType: { in: ["post", "page"] }, draft: { eq: false } }

In this query the fields categories and title are filtered to find the book that has Fantastic in its title and belongs to the magical creatures category.

You can also combine the mentioned operators. This query filters on /History/ for the regex operator. The result is Hogwarts: A History and History of Magic. You can filter out the latter with the ne operator.

Complete list of possible operators

In the playground below the list, there is an example query with a description of what the query does for each operator.

  • eq: short for equal, must match the given data exactly
  • ne: short for not equal, must be different from the given data
  • regex: short for regular expression, must match the given pattern. Note that backslashes need to be escaped twice, so /\w+/ needs to be written as "/\\\\w+/".
  • glob: short for global, allows to use wildcard * which acts as a placeholder for any non-empty string
  • in: short for in array, must be an element of the array
  • nin: short for not in array, must NOT be an element of the array
  • gt: short for greater than, must be greater than given value
  • gte: short for greater than or equal, must be greater than or equal to given value
  • lt: short for less than, must be less than given value
  • lte: short for less than or equal, must be less than or equal to given value
  • elemMatch: short for element match, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators

If you want to understand more how these filters work, looking at the corresponding tests in the codebase could be very useful.

Sort

The ordering of your results can be specified with sort. Here the results are sorted in ascending order of frontmatter’s date field.

You can also sort on multiple fields but the sort keyword can only be used once. The second sort field gets evaluated when the first field (here: date) is identical. The results of the following query are sorted in ascending order of date and title field.

Children's Anthology of Monsters and Break with Banshee both have the same date (1992-01-02) but in the first query (only one sort field) the latter comes after the first. The additional sorting on the title puts Break with Banshee in the right order.

By default, sort fields will be sorted in ascending order. Optionally, you can specify a sort order per field by providing an array of ASC (for ascending) or DESC (for descending) values. For example, to sort by frontmatter.date in ascending order, and additionally by frontmatter.title in descending order, you would use sort: { fields: [frontmatter___date, frontmatter___title], order: [ASC, DESC] }. Note that if you only provide a single sort order value, this will affect the first sort field only, the rest will be sorted in default ascending order.

Format

Dates

Dates can be formatted using the formatString function.

Gatsby relies on Moment.js to format the dates. This allows you to use any tokens in your string. See moment.js documentation for more tokens.

You can also pass in a locale to adapt the output to your language. The above query gives you the english output for the weekdays, this example outputs them in german.

Example: anotherDate(formatString: "dddd, MMMM Do YYYY, h:mm:ss a") # Sunday, August 5th 2018, 10:56:14 am

Dates also accept the fromNow and difference function. The former returns a string generated with Moment.js’ fromNow function, the latter returns the difference between the date and current time (using Moment.js’ difference function).

Excerpt

Excerpts accept three options: pruneLength, truncate, and format. format can be PLAIN or HTML.

Sort, filter, limit & format together

This query combines sorting, filtering, limiting and formatting together.

Query variables

In addition to adding query arguments directly to queries, GraphQL allows to pass in “query variables”. These can be both simple scalar values as well as objects.

The query below is the same one as the previous example, but with the input arguments passed in as “query variables”.

To add variables to page component queries, pass these in the context object when creating pages.

Group

You can also group values on the basis of a field e.g. the title, date or category and get the field value, the total number of occurrences and edges.

The query below gets us all authors (fieldValue) who wrote a book and how many books (totalCount) they wrote. In addition we’re grabbing the title of the author’s books. You can see for example that Bathilda Bagshot wrote three books.

Fragments

Fragments are a way to save frequently used queries for re-use. To create a fragment, define it in a query and export it as a named export from any file Gatsby is aware of. A fragment is available for use in any other GraphQL query, regardless of location in the project. Fragments defined in a Gatsby project are global, so names must be unique.

The query below defines a fragment to get the site title, and then uses the fragment to access this information.

Aliasing

Want to run two queries on the same datasource? You can do this by aliasing your queries. See below for an example:

When you use your data, you will be able to reference it using the alias instead of the root query name. In this example, that would be data.someEntries or data.someMoreEntries instead of data.allMarkdownRemark.

Where next?

Try running your own queries, check out the rest of the docs or run through the tutorial.


Edit this page on GitHub
Docs
Tutorials
Plugins
Blog
Showcase