1

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'

Jonatanbs
  • 223
  • 2
  • 9
  • Please improve the question if you want anyone to be able to help. I am guessing that you mean "Full-text search" for MySQL – Pablo Palacios Aug 09 '21 at 16:19

2 Answers2

3

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).

Rob Sutcliffe
  • 321
  • 1
  • 14
1

I am guessing that you mean "Full-text search" for MySQL. So, I will give it a try.

There will probably be two ways if doing this or something similar.

You can harness the power of Strapi filters contains, ncontains, containss and ncontainss will do a similar thing to full-text search. Yes, it's not exactly full test search, but it will do most cases.

i.e: enter image description here

enter image description here

Ref: https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#filters

And I haven't really deeply tested this one, but it might work. You can make a controller endpoint and inside the controller use Knex to build a complex query and request a full-text response.

i.e:

const result = await knex('users')
            .orWhereRaw('MATCH(firstname_preferred,lastname_preferred,username) AGAINST(? IN BOOLEAN MODE)', params.search)
            .limit(lim)

Ref: https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#knex https://gist.github.com/cameronblandford/808ca0f66acffb8b50b4e3704d6063a1

Pablo Palacios
  • 2,767
  • 20
  • 37