Git Product home page Git Product logo

isabella232 / gatsby-plugin-elasticlunr-search Goto Github PK

View Code? Open in Web Editor NEW

This project forked from botify-hq/gatsby-plugin-elasticlunr-search

0.0 0.0 0.0 1.36 MB

Gatsby search plugin via elastic lunr client-side search index. Forked from andrew-codes/gatsby-plugin-elasticlunr-search to work with gatsby-v2.

Home Page: https://gatsby-contrib.github.io/gatsby-plugin-elasticlunr-search/

License: MIT License

JavaScript 49.64% CSS 50.36%

gatsby-plugin-elasticlunr-search's Introduction

Search Plugin for Gatsby

This plugin enables search integration via elastic lunr. Content is indexed and then made available via graphql to rehydrate into an elasticlunr index. From there, queries can be made against this index to retrieve pages by their ID.

It is a fork of gatsby-plugin-elasticlunr-search made in order to use the plugin with gatsby-v2.

Getting Started

Install the plugin via npm install --save @gatsby-contrib/gatsby-plugin-elasticlunr-search.

See the example site code for more specific implementation details.

Next, update your gatsby-config.js file to utilize the plugin.

Setup in gatsby-config

Here's an example for a site that create pages using markdown, in which you you'd like to allow search features for title and tags frontmatter entries.

gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `@gatsby-contrib/gatsby-plugin-elasticlunr-search`,
      options: {
        // Fields to index
        fields: [`title`, `tags`],
        // 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,
            tags: node => node.frontmatter.tags,
            path: node => node.frontmatter.path,
          },
        },
      },
    },
  ],
}

Consuming in Your Site

The serialized search index will be available via graphql. Once queried, a component can create a new elasticlunr index with the value retrieved from the graphql query. Search queries can be made against the hydrated search index. The results is an array of document IDs. The index can return the full document given a document ID.

In gatsby-v2, it is possible to use graphql queries inside components using StaticQuery.

Suppose that you want to include the Search component inside an Header component. (Of course, you could also query siteSearchIndex from layout.js component, and pass it down as prop to any component that need it.)

First, query the data with StaticQuery inside the Header component, and pass it as props to the Search component.

components/header.js

import React from "react"
import { StaticQuery, Link } from "gatsby"
import { graphql } from "gatsby"

import Search from "./search"

const Header = () => (
  <StaticQuery
    query={graphql`
      query SearchIndexQuery {
        siteSearchIndex {
          index
        }
      }
    `}
    render={data => (
      <header>
        ... header stuff...
        <Search searchIndex={data.siteSearchIndex.index} />
      </header>
    )}
  />
)

export default Header

And then use the searchIndex inside your Search component.

components/search.js

import React, { Component } from "react"
import { Index } from "elasticlunr"

// 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 key={page.id}>
              <Link to={"/" + page.path}>{page.title}</Link>
              {": " + page.tags.join(`,`)}
            </li>
          ))}
        </ul>
      </div>
    )
  }
  getOrCreateIndex = () =>
    this.index
      ? this.index
      : // Create an elastic lunr index and hydrate with graphql query results
        Index.load(this.props.searchIndex)

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

Partial Searches

If you want your search to include partial matches, for example if you had the following data:

sku: ["ab21345", "ab98765", "abcdef12"]

And wanted a search for "ab" to return all of those data, then you can simply include { expand: true } as the second parameter to this.index.search() when setting the results state.

Taking the above example implementation, adapt the search function in the Search component to the following:

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, { expand: true }) // Accept partial matches
      // Map over each ID and return the full document
      .map(({ ref }) => this.index.documentStore.getDoc(ref)),
  })
}

gatsby-plugin-elasticlunr-search's People

Contributors

andrew-codes avatar mathieuforest avatar rafi avatar shrmnk avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.