Dieses Plugin ermöglicht die Suchintegration über Elastic Lunr. Der Inhalt wird indiziert und dann über GraphQL zur Verfügung gestellt, um ihn in einen elasticlunr
Index umzuwandeln. Von dort aus können Abfragen für diesen Index durchgeführt werden, um Seiten anhand ihrer ID abzurufen.
Installieren Sie das Plugin über npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search
. Genauere Implementierungsdetails finden Sie im Demo-Site-Repo.
Aktualisieren Sie als Nächstes Ihre Datei gatsby-config.js
um das Plugin zu nutzen.
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 ,
} ,
} ,
} ,
} ,
] ,
} ;
Der serialisierte Suchindex wird über graphql verfügbar sein. Nach der Abfrage kann eine Komponente einen neuen elastischen LUNR-Index mit dem aus der GraphQL-Abfrage abgerufenen Wert erstellen. Suchanfragen können anhand des hydratisierten Suchindex gestellt werden. Das Ergebnis ist ein Array von Dokument-IDs. Der Index kann bei Angabe einer Dokument-ID das vollständige Dokument zurückgeben
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 ) ) ,
} ) ;
}
}