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 クエリから取得した値を使用して新しい Elastic 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 ) ) ,
} ) ;
}
}