flexsearch example

A super simple example to show how to index a collection of data and then run a full-text search

Andres Canavesi
Sep 09, 2021
flexsearch It's an awesome package to index in-memory data
featured image

About flexsearch package

flexsearch It's an awesome package to index in-memory data. You can use it to implement justa. search box in your site or to show related data with the content you are displaying

How to install it

yarn add flexsearch
npm install flexsearch


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 Daniel Lerman on Unsplash