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