gatsby plugin elasticlunr search
1.0.0
該插件支援透過 elastic lunr 進行搜尋整合。內容被索引,然後透過 graphql 重新產生elasticlunr
索引。從那裡,可以針對該索引進行查詢,以透過頁面 ID 檢索頁面。
透過npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search
安裝插件。有關更具體的實作細節,請參閱演示網站儲存庫。
接下來,更新您的gatsby-config.js
檔案以使用該插件。
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 ,
} ,
} ,
} ,
} ,
] ,
} ;
序列化搜尋索引將透過 graphql 提供。查詢後,元件可以使用從 graphql 查詢檢索到的值來建立新的彈性 lunr 索引。可以針對水合搜尋索引進行搜尋查詢。結果是文檔 ID 的陣列。給定文檔 ID,索引可以傳回完整文檔
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 ) ) ,
} ) ;
}
}