Code With Wolf


Javascript Flexsearch Tutorial with Node JS

Javascript Flexsearch Tutorial with Node JS

A few months ago, I wrote one of my more popular blog posts, Flexsearch Tutorial with React.

In that post, I mention a little bit about how Flexsearch works and why to use it.

Flexsearch's documentation goes into much more detail and shows all of the options they offer for search capability.

What I like about Flexsearch is it's capability matched with the focus on performance.

However, you are probably here because you have already decided to use Flexsearch but don't know how the heck to set it up, so I'll save the evangelizing and just show you how to do that.

I noticed that a lot of people will not be using Flexsearch with just React JS or a front end library, so I wanted to put together a very simple tutorial for How to use Flexsearch with Node JS as this is a more likely use-case.

import { Index } from "flexsearch";

//  Create the search index variable
const index = new Index({});

function setupSearchIndex() {
  //  Add the data to the search index
  const data = {
    1: { id: 1, title: "React" },
    2: { id: 2, title: "React.js" },
    3: { id: 3, title: "ReactJS" },
    4: { id: 4, title: "Node" },
    5: { id: 5, title: "Node.js" },
    6: { id: 6, title: "NodeJS" }
  };

  Object.values(data).forEach((item) => {
    index[item.id] = item.title;
  });
}

function search(query) {
  setupSearchIndex();
  const results = index.search(query);
  console.log(results);
}

This is a very basic setup to get you started.

Yes, I'm using a global variable for the search index. I don't recommend this for your application so scope accordingly.

Hopefully you can use this script to base your search implementation off of.

Now, running the search function and passing in your search term as the query parameter will yield your search results.

Calling search('react') will return [{ id: 1, title: "React" },{ id: 2, title: "React.js" },{ id: 3, title: "ReactJS" }]



© 2022 Code With Wolf