Skip to content

Instantly share code, notes, and snippets.

@nepsilon
Last active December 13, 2023 14:16
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nepsilon/383bb294234579048bba to your computer and use it in GitHub Desktop.
Save nepsilon/383bb294234579048bba to your computer and use it in GitHub Desktop.
PostgreSQL: Native fuzzy search with levenshtein() — First published in fullweb.io issue #41

PostgreSQL: Fuzzy search with levenshtein()

Ever wanted to implement a “Did you mean?” feature in your search results? Google is said to have greatly increased its user engagement with it. Here is how to implement it simply in Postgres (v9.1+):

Install the extension:

CREATE EXTENSION fuzzystrmatch;

Test the function:

SELECT levenshtein('GUMBO', 'GAMBOL');
 levenshtein
-------------
      2
                  

Build your query:

Here only asking the top 5 close matches:

SELECT word
FROM my_table
WHERE levenshtein(word, "user query") <= 3
ORDER BY levenshtein(word, "user query")
LIMIT 5;

BONUS: Use levenshtein_less_equal() for faster lookup:

SELECT levenshtein_less_equal('extensive', 'exhaustive',2);
 levenshtein_less_equal
------------------------
           3
                  
@TheXHeli
Copy link

you have to install first the extension 'fuzzystrmatch'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment