gatsby-plugin-local-search
Gatsby plugin for providing client-side search for data available in Gatsby's
GraphQL layer using a variety of engines.
The following engines are supported:
This plugin provides a search index and store using the selected engine. To
display search results, pair the index and store with a compatible React hook or
component. See Displaying the search results.
Install
npm install --save gatsby-plugin-local-search
How to use
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-local-search',
options: {
name: 'pages',
engine: 'flexsearch',
engineOptions: 'speed',
query: `
{
allMarkdownRemark {
nodes {
id
frontmatter {
path
title
}
rawMarkdownBody
}
}
}
`,
ref: 'id',
index: ['title', 'body'],
store: ['id', 'path', 'title'],
normalizer: ({ data }) =>
data.allMarkdownRemark.nodes.map((node) => ({
id: node.id,
path: node.frontmatter.path,
title: node.frontmatter.title,
body: node.rawMarkdownBody,
})),
},
},
],
}
How to query
A new node type becomes available named localSearch${name}
, where ${name}
is
the name provided in the options. In the above example, the node would be
accessed with localSearchPages
.
The search index and store are made available as fields on the node.
index
: (String) The search index created using the engine selected in
the plugin options.store
: (JSON) The store used to map a search result's ref
key to data.
Note that store
is an object but does not require you to explicitly query each
field.
{
localSearchPages {
index
store
}
}
Lazy-loading the index and/or store
The index and store can become large depending on the number of documents and
their fields. To reduce your bundle size and delay fetching these pieces of data
until needed, you can query a URL for both the index and store like the
following.
{
localSearchPages {
publicIndexURL
publicStoreURL
}
}
Both publicIndexURL
and publicStoreURL
will return a public URL that can be
fetched at run-time. For example, you could call fetch
with the URLs to load
the data in the background only as the user focuses your interface's search
input.
The files contain data identical to querying for index
and store
directly
and will be saved in your site's /public
folder. This functionality if very
similar to gatsby-source-filesystem
's publicURL
field.
Displaying the search results
This plugin provides a search index and store object but leaves presentation and
search functionality up to you.
The following React components/hooks are recommended pairings: