Svelte Full Text Search - flexsearch

"flexsearch" is a JavaScript library for fast, flexible, and robust search and indexing. It provides a high-performance search engine that is optimized for search and indexing, and can be used in both client-side and server-side applications. It supports a range of features including full-text search, fuzzy search, query highlighting, and auto-suggestions. Here's how to implement it into a Svelte project.


1npm install flexsearch

Importing into your project

flexsearch has three types of indexes:

Most of you probably need just one of them according to your scenario. To import via the npm package you will need to import just the single index you want below is an example of Index and Document being imported into a project:

1import Document from "flexsearch/src/document";
2import Index from "flexsearch/src/index";

NOTE: if you are importing into Svelte you will need to edit the package.json of the module and add "type": "module" or Svelte will not allow it to be imported

Using it in Svelte

Adding the documents

new Document will create a flexsearch document index that allows you to add your documents to the index. It takes a document descriptor which contains a document object with the index field being the key of the object you want indexed.

1let findDocument = new Document({
2  document: {
3    index: ["title", "description", "content"],
4  },
6for (let i = 0; i <; i++) {
7  findDocument.add(docs[i]);

Search functions

To search the document index use the index you created, in this case, findDocument. Use the .search function and pass your search query to the function. This will return an object with the keys being the same as the index field of the document you passed upon initiation. The keys will contain arrays of the ids of the documents that match the search query. Here I am flattening the object into an array of IDs and then filtering them using svelte in the {#each } loop only if there is a search query.

1let search = "";
2let results = [];
3function findDocuments() {
4  results = findDocument
5    .search(search)
6    .map((e) => e.result)
7    .flat();

Svelte elements

 2 type="search"
 3 id="search"
 4 placeholder="Search"
 5 bind:value={search}
 6 on:keydown={findDocuments}
 9// Filter the documents if the search term is not blank
10{#each docs as doc}
11 {#if search == '' || results.indexOf( != -1}
12  // Search Results
13 {/if}