flexsearch tutorial

We are going to build a small example to see how it works.

Andres Canavesi
Nov 10, 2021
featured image

What is flexsearch

flexsearch It's a module available through npm or yarn to index in-memory data. With this module, you will be able to search or display related data on your site. We are going to build a small example to see how it works.

How to install flexsearch

Like any other Node.js module, install it like this:
yarn add flexsearch
npm install flexsearch

How to use flexsearch

Just create an index.js file to see how it works.
const { Index } = require("flexsearch");

const options = {
    charset: "latin:extra",
    preset: 'match',
    tokenize: 'strict',
    cache: false
const index = new Index(options);

// my collection
const recipes = [
    {id:1, title: 'Orange cake'},
    {id:2, title: 'New York-Style Bacon Egg and Cheese Sandwich'},
    {id:3, title: 'Bacon Wrapped Cheese Stuffed Meatloaf'},
    {id:4, title: 'French Yogurt Cake'},
    {id:5, title: 'Gougeres (French Cheese Puffs)'},
    {id:6, title: 'Authentic Brazilian Cheese Bread (Pão de Queijo)'},
    {id:7, title: 'Camarão na Moranga (Brazilian Shrimp Stuffed Pumpkin)'},
    {id:8, title: 'Parmesan Cheese Muffins'},
    {id:9, title: 'Cookie Dough Stuffed Oreos'},

// index my collection
recipes.forEach((recipe) =>{
    index.add(recipe.id, recipe.title)

// search (it will return an array of ids)
const ids = index.search('Cookie', 5);
// based on the ids returned by the index, look for the recipes for those ids
const result = recipes.filter((recipe) => ids.includes(recipe.id));


Execution output

[ 9, 1, 4, 6 ]
  { id: 1, title: 'Orange cake' },
  { id: 4, title: 'French Yogurt Cake' },
  { id: 6, title: 'Authentic Brazilian Cheese Bread (Pão de Queijo)' },
  { id: 9, title: 'Cookie Dough Stuffed Oreos' }


Photo by Artem Beliaikin on Unsplash

nodejs flexsearch javascript dev