Code Monkey home page Code Monkey logo

gatsby-plugin-elasticlunr-search's Introduction

Maintainability Codacy Badge

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.

Getting Started

Install the plugin via npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search. See the demo site repo for more specific implementation details.

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

Setup in 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,
                    },
                },
            },
        },
    ],
};

Consuming in Your Site

The serialized search index will be available via graphql. Once queried, a component can create a new elastic lunr 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

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

gatsby-plugin-elasticlunr-search's People

Contributors

andrew-codes avatar mathieuforest avatar rafi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

gatsby-plugin-elasticlunr-search's Issues

Full text search?

Is it possible to perform full text searches?

My data is coming from Contentful. I want the search to cover the title and the full text of the body markdown field, and for it to search over all instances of a particular content type.

error Cannot query field "siteSearchIndex" on type "Query" graphql/template-strings

I've searched through all the related issues and tried everything I could find, but I'm still getting the following error when I try to save my header component with the Search component included:

error Cannot query field "siteSearchIndex" on type "Query" graphql/template-strings

I'm fairly new to Gatsby so I may have overlooked something. Any help would be greatly appreciated.

Here are the relevant site files:

package.json:

{
	"name": "gatsby-wordpress-starter",
	"description": "",
	"version": "",
	"author": "",
	"dependencies": {
		"@gatsby-contrib/gatsby-plugin-elasticlunr-search": "^2.3.0",
		"babel-plugin-styled-components": "^1.10.1",
		"elasticlunr": "^0.9.5",
		"gatsby": "^2.11.0",
		"gatsby-cli": "^2.7.9",
		"gatsby-image": "^2.1.4",
		"gatsby-plugin-manifest": "^2.1.1",
		"gatsby-plugin-offline": "^2.1.3",
		"gatsby-plugin-postcss": "^2.0.7",
		"gatsby-plugin-react-helmet": "^3.0.12",
		"gatsby-plugin-sharp": "^2.1.5",
		"gatsby-plugin-styled-components": "^3.1.0",
		"gatsby-source-filesystem": "^2.0.39",
		"gatsby-source-wordpress": "^3.0.64",
		"gatsby-transformer-sharp": "^2.1.21",
		"intersection-observer": "^0.7.0",
		"isomorphic-fetch": "^2.2.1",
		"postcss-extend-rule": "^2.0.0",
		"postcss-import": "^12.0.1",
		"postcss-mixins": "^6.2.1",
		"postcss-nested": "^4.1.2",
		"postcss-preset-env": "^6.6.0",
		"postcss-simple-vars": "^5.0.2",
		"prop-types": "^15.7.2",
		"react": "^16.8.6",
		"react-dom": "^16.8.6",
		"react-helmet": "^5.2.1",
		"simple-crypto-js": "^2.0.2",
		"styled-components": "^4.3.2"
	},
	"devDependencies": {
		"prettier": "^1.18.2",
		"typescript": "^3.5.2"
	},
	"keywords": [
		"gatsby",
		"wordpress",
		"ACF",
		"ACF Pro",
		"Advanced Custom Fields",
		"Flexible Content"
	],
	"license": "MIT",
	"scripts": {
		"build": "gatsby build",
		"develop": "gatsby develop",
		"format": "prettier --write src/**/*.{js,jsx}",
		"start": "npm run develop",
		"serve": "gatsby serve",
		"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
	},
	"repository": {
		"type": "git",
		"url": "git+https://github.com/gatsbyjs/gatsby-starter-default.git"
	},
	"bugs": {
		"url": "https://github.com/gatsbyjs/gatsby/issues"
	},
	"homepage": "https://github.com/gatsbyjs/gatsby-starter-default#readme",
	"main": "gatsby-browser.js"
}

gatsby-config.js:

