gatsby plugin elasticlunr search
1.0.0
ปลั๊กอินนี้เปิดใช้งานการรวมการค้นหาผ่าน lunr แบบยืดหยุ่น เนื้อหาได้รับการจัดทำดัชนีแล้วเผยแพร่ผ่าน graphql เพื่อเติมน้ำกลับเข้าไปในดัชนี elasticlunr
จากนั้น คุณสามารถสอบถามกับดัชนีนี้เพื่อดึงข้อมูลเพจตาม ID ของพวกเขาได้
ติดตั้งปลั๊กอินผ่าน npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search
ดู repo ไซต์สาธิตสำหรับรายละเอียดการใช้งานที่เฉพาะเจาะจงมากขึ้น
จากนั้น อัปเดตไฟล์ 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 เมื่อสอบถามแล้ว ส่วนประกอบจะสามารถสร้างดัชนี lunn แบบยืดหยุ่นใหม่พร้อมค่าที่ดึงมาจากแบบสอบถาม graphql คำค้นหาสามารถทำได้โดยเทียบกับดัชนีการค้นหาแบบไฮเดรต ผลลัพธ์คืออาร์เรย์ของรหัสเอกสาร ดัชนีสามารถส่งคืนเอกสารฉบับเต็มโดยระบุรหัสเอกสาร
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 ) ) ,
} ) ;
}
}