Search code examples
mysqlstrapifuzzy-search

How to implement Fuzzy search in strapi cms


Any ideas on how to implement fuzzy search in strapi (with mysql)?

Example: when i search for 'tvs ad' i would like to get the entry with name of 'tv syd'


Solution

  • You could create a custom controller in Strapi and include a fuzzy search library like fuse.js

    If you need help creating a custom controller or connecting it to an end point see this page in the docs

    This is a simple controller to do a fuzzy search on a table called films and searching the title and synopsis fields with a search term

    'use strict';
    const Fuse = require('fuse.js');
    
    module.exports = {
      async fuzzySearch(ctx) {
        
        const searchTerm = ctx.query._search;
        
        const allFilms = await strapi.services.films.find();
        
        const fuse = new Fuse(allFilms, {
          keys:["title", "synopsis"]
        });
        
        const searchedFilms = fuse.search(searchTerm);
        
        return searchedFilms;
      }
    }

    For a large database table you'd need to write a custom mysql query. But I found this solution works great if you have less than a few thousand entries because fuze gives you loads of options for querying multiple fields and weighting fields differently (i.e. making the film title more important than the synopsis).