Este plugin permite a integração de pesquisa via elastic lunr. O conteúdo é indexado e disponibilizado via graphql para reidratar em um índice elasticlunr
. A partir daí, consultas podem ser feitas nesse índice para recuperar páginas por seu ID.
Instale o plugin via npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search
. Consulte o repositório do site de demonstração para obter detalhes de implementação mais específicos.
Em seguida, atualize seu arquivo gatsby-config.js
para utilizar o 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 ,
} ,
} ,
} ,
} ,
] ,
} ;
O índice de pesquisa serializado estará disponível via graphql. Uma vez consultado, um componente pode criar um novo índice lunr elástico com o valor recuperado da consulta graphql. As consultas de pesquisa podem ser feitas no índice de pesquisa hidratado. O resultado é uma matriz de IDs de documentos. O índice pode retornar o documento completo dado um ID de documento
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 ) ) ,
} ) ;
}
}