module.exports = {
	siteMetadata: {
		title: `Gatsby - Wordpress`,
	},
	plugins: [
		`gatsby-plugin-react-helmet`,
		{
			resolve: `gatsby-source-filesystem`,
			options: {
				name: `images`,
				path: `${__dirname}/src/images`,
		},
		},
		`gatsby-plugin-styled-components`,
		`gatsby-transformer-sharp`,
		`gatsby-plugin-sharp`,
		{
			resolve: `gatsby-plugin-manifest`,
			options: {
				name: `gatsby-starter-default`,
				short_name: `starter`,
				start_url: `/`,
				background_color: `#663399`,
				theme_color: `#663399`,
				display: `minimal-ui`,
				icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
			},
		},
		{
			resolve: `gatsby-source-wordpress`,
			options: {
				baseUrl: `test-gatsby-admin.pantheonsite.io`,
				protocol: `http`,
				hostingWPCOM: false,
				useACF: true,
				acfOptionPageIds: [],
				verboseOutput: true,
				perPage: 100,
				searchAndReplaceContentUrls: {
					sourceUrl: `test-gatsby-admin.pantheonsite.io`,
					replacementUrl: `test-gatsby-admin.pantheonsite.io`,
				},
				concurrentRequests: 10,
				includedRoutes: [
					"**/categories",
					"**/posts",
					"**/pages",
					"**/media",
					"**/menus",
					"**/tags",
					"**/taxonomies",
					"**/users",
					"**/example-cpt",
					"**/example-tax",
				],
				excludedRoutes: [],
				normalizer: function( { entities } ) {
					return entities
				},
			},
		},
		{
			resolve: `@gatsby-contrib/gatsby-plugin-elasticlunr-search`,
			options: {
				// Fields to index
				fields: [ `title`],
				// How to resolve each field`s value for a supported node type
				resolvers: {
					wordpress__PAGE: {
						title: node => node.title,
						path: node => node.slug,
					},
					wordpress__POST: {
						title: node => node.title,
						path: node => node.slug,
					},
				},
			},
		},
		{
			resolve: `gatsby-plugin-postcss`,
			options: {
				postCssPlugins: [
					require( `postcss-import` ),
					require( `postcss-simple-vars` ),
					require( `postcss-nested` ),
					require( `postcss-mixins` ),
					require( `postcss-extend-rule` ),
					require( `postcss-preset-env` )( {
						stage: 0 ,
						autoprefixer: {
							grid: true
						}
					} ),
				],
			},
		},
		{
			resolve: `gatsby-source-filesystem`,
			options: {
				name: `images`,
				path: `${__dirname}/src/images/`,
				ignore: [`**/\.*`], // ignore files starting with a dot
			},
		},
	],
}

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

header.js:

import React from 'react'
import { StaticQuery, Link } from 'gatsby'
import Img from 'gatsby-image'
import { graphql } from "gatsby"
import './header-styles.css'

import Navigation from '../navigation/navigation'
import Search from '../search/search'

const Header = ( { siteLogo } ) => (
	<StaticQuery
		query={ graphql`
			query SearchIndexQuery {
				siteSearchIndex {
					index
				}
			}
		` }
		render={ data => (
			<header className='site-header'>
				<a href='#main-content' className='screen-reader-text'>Skip to main content</a>
				<div className='site-header__inner'>
					<div className="site-header__wrap">
						<Link to="/" className='site-header__logo'>
							<Img fluid={ siteLogo } alt='Gatsby Logo' />
						</Link>
						<Navigation navType='header-nav' />
					</div>
					<Search searchIndex={ data.siteSearchIndex.index } />
				</div>
			</header>
		) }
	/>
)

export default Header

When following the examples on Github I didn't see any code changes to gatsby-node.js. Was I supposed to update this file to make the search work? Here is my current gatsby-node.js file just in case this may be causing issues:

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

const path = require(`path`)

