@gatsby-contrib/gatsby-plugin-elasticlunr-search

中文文档
3.0.2发布于 2021/03/16MITCommonJS近 30 天下载 3569

Search for gatsby; implemented via elasticlunr.

原始使用文档
文档目录4 节
  1. Setup in gatsby-config
  2. Consuming in Your Site
  3. Partial Searches
  4. Optimize handling of data models with nested nodes

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,
          },
        },
        // Optional filter to limit indexed nodes
        filter: (node, getNode) => node.frontmatter.tags !== "exempt",
      },
    },
  ],
}

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, 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"
import { Link } from "gatsby"

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

Optimize handling of data models with nested nodes

There are times when you have a data model that has nested nodes. Example resolver configuration in gatsby-config.js:

resolvers : {
  // For any node of BlogPost, list how to resolve the fields' values
  BlogPost : {
    title         : node => node.title,
    featuredImage : node => node.featuredImage___NODE // featuredImage is of type Asset below and is an id reference to Asset
  },

  // For any node of type Asset, this is how BlogPost featuredImage is resolved
  Asset : {
    fileUrl : node => node.file && node.file.url
  }
}

The problem with the above resolvers configuration is that it will include all Asset models in the elasticlunr index, potentially bloating the elasticlunr index and leading to large bundle sizes and slower page load times.

The solution is to make use of the second paramater passed to each field resolver function called getNode. getNode is the same function provided by gatsby to the setFieldsOnGraphQLNodeType node api method and when called with a data model node id it will return a node with all it's data. The above example of the BlogPost model with the nested featuredImage property of type Asset then becomes:

resolvers : {
  // For any node of BlogPost, list how to resolve the fields' values
  BlogPost : {
    title         : node => node.title,
    featuredImage : (node, getNode) => getNode(node.featuredImage___NODE) // featuredImage is of type Asset and is now the Asset model itself
  }
}

Now you can use the featuredImage data of BlogPost model without including all Asset models in the elasticlunr index (see PR #3 for more details).

You can now also resolve the gatsby store with getNodesByType and getNodes so the full signature of node resolving is this:

(node, getNode, getNodesByType, getNodes)

Documentation of all node helpers:

版本与发布记录

@gatsby-contrib/gatsby-plugin-elasticlunr-search 共发布 14 个版本,首次发布于 2018/10/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.2latest2021/03/165 年前
3.0.12021/03/165 年前
3.0.02021/03/165 年前
2.4.22020/06/116 年前
2.4.12020/06/116 年前
2.4.02020/06/116 年前

关于 @gatsby-contrib/gatsby-plugin-elasticlunr-search 的常见问题

@gatsby-contrib/gatsby-plugin-elasticlunr-search 是什么?

Search for gatsby; implemented via elasticlunr.

如何安装 @gatsby-contrib/gatsby-plugin-elasticlunr-search?

在项目目录运行 npm install @gatsby-contrib/gatsby-plugin-elasticlunr-search,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:gatsby(>3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gatsby-contrib/gatsby-plugin-elasticlunr-search 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/gatsby-contrib__gatsby-plugin-elasticlunr-search 是否存在。

@gatsby-contrib/gatsby-plugin-elasticlunr-search 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gatsby-contrib/gatsby-plugin-elasticlunr-search 可以商用吗?

@gatsby-contrib/gatsby-plugin-elasticlunr-search 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gatsby-contrib/gatsby-plugin-elasticlunr-search 的下载量有多少?

根据 npm 官方下载统计,@gatsby-contrib/gatsby-plugin-elasticlunr-search 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,569 次,日均约 119 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gatsby-contrib/gatsby-plugin-elasticlunr-search 还在维护吗?

最新版本 3.0.2 发布于 2021/03/16(5 年前);至今共发布 14 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。