/searchable-trigrams

A simple trigrams search, implementing spatie/searchable. Laravel was excluded from Searchable to be able to use it with Lumen framework

Primary LanguagePHP

Searchable Triagrams

This package get super powers from "spatie/searchable" and includes a custom search using trigrams, this feature it's provided from postgresql for this reason you must enable it from psql using the command:

CREATE EXTENSION pg_trgm;

Trigrams are formed by breaking a string into groups of three consecutive letters. For example, the string "hello" would be represented by the following set of trigrams:

" h", " he", "hel", "ell", "llo", "lo "

Installation


You can install the package via composer:

composer require delarocha/searchable-trigrams

Preparing your models


For a better performance in your searches include a migration file indexing all fields will you use to your searches in the following way.

public function up()
{
   DB::statement('CREATE INDEX users_name_trigram ON users USING GIST(name  gist_trgm_ops);');      
}
public function down()
{
    DB::statement('DROP INDEX IF EXISTS users_name_trigram');
}

Usage


Searchable trigrams is basically a custom search aspect to "spatie/searchable" for this reason, go to their github repository to read general instructions.

Searching models

With the models prepared you can search them like this:

use Searchable\Fuzzy\Search;

$searchResults = (new Search())
   ->registerSearchMethod(User::class, 'name')
   ->search('john');

You can include an extra parameter to specify you are using your search as autocomplete

use Searchable\Fuzzy\Search;

$searchResults = (new Search())
   ->registerSearchMethod(User::class, 'name', true)
   ->search('john');