exports.createPages = ( { graphql, actions } ) => {
	const { createPage } = actions
	const pageTemplate = path.resolve( './src/templates/page.js' )
	const postTemplate = path.resolve( './src/templates/post.js' )
	const cptTemplate = path.resolve( './src/templates/cpt.js' )
	const pagePassword = path.resolve( './src/templates/page-password.js' )

	return graphql(`
		{
			allWordpressPage {
				edges {
					node {
						id
						slug
						wordpress_id
						path
						template
					}
				}
			}
			allWordpressPost {
				edges {
					node {
						id
						slug
						wordpress_id
						path
						template
					}
				}
			}
			allWordpressWpExampleCpt {
				edges {
					node {
						id
						slug
						wordpress_id
						path
						template
					}
				}
			}
		}
	`).then( result => {
		if ( result.errors ) {
			throw result.errors
		}

		const pages = result.data.allWordpressPage.edges

		pages.forEach( page => {
			const template = page.node.template
			if( 'page-password.php' !== template ) {
				createPage( {
					path: `${ page.node.path }`,
					component: pageTemplate,
					context: {
						id: page.node.wordpress_id,
					},
				} )
			} else {
				createPage( {
					path: `${ page.node.path }`,
					component: pagePassword,
					context: {
						id: page.node.wordpress_id,
					},
				} )
			}
		} )

		const posts = result.data.allWordpressPost.edges
		posts.forEach( post => {
			createPage( {
				path: `/blog/${ post.node.slug }`,
				component: postTemplate,
				context: {
					id: post.node.wordpress_id,
				},
			} )
		} )

		const cptPosts = result.data.allWordpressWpExampleCpt.edges
		cptPosts.forEach( post => {
			createPage( {
				path: `/example-cpt/${ post.node.slug }`,
				component: cptTemplate,
				context: {
					id: post.node.wordpress_id,
				},
			} )
		} )
	} )
}

Gatsby v2 Error

Is Gatsby v2 supported?

error UNHANDLED REJECTION


  Error: Cannot use GraphQLScalarType "SiteSearchIndex_Index" from another module or realm.
  Ensure that there is only one instance of "graphql" in the node_modules
  directory. If different versions of "graphql" are the dependencies of other
  relied on modules, use "resolutions" to ensure only one version is installed.
  https://yarnpkg.com/en/docs/selective-version-resolutions
  Duplicate "graphql" modules cannot be used at the same time since different
  versions may have different capabilities and behavior. The data from one
  version used in the function from another could produce confusing and
  spurious results.

  - mergeSchemas.js:92
    [azdanov.github.io]/[graphql-tools]/dist/stitching/mergeSchemas.js:92:31

  - Array.forEach

  - mergeSchemas.js:90
    [azdanov.github.io]/[graphql-tools]/dist/stitching/mergeSchemas.js:90:36

  - Array.forEach

  - mergeSchemas.js:65 mergeSchemasImplementation
    [azdanov.github.io]/[graphql-tools]/dist/stitching/mergeSchemas.js:65:13

  - mergeSchemas.js:26 mergeSchemas
    [azdanov.github.io]/[graphql-tools]/dist/stitching/mergeSchemas.js:26:12

  - index.js:47
    [azdanov.github.io]/[gatsby]/dist/schema/index.js:47:20

  - Generator.next

GraphQLError: String cannot represent an array value: []

When I run gatsby build/develop, everything works fine, but this plugin causes my console to throw GraphQLError: String cannot represent an array value: [] for every single node in my app, for some nodes it posts a wall of the error repeating itself. This doesn't necessarily cause any issues, as I can still use the search once the site is built, but I'd still like to get to the bottom of this if possible, in case it is the cause of another error down the line.

gatsby-config

module.exports = {
  pathPrefix: `/ctc`,
  siteMetadata: {
    title: `Gatsby Default Starter`,
  },
  plugins: [
    {
      resolve: `@andrew-codes/gatsby-plugin-elasticlunr-search`,
      options: {
      // Fields to index
        fields: [
          'title'
        ],
      // 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
          BookJson: {
            title: node => node.title,
            gatsby_slug: node => node.gatsby_slug,
            image: node => node.image
          },
          AuthorJson: {
            title: node => node.title,
            gatsby_slug: node => node.gatsby_slug,
            image: node => node.image
          }
        },
      },
    },
    `gatsby-transformer-json`,
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-sass`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/data/final`
      }
    },
  ],
}

gatsby-node

const path = require(`path`);
const { createFilePath } = require(`gatsby-source-filesystem`)
const slugify = require('slugify')
const request = require('request-promise-native')
const crypto = require('crypto');
const fs = require('fs')

//create pages from OutputJson nodes, using id field as path
exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators
  return new Promise((resolve, reject) => {
    graphql(`
      {
        allGenreJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allClipJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allReadingAgeJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allNarratorJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allSeriesJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allPublisherJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allAuthorJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
              type
            }
          }
        }
        allBookJson {
          edges {
            node {
              slug
              gatsby_slug
              id
              title
            }
          }
        }
      }`
    ).then(result => {
      result.data.allBookJson.edges.forEach(({node}) => {
        createPage({
          path: `${node.gatsby_slug}`,
          component: path.resolve('./src/templates/book.js'),
          context: {
            id: node.id,
            type: node.type,
            title: node.title
          },
        })
      })
      var apiEnds = ['Genre','Author','ReadingAge','Narrator','Series','Publisher']
      apiEnds.forEach((endpoint) => {
        result.data[`all${endpoint}Json`].edges.forEach(({ node}) => {

          createPage({
            path: `${node.gatsby_slug}`,
            component: path.resolve('./src/templates/category.js'),
            context: {
              id: node.id,
              type: node.type,
              title: node.title,
            },
          })
        })
      })
      resolve()
    })
  })
}

siteSearchIndex not show - resolver problem in config

Hey guys,

I am having this problem for a while and I have been checking every issue that is out there, including the one that are exactly the same as mine, but didn't work.

Basically, I am using the gatsby-source-wordpress plugin with elasticlunr. According to the documentation it should be rather easy. But I guess the following error is explaning that the resolver type is incorrect:

 ERROR #11321  PLUGIN

"@gatsby-contrib/gatsby-plugin-elasticlunr-search" threw an error while running the onCreateNode lifecycle:

Cannot read property 'tags' of undefined

  127 |   }
  128 |
> 129 |   if (filter && !filter(node, getNode)) {
      |                  ^
  130 |     return;
  131 |   }
  132 |

File: node_modules/@gatsby-contrib/gatsby-plugin-elasticlunr-search/gatsby-node.js:129:18

I check all the answers and most people who are using the wordpress plugin are doing exactly the same as me.


module.exports = {
  siteMetadata: {
    title: `wp-gatsby template`,
    description: `wp-gatsby template`,
    author: `D19cannon`,
  },
  plugins: [
    `gatsby-plugin-lint-queries`,
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    // Setup WPGraphQL.com to be the source
    {
      resolve: `gatsby-source-graphql`,
      options: {
        // This type will contain remote schema Query type
        typeName: `WPGraphQL`,
        // This is field under which it's accessible
        fieldName: `wpgraphql`,
        // Url to query from
        url: `http://wp.test/graphql`,
      },
    },
    {
      resolve: 'gatsby-source-wordpress',
      options: {
        baseUrl: 'wp.test/',
        // WP.com sites set to true, WP.org set to false
        hostingWPCOM: false,
        protocol: 'http',
        // Use 'Advanced Custom Fields' Wordpress plugin
        useACF: true,
        auth: {},
        // Set to true to debug endpoints on 'gatsby build'
        verboseOutput: true,
      },
    {
      resolve: `@gatsby-contrib/gatsby-plugin-elasticlunr-search`,
      options: {
        // Fields to index
        fields: [`title`],
        // How to resolve each field`s value for a supported node type
        resolvers: {
          wordpress__PAGE: {
            title: node => node.title,
          },
          wordpress__POST: {
            title: node => node.title,
          },
        },
        // Optional filter to limit indexed nodes
        filter: (node, getNode) =>
          node.frontmatter.tags !== 'exempt',
      },
    },
  ],
}

Let me know what the fields are suppose to be other than 'wordpress__POST'
Thanks.

Any way to return all results by default?

I know it's probably something simple, but can't seem to figure it out. At the moment I'm just getting results when someone enters a query, but it would be great if I could show all possible results on page load, and then just have them filtered when someone enters a query.

Error: duplicate "graphql" modules in Gatsby v2

I was trying to configure this plugin in a Gatsby v2 website and received this message:

Ensure that there is only one instance of "graphql" in the node_modules directory.
If different versions of "graphql" are the dependencies of other relied on modules,
use "resolutions" to ensure only one version is installed.

And then...

https://yarnpkg.com/en/docs/selective-version-resolutions

Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.

Error: Cannot use GraphQLObjectType "SitePageConnection" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.

Here is what I did:

  1. Created a new Gatsby website, starting from the official blog v2 template
gatsby new my-blog https://github.com/gatsbyjs/gatsby-starter-blog#v2
  1. Created a Search React component and copy-pasted the code available in
    the Consuming your site section.

  2. Updated gatsby-config.js as explained here.

I'm not sure how to use the selective version resolution. In the documentation they say to add a resolutions field in package.json and then run npm install. This is what I tried (with no luck).

"resolutions": {
    "@andrew-codes/**/graphql": "0.13.0",
    "[email protected]/**/graphql": "0.10.3"
  }

Have I misunderstood how to use this plugin or this behavior is due to changes in Gatsby v2?

Question: How do I limit the search

Currently if I perform a search for "walks around" I get titles with either "walks" or "around" in them. I would like the query to only return titles with both "walks" and "around" in them.

Allow to clear the "stop words" in elasticlunr's index

It appears that searching for "common" words are filtered out with elasticlunr's "stop word" filter. So words like "to", and "but" will not return a result. I would like to be able to clear this one (my use case is searching for component names in a design system documentation site, so words like "tooltip" and "button" don't come up until you type the whole word

Elasticlunr has a method elasticlunr.clearStopWords() -> is it possible to expose that method in the config?

http://elasticlunr.com/docs/stop_word_filter.js.html

LMDB DUPFIXED size error

I have this error :

 ERROR #85901  GRAPHQL

There was an error in your GraphQL query:

MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size

  1 | query SearchIndexQuery {
  2 |   siteSearchIndex {
> 3 |     index
    |     ^
  4 |   }
  5 | }

when i try to resolve 2 nodes with the getNode() function in a single resolver function (gatsby-config.js)

Exemple code:

additionalSearchData: (node, getNode) => {

  const reference = getNode(node.reference___NODE)
  const technologies = getNode(node.technologies___NODE)

  return `${reference.title} ${technologies.map(tech => tech.title).join(' ')}`
}

Having trouble integrating with Wordpress plugin

Hi I am using wordpress as my CMS and query data from it rather than using markdown. Can anyone help me revise my code to make this work? I think most of my problem stems from me not understanding fundamentally how Gatsby node works. I do know however, the siteSearchIndex query is not being generated. How do I properly generate it?

gatsby-node.js

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators;
  if (node.internal.type === `searchStuff`) {
    const slug = node.slug;

    createNodeField({
      node,
      name: `slug`,
      value: slug,
    });

    const template = path.resolve(`./src/templates/single.js`);
    createNodeField({
      node,
      name: `template`,
      value: template,
    });
  }
};

gatsby-config.js

{
      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
              searchStuff: {
                  title: node => node.title,
                  keywords: node => node.acf.keywords,
                },
            },
        },
    },

Getting more info than just title and keywords

I want to enrich my nodes with some extract information that are on the markdown body

---
title: "Sweet Pandas Eating Sweets"
date: "2017-08-10"
---

#Starting
Pandas are really sweet.

##Topic 2
Here's a video of a panda eating sweets.

It's possible to extract Starting and Topic2 headers and add them into my GraphQL so that I can query it?

Installing plugin as a dev dependency on README

Hey, I'm checking out your plugin and see the install instructions are to install it as a dev -D dependency

npm install -D @andrew-codes/gatsby-plugin-elasticlunr-search

In your demo site, the plugin is used as a normal dependency

@andrew-codes/gatsby-plugin-elasticlunr-search plugin has generated no Gatsby nodes.

Hello,

I don't think this is an issue, more just my misunderstanding of how to properly integrate this plugin.

I'm having a miserable time trying to integrate this into a gatsby site that's using the gatsby-source-WordPress plugin.

I'm able to pull all of my Wordpress info, into regular templates, so that's not an issue. It's just whenever I run gatsby develop I receive the " @andrew-codes/gatsby-plugin-elasticlunr-search plugin has generated no Gatsby nodes." warning. Followed by another GraphQL warning, "GraphQL Error Unknown field siteSearchIndex on type RootQueryType."

Clearning or deleting the .cache folder doesn't seem to have any effect.

It's like it's just not creating the siteSearchIndex.

Here's my gatsby-config.js file

module.exports = {
    siteMetadata: {
        title: `RMFA Walking Tour`,
    },
    plugins: [
        `gatsby-plugin-react-helmet`,
        `gatsby-plugin-catch-links`,
        {
            resolve: `gatsby-source-filesystem`,
            options: {
                path: `${__dirname}/src/pages`,
                name: 'pages',
            },
        },
        {
            resolve: "gatsby-source-wordpress",
            options: {
                baseUrl: "rochesternharts.local",
                protocol: "http",
                hostingWPCOM: false,
                useACF: true,
                verboseOutput: false,
                perPage: 100,
                concurrentRequests: 10,
            },
        },
        {
            resolve: `@andrew-codes/gatsby-plugin-elasticlunr-search`,
            options: {
                // Fields to index
                fields: [
                    'id',
                    'title',
                    'artwork_number',
                    'artist_name',
                ],
                // 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
                    artwork: {
                        id: node=> node.id,
                        title: node => node.title,
                        artwork_number: node => node.acf.artwork_number,
                        artist_name: node => node.acf.artist_name,
                    },
                },
            },
        },
    ],
}

and my gatsby-node.js

const _ = require(`lodash`)
const Promise = require(`bluebird`)
const path = require(`path`)
const slash = require(`slash`)

const fs = require('fs');
const { createFilePath } = require(`gatsby-source-filesystem`);

const rootDir = path.resolve(__dirname);

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators;
  if (node.internal.type === `artwork`) {
    const slug = node.slug;

    createNodeField({
      node,
      name: `slug`,
      value: slug,
    });

    const template = path.resolve(`./src/templates/single.js`);
    createNodeField({
      node,
      name: `template`,
      value: template,
    });
  }
};

exports.createPages = ({ graphql, boundActionCreators }) => {
    const { createPage } = boundActionCreators;

    return new Promise((resolve, reject) => {
        graphql(
            `
            {
                allWordpressWpArtwork {
                    edges {
                        node {
                            id
                            title
                            slug
                            acf {
                                artwork_number
                                artist_name
                                artist_bio
                            }
                        }
                    }
                }
            }
            `
        ).then(result => {
            if (result.errors) {
                console.log(result.errors);
                reject(result.errors);
            }
            const template = path.resolve(`./src/templates/single.js`);
            _.each(result.data.allWordpressWpArtwork.edges, edge => {
                createPage({
                    path: `${edge.node.slug}`,
                    component: slash(template),
                    context: {
                        slug: edge.node.slug,
                    },
                });
            });
        });

        resolve();
    });
}

Just for clarification, when I console.log the node.internal.type it returns 'artwork' as that's my Wordpress custom post type name.

I realize that this issue encompasses way more than just the elasticlunr-search plugin. So if it's just too broad an issue, I understand. But if you have any advice, I'd really appreciate it, I've hit a brick wall.

Can't seem to work with gatsby-transformer-json

I would like to search some json files. If I look in the graphql explorer, I can see videosJson and documentsJson and the associated nodes. I get an error about serialisedData is null in the browser though.

Below is the relevant portion of my gatsby-config.js. Is this elasticlunr-search plugin intended to work with non-markdown resolvers like this?

  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/data`,
      },
    },
    `gatsby-transformer-json`,
    {
      resolve: `@gatsby-contrib/gatsby-plugin-elasticlunr-search`,
      options: {
        // Fields to index
        fields: [`title`, `categories`, `description`],
        // 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
          VideosJson: {
            title: node => node.title,
            categories: node => node.categories,
            description: node => node.description,
            path: node =>
              `/videos/${slugify(node.frontmatter.title)}`,
          },
          DocumentsJson: {
            title: node => node.title,
            categories: node => node.categories,
            description: node => node.description,
            type: node => node.type,
            path: node => node.url
          },
        },
      },
    },

This plugin breaks Hot Reloading

Not sure why exactly, but I think it might be because we are calling createNode inside of onCreateNode which might be an infinite loop type situation?

Warnings about multiple equal name modules due to upper and lower case react.

For Example on Windows getting alot of these:

warning in ./~/react/lib/KeyEscapeUtils.js

There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.

warning in ./~/React/lib/KeyEscapeUtils.js

There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.

Mine resolved by changing the component example use lowercase 'react' instead of the proposed 'React':
FROM: import React, {Component} from 'React';
TO: import React, {Component} from 'react';
...
Kind of obvious but just in-case it confused someone else... (I have no idea about react so might be incredibly stupid of me!)

Sporadic GraphQL Error

I'd like to implement this plugin into my site, but most of the times when I run gatsby develop, I get a GraphQL Error.

success delete html files from previous builds — 0.006 s
success open and validate gatsby-config.js — 0.004 s
success copy gatsby files — 0.022 s
success onPreBootstrap — 0.007 s
success source and transform nodes — 0.044 s
success building schema — 0.144 s
success createLayouts — 0.007 s
success createPages — 0.005 s
success createPagesStatefully — 0.014 s
success onPreExtractQueries — 0.001 s
success update schema — 0.092 s
GraphQL Error There was an error while compiling your site's GraphQL queries.
  Invariant Violation: GraphQLParser: Unknown field `siteSearchIndex` on type `RootQueryType`. Source: document `SearchIndexExampleQuery` file: `GraphQL request`.
    
success extract queries from components — 0.118 s
success run graphql queries — 0.013 s
success write out page data — 0.003 s
success write out redirect data — 0.001 s
success onPostBootstrap — 0.001 s

info bootstrap finished - 1.908 s

Here is my gatsby configuration:

module.exports = {
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-catch-links`,
    `gatsby-plugin-styled-components`,
    `gatsby-plugin-sass`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography.js`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/pages/posts`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              classPrefix: "language-",
            },
          },
        ],
      },
    },
    {
      resolve: `@andrew-codes/gatsby-plugin-elasticlunr-search`,
      options: {
        fields: [
          'title',
          'tags',
        ],
        resolvers: {
          MarkdownRemark: {
            title: node => node.frontmatter.title,
            tags: node => node.frontmatter.tags,
          },
        },
      },
    },
  ],
};

It seems it doesn't matter in which order the plugins are listed. 90% of the time, I get the error, sometimes it works.
Could this be a timing problem?

Thanks!

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.