Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similarity function in Postgres with pg_trgm

Tags:

I'm trying to use the similarity function in Postgres to do some fuzzy text matching, however whenever I try to use it I get the error:

function similarity(character varying, unknown) does not exist 

If I add explicit casts to text I get the error:

function similarity(text, text) does not exist 

My query is:

SELECT (similarity("table"."field"::text, %s::text)) AS "similarity", "table".* FROM "table" WHERE similarity > .5 ORDER BY "similarity" DESC LIMIT 10 

Do I need to do something to initalize pg_trgm?

like image 878
Alex Gaynor Avatar asked Feb 12 '10 20:02

Alex Gaynor


People also ask

How does pg_ trgm work?

pg_trgm ignores non-word characters (non-alphanumerics) when extracting trigrams from a string. Each word is considered to have two spaces prefixed and one space suffixed when determining the set of trigrams contained in the string.

What is gin index in postgresql?

GIN stands for Generalized Inverted Index. GIN is designed for handling cases where the items to be indexed are composite values, and the queries to be handled by the index need to search for element values that appear within the composite items.

What is Btree_gist?

btree_gist provides GiST index operator classes that implement B-tree equivalent behavior for the data types int2 , int4 , int8 , float4 , float8 , numeric , timestamp with time zone , timestamp without time zone , time with time zone , time without time zone , date , interval , oid , money , char , varchar , text , ...


2 Answers

With postgresql 9.1:

after installing (on ubuntu) sudo apt-get install postgresql-contrib as tomaszbak answered.

you just have to execute the sql command:

CREATE EXTENSION pg_trgm; 
like image 101
morja Avatar answered Sep 18 '22 09:09

morja


You have to install pg_trgm. In debian, source this sql: /usr/share/postgresql/8.4/contrib/pg_trgm.sql. From the command line:

psql -f /usr/share/postgresql/8.4/contrib/pg_trgm.sql 

Or inside a psql shell:

\i /usr/share/postgresql/8.4/contrib/pg_trgm.sql 

The script defaults to installing in the public schema, edit the search path at the top if you want to install it somewhere else (so that uninstalling/upgrading can be done simply by dropping the schema).

like image 27
Tobu Avatar answered Sep 20 '22 09:09

Tobu