Similarity function in Postgres with pg_trgm

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

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?

回答1:

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



回答2:

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; 


回答3:

On ubuntu you need to run

sudo apt-get install postgresql-contrib 

to get /usr/share/postgresql/8.4/contrib/pg_trgm.sql



回答4:

If you have the pg_trgm extension installed not in the public schema you must explicitly specify the schema when using the similarity function like this

select schema.similarity(foo,bar) from schema.baz 


回答5:

For Postgres 8.4 do following:

As sudo user run:

sudo apt-get install postgresql-contrib-8.4

Switch to postgres user:

sudo su - postgres

Run:

psql -U DB_USER -d DB_NAME -f /usr/share/postgresql/8.4/contrib/pg_trgm.sql

Restart postgres



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!