Ce plugin permet l'intégration de la recherche via Elastic Lunr. Le contenu est indexé puis mis à disposition via graphql pour se réhydrater dans un index elasticlunr
. À partir de là, des requêtes peuvent être effectuées sur cet index pour récupérer les pages par leur identifiant.
Installez le plugin via npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search
. Consultez le dépôt du site de démonstration pour des détails de mise en œuvre plus spécifiques.
Ensuite, mettez à jour votre fichier gatsby-config.js
pour utiliser le plugin.
gatsby-config
module . exports = {
plugins : [
{
resolve : `@andrew-codes/gatsby-plugin-elasticlunr-search` ,
options : {
// Fields to index
fields : [
'title' ,
'keywords' ,
] ,
// How to resolve each field's value for a supported node type
resolvers : {
// For any node of type MarkdownRemark, list how to resolve the fields' values
MarkdownRemark : {
title : node => node . frontmatter . title ,
keywords : node => node . frontmatter . keywords ,
} ,
} ,
} ,
} ,
] ,
} ;
L'index de recherche sérialisé sera disponible via graphql. Une fois interrogé, un composant peut créer un nouvel index élastique Lunr avec la valeur extraite de la requête graphql. Des requêtes de recherche peuvent être effectuées sur l'index de recherche hydraté. Le résultat est un tableau d’ID de document. L'index peut renvoyer le document complet étant donné un identifiant de document
import React , { Component } from 'react' ;
import { Index } from 'elasticlunr' ;
// Graphql query used to retrieve the serialized search index.
export const query = graphql `query
SearchIndexExampleQuery {
siteSearchIndex {
index
}
}` ;
// Search component
export default class Search extends Component {
constructor ( props ) {
super ( props ) ;
this . state = {
query : `` ,
results : [ ] ,
} ;
}
render ( ) {
return (
< div >
< input type = "text" value = { this . state . query } onChange = { this . search } / >
< ul >
{ this . state . results . map ( page => (
< li >
{ page . title } : { page . keywords . join ( `,` ) }
< / li >
) ) }
< / ul >
< / div >
) ;
}
getOrCreateIndex = ( ) => this . index
? this . index
// Create an elastic lunr index and hydrate with graphql query results
: Index . load ( this . props . data . siteSearchIndex . index ) ;
search = ( evt ) => {
const query = evt . target . value ;
this . index = this . getOrCreateIndex ( ) ;
this . setState ( {
query ,
// Query the index with search string to get an [] of IDs
results : this . index . search ( query )
// Map over each ID and return the full document
. map ( ( {
ref ,
} ) => this . index . documentStore . getDoc ( ref ) ) ,
} ) ;
}
}