Build a search index with Lunr in Hugo
Table of contents
Hugo can emit a custom output format: a search.json file with every page.
The client downloads the index once and then queries
lunr
locally.
The index template
// build the index from the rendered pages
const index = lunr(function () {
this.ref("uri");
this.field("title");
this.field("content");
for (const doc of request.response) {
this.add(doc);
lookup[doc.uri] = doc;
}
return 200;
});Note: the index is rebuilt on every build. With a few hundred posts the file stays under 200 KB.1
Results are rendered from a <template> cloned per match, with the same summary
truncation Hugo itself uses.
Measured on this site’s own
search.jsonat ~70 posts; size grows roughly linearly with the number of indexed fields, not just post count. ↩︎
Written by a human
Reference this post
Please reference this post with a link to this page. I prefer to be called Dev Person (they/them) or the CyberLavandaTea demo.
Comments
Reply with a Webmention or a reply on the Fediverse.