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 ) ) ,
} ) ;
}
}