Flexsearch.js Plugin for Gatsby
Gatsby plugin for full text search implementation based on FlexSearch.js client-side index, heavily inspired in the gatsby-plugin-lunr.
Getting Started
Install gatsby-plugin-flexsearch
npm install --save gatsby-plugin-flexsearch
Add gatsby-plugin-flexsearch
configuration to the gatsby-config.js
as following:
moduleexports = plugins: resolve: 'gatsby-plugin-flexsearch' options: // L languages: 'en' type: 'MarkdownRemark' // Filter the node types you want to index // Fields to index. fields: name: 'title' indexed: true // If indexed === true, the field will be indexed. resolver: 'frontmatter.title' // Attributes for indexing logic. Check https://github.com/nextapps-de/flexsearch#presets for details. attributes: encode: 'balance' tokenize: 'strict' threshold: 6 depth: 3 store: true // In case you want to make the field available in the search results. name: 'description' indexed: true resolver: 'frontmatter.description' attributes: encode: 'balance' tokenize: 'strict' threshold: 6 depth: 3 store: false name: 'url' indexed: false resolver: 'fields.slug' store: true
Implementing Search in Your UI
The search data will be available on the client side via window.__FLEXSEARCH__
that is an object with the following fields:
index
- a flexsearch index instancestore
- object that stores the indexed gatsby nodes where the id of each node corresponds to the id the filter, according with flexsearch.js best practices (https://github.com/nextapps-de/flexsearch#best-practices)).
// Search component state = query: '' results: { const ResultList = { if thisstateresultslength > 0 return thisstateresults else if thisstatequerylength > 2 return 'No results for ' + thisstatequery else if thisstateresultslength === 0 && thisstatequerylength > 0 return 'Please insert at least 3 characters' else return '' } return <div className=thispropsclassNames> <input className="search__input" type="text" onChange=thissearch placeholder='Search' /> <div className="search__list"> <ResultList /> </div> </div> } { // adicionar variável para língua var index = window__FLEXSEARCH__enindex var store = window__FLEXSEARCH__enstore if !query || !index return else var results = // search the indexed fields Object // find the unique ids of the nodes results = Array // return the corresponding nodes in the store var nodes = store return nodes } { const query = eventtargetvalue if thisstatequerylength > 2 const results = this this else this }