Skip to content

Instantly share code, notes, and snippets.

@ajmalafif
Created January 5, 2021 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajmalafif/07c021359083a22d67d262dc6093db4c to your computer and use it in GitHub Desktop.
Save ajmalafif/07c021359083a22d67d262dc6093db4c to your computer and use it in GitHub Desktop.
Algolia + Sanity.io + Gatsby queries
const escapeStringRegexp = require("escape-string-regexp")
// const pagePath = `content`
// const indexName = `Pages`
const pageQuery = `{
pages: allMdx {
edges {
node {
id
frontmatter {
title
}
fields {
slug
}
excerpt(pruneLength: 5000)
}
}
}
}`
const postQuery = `{
posts: allSanityPost {
edges {
node {
id
title
slug {
current
}
_rawExcerpt
}
}
}
}`
function pageToAlgoliaRecord({ node: { id, frontmatter, fields, ...rest } }) {
return {
objectID: id,
...frontmatter,
...fields,
...rest,
}
}
function postToAlgoliaRecord({ node: { id, slug, ...rest } }) {
return {
objectID: id,
...slug,
...rest,
}
}
const queries = [
{
query: pageQuery,
transformer: ({ data }) => data.pages.edges.map(pageToAlgoliaRecord),
indexName: `Pages`,
settings: { attributesToSnippet: [`excerpt:20`] },
},
{
query: postQuery,
transformer: ({ data }) => data.posts.edges.map(postToAlgoliaRecord),
indexName: `Posts`,
settings: { attributesToSnippet: [`excerpt:20`] },
},
]
module.exports = queries
@ajmalafif
Copy link
Author

For future reference, some idea for a better alternative approach by Corey Ward (@coreyward) from Sanity.io Slack channel:

In short, I used the Sanity webhooks to notify a serverless function wehn documents changed. On each invocation it fetches the relevant data from the changed documents, fetches related search index objects from Algolia, and then does simple comparison to see what changes need to be made to the index. Because Algolia works best with small objects and I wanted full text search, each “section” of the page is indexed individually but pointing to the page slug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment