Universal Search #3 Hexo Local Search

This is the 3rd article in a series that covers the steps to add searching to Ghost, Hexo or any general website using APIs provided by various services.

The latest version of Universal Search is available on Github at https://github.com/artchen/universal-search.

We have covered UI and common logics in the first article. This time we are going to explore Hexo local search. If you website is not generated by Hexo, you don’t necessarily need to read this article.

Basic Idea

Static site generator like Hexo does not rely on any database. Instead they pre-generate all pages and save them as individual html files. If we want to add search ability without using 3rd-party services, we will have to generate the "database" ourselves. In this case, the "database" is a index file that contains essential information of pages and posts. When the user submit a search request, the front-end javascript will download this index file, and searching for relevant items.

Generate Index File

There are several Hexo generators that does this for us. I use hexo-generator-json-content by alexbruno for this project.

To install this plugin, first navigate to your Hexo directory, then

npm install --save hexo-generator-json-content

Then edit the global _config.yml, add the following configuration:

jsonContent:
  meta: false
  keywords: false # (english, spanish, polish, german, french, italian, dutch, russian, portuguese, swedish)
  pages:
    title: true
    slug: false
    date: false
    updated: false
    comments: false
    path: true
    link: false
    permalink: true
    excerpt: false
    keywords: false
    text: false
    raw: false
    content: true
  posts:
    title: true
    slug: false
    date: false
    updated: false
    comments: false
    path: true
    link: false
    permalink: true
    excerpt: false
    keywords: false
    text: false
    raw: false
    content: true
    categories: false
    tags: false

The plugin should be good to go. From now on, every time hexo generate is executed, a content.json file will be generated in the public directory.

Build the class

This section is more of a development note. Plugin users don’t have to read it.

The class for Hexo local search is similar to the one we created for Google Custom Search Engine except this time we need a contentSearch(post, queryText) function to manually account for the keyword searching.

I adopted this searching algorithm from http://hahack.com/codes/local-search-engine-for-hexo/. It was pretty simple and clean.

https://gist.github.com/artchen/dd07cb1552e0335cdda6c9f692cbca13.js

Enable your search

Initialize an instance of the HexoSearch class:

var customSearch = new HexoSearch({
  endpoint: "<path-to-your-content.json>" # optional
});