Query similar documents

Prismic no longer recommends the gatsby-source-prismic-graphql plugin

With recent changes to Gatsby, Prismic no longer recommends the gatsby-source-prismic-graphql plugin that this documentation uses. Read more about the future of Prismic and Gatsby. We highly recommend using the gatsby-source-prismic instead. The documentation for this plugin can be found in the plugin's github README.

We will leave this documentation here for now, but will change it in the future when we determine the best approach for Prismic & Gatsby.

The similar argument allows you to find documents in your Prismic repository that have similar content to a given document. This allows you to build an automated content discovery feature (for example, a "Related posts" section).

The similar argument

The similar argument is followed by an object with these arguments:

  • documentId - The ID of a given document.
  • max - It represents the maximum number of retrieved documents. The higher the value, the more documents that will be returned. A lower maximum value will return less documents.

In the following example you can see that we are querying all documents of the type Video that are similar to the document with the ID field that has the value of "XmjhAxUAACQA39Fx" and set the maximum number to 20 documents.

You must use the document ID

The documentID can only be the ID of a given document. If you use a different value, for example: a UID field, the query won't work.

Then we retrieve a Title field that has the API ID of "video_name" and a Rich Text field that has the API ID of "creator_name":

Copy
{
  prismic {
    allVideos(similar: {documentId: "XmjhAxUAACQA39Fx", max: 20}) {
      edges {
        node {
          video_name
          creator_name
        }
      }
    }
  }
}

How it works

When you perform this query in Prismic, here's what happens behind the scenes. The content from every field in your selected document is transformed into a string and then concatenated. Then Prismic will check all the other documents and find occurrences of words between the documents. This is how it finds similar documents.

This is also why the max value is important. The higher the maximum number of returned documents, the more general the match will be. The lower the max is, the more specific the match will need to be to make the cut.