Ошибка функция similarity character varying unknown не существует

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?

asked Feb 12, 2010 at 20:44

Alex Gaynor's user avatar

Alex GaynorAlex Gaynor

14.3k9 gold badges63 silver badges113 bronze badges

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;

answered May 14, 2013 at 20:50

morja's user avatar

2

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

answered Feb 12, 2010 at 20:54

Tobu's user avatar

TobuTobu

24.6k4 gold badges91 silver badges98 bronze badges

1

On ubuntu you need to run

sudo apt-get install postgresql-contrib

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

answered Oct 27, 2011 at 13:32

tomaszbak's user avatar

tomaszbaktomaszbak

8,2374 gold badges44 silver badges37 bronze badges

1

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

answered Jul 12, 2014 at 9:55

Kolyunya's user avatar

KolyunyaKolyunya

5,9447 gold badges45 silver badges81 bronze badges

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

answered Nov 6, 2014 at 12:18

Haris Krajina's user avatar

Haris KrajinaHaris Krajina

14.7k12 gold badges64 silver badges81 bronze badges

I was having this same issue in the context of running the Django Test Runner against a function that uses the Django 1.11 ORM for trigram similarity on Postgres 9.4.

I had to do a few things to get it working:

1) OP is correct that this required enabling the pg_trgm extension. However, in postgres9.4 this is enabled on a per-database basis. Since Django deletes and recreates the test database with each run, the new test database didn’t have the extension installed. To fix this, I initialized the pg_trgm extension within the default newly-created database template in postgres. The command to do this is psql -d template1 -c 'CREATE EXTENSION pg_trgm;' run as the postgres user.

2) Postgres had to be restarted

3) The Django test runner wasn’t recognizing this, so I had to upgrade from Django 1.11.12 to 1.11.18 (presumably this is also fixed in newer versions of Django)

answered Jan 24, 2019 at 18:16

Robert Townley's user avatar

Robert TownleyRobert Townley

3,4043 gold badges28 silver badges53 bronze badges

in case others are struggling too: assuming that the db is called “ttrss” I switched to the command line of postgresql:

sudo -u postgres psql --dbname=ttrss

then install the extension there:

CREATE EXTENSION pg_trgm;

answered Sep 29, 2021 at 8:03

Rex Honey's user avatar

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?

asked Feb 12, 2010 at 20:44

Alex Gaynor's user avatar

Alex GaynorAlex Gaynor

14.3k9 gold badges63 silver badges113 bronze badges

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;

answered May 14, 2013 at 20:50

morja's user avatar

2

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

answered Feb 12, 2010 at 20:54

Tobu's user avatar

TobuTobu

24.6k4 gold badges91 silver badges98 bronze badges

1

On ubuntu you need to run

sudo apt-get install postgresql-contrib

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

answered Oct 27, 2011 at 13:32

tomaszbak's user avatar

tomaszbaktomaszbak

8,2374 gold badges44 silver badges37 bronze badges

1

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

answered Jul 12, 2014 at 9:55

Kolyunya's user avatar

KolyunyaKolyunya

5,9447 gold badges45 silver badges81 bronze badges

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

answered Nov 6, 2014 at 12:18

Haris Krajina's user avatar

Haris KrajinaHaris Krajina

14.7k12 gold badges64 silver badges81 bronze badges

I was having this same issue in the context of running the Django Test Runner against a function that uses the Django 1.11 ORM for trigram similarity on Postgres 9.4.

I had to do a few things to get it working:

1) OP is correct that this required enabling the pg_trgm extension. However, in postgres9.4 this is enabled on a per-database basis. Since Django deletes and recreates the test database with each run, the new test database didn’t have the extension installed. To fix this, I initialized the pg_trgm extension within the default newly-created database template in postgres. The command to do this is psql -d template1 -c 'CREATE EXTENSION pg_trgm;' run as the postgres user.

2) Postgres had to be restarted

3) The Django test runner wasn’t recognizing this, so I had to upgrade from Django 1.11.12 to 1.11.18 (presumably this is also fixed in newer versions of Django)

answered Jan 24, 2019 at 18:16

Robert Townley's user avatar

Robert TownleyRobert Townley

3,4043 gold badges28 silver badges53 bronze badges

in case others are struggling too: assuming that the db is called “ttrss” I switched to the command line of postgresql:

sudo -u postgres psql --dbname=ttrss

then install the extension there:

CREATE EXTENSION pg_trgm;

answered Sep 29, 2021 at 8:03

Rex Honey's user avatar

Вопрос:

Я пытаюсь использовать функцию подобия в Postgres для выполнения нечеткого соответствия текста, однако всякий раз, когда я пытаюсь его использовать, я получаю ошибку:

function similarity(character varying, unknown) does not exist

Если я добавляю явные приведения к тексту, я получаю ошибку:

function similarity(text, text) does not exist

Мой запрос:

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

Мне нужно что-то сделать, чтобы инициализировать pg_trgm?

Лучший ответ:

Вам нужно установить pg_trgm. В debian, введите этот sql: /usr/share/postgresql/8.4/contrib/pg_trgm.sql. Из командной строки:

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

Или внутри оболочки psql:

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

script по умолчанию устанавливается в общедоступную схему, отредактируйте путь поиска вверху, если вы хотите установить его где-то в другом месте (чтобы удаление/обновление можно было просто удалить из схемы).

Ответ №1

С postgresql 9.1:

после установки (на ubuntu) sudo apt-get install postgresql-contrib как ответил tomaszbak.

вам просто нужно выполнить команду sql:

CREATE EXTENSION pg_trgm;

Ответ №2

На ubuntu вам нужно запустить

sudo apt-get install postgresql-contrib

чтобы получить/usr/share/postgresql/8.4/contrib/pg_trgm.sql

Ответ №3

Если у вас установлено расширение pg_trgm не в схеме public, вы должны явно указать схему при использовании функции similarity, подобной этой

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

Ответ №4

Для Postgres 8.4 выполните следующие действия:

Как работает пользователь sudo:

sudo apt-get install postgresql-contrib-8.4

Переключиться на пользователя postgres:

sudo su - postgres

Run:

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

Перезапуск postgres

Ответ №5

У меня возникла такая же проблема в контексте запуска Django Test Runner для функции, которая использует ORM Django 1.11 для сходства триграмм в Postgres 9.4.

Я должен был сделать несколько вещей, чтобы это заработало:

1) OP правильно, что для этого необходимо включить расширение pg_trgm. Однако в postgres9.4 это включено для каждой -d атабазы. Поскольку Django удаляет и воссоздает тестовую базу данных при каждом запуске, в новой тестовой базе данных расширение не установлено. Чтобы это исправить, я инициализировал расширение pg_trgm в новом шаблоне базы данных -c по умолчанию в postgres. Команда для этого – psql -d template1 -c 'CREATE EXTENSION pg_trgm;' запустить как пользователь postgres.

2) Postgres пришлось перезапустить

3) Тестер Django не распознал это, поэтому мне пришлось обновить его с 1.11.12 до 1.11.18 (возможно, это также исправлено в более новых версиях Django)

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?

asked Feb 12, 2010 at 20:44

Alex Gaynor's user avatar

Alex GaynorAlex Gaynor

14.1k9 gold badges62 silver badges111 bronze badges

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;

answered May 14, 2013 at 20:50

morja's user avatar

2

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

answered Feb 12, 2010 at 20:54

Tobu's user avatar

TobuTobu

24.4k4 gold badges92 silver badges98 bronze badges

1

On ubuntu you need to run

sudo apt-get install postgresql-contrib

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

answered Oct 27, 2011 at 13:32

tomaszbak's user avatar

tomaszbaktomaszbak

8,1774 gold badges43 silver badges37 bronze badges

1

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

answered Jul 12, 2014 at 9:55

Kolyunya's user avatar

KolyunyaKolyunya

5,8607 gold badges44 silver badges80 bronze badges

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

answered Nov 6, 2014 at 12:18

Haris Krajina's user avatar

Haris KrajinaHaris Krajina

14.5k12 gold badges62 silver badges79 bronze badges

I was having this same issue in the context of running the Django Test Runner against a function that uses the Django 1.11 ORM for trigram similarity on Postgres 9.4.

I had to do a few things to get it working:

1) OP is correct that this required enabling the pg_trgm extension. However, in postgres9.4 this is enabled on a per-database basis. Since Django deletes and recreates the test database with each run, the new test database didn’t have the extension installed. To fix this, I initialized the pg_trgm extension within the default newly-created database template in postgres. The command to do this is psql -d template1 -c 'CREATE EXTENSION pg_trgm;' run as the postgres user.

2) Postgres had to be restarted

3) The Django test runner wasn’t recognizing this, so I had to upgrade from Django 1.11.12 to 1.11.18 (presumably this is also fixed in newer versions of Django)

answered Jan 24, 2019 at 18:16

Robert Townley's user avatar

Robert TownleyRobert Townley

3,3443 gold badges28 silver badges51 bronze badges

in case others are struggling too: assuming that the db is called “ttrss” I switched to the command line of postgresql:

sudo -u postgres psql --dbname=ttrss

then install the extension there:

CREATE EXTENSION pg_trgm;

answered Sep 29, 2021 at 8:03

Rex Honey's user avatar

Вопрос:

Я пытаюсь использовать функцию подобия в Postgres для выполнения нечеткого соответствия текста, однако всякий раз, когда я пытаюсь его использовать, я получаю ошибку:

function similarity(character varying, unknown) does not exist

Если я добавляю явные приведения к тексту, я получаю ошибку:

function similarity(text, text) does not exist

Мой запрос:

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

Мне нужно что-то сделать, чтобы инициализировать pg_trgm?

Лучший ответ:

Вам нужно установить pg_trgm. В debian, введите этот sql: /usr/share/postgresql/8.4/contrib/pg_trgm.sql. Из командной строки:

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

Или внутри оболочки psql:

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

script по умолчанию устанавливается в общедоступную схему, отредактируйте путь поиска вверху, если вы хотите установить его где-то в другом месте (чтобы удаление/обновление можно было просто удалить из схемы).

Ответ №1

С postgresql 9.1:

после установки (на ubuntu) sudo apt-get install postgresql-contrib как ответил tomaszbak.

вам просто нужно выполнить команду sql:

CREATE EXTENSION pg_trgm;

Ответ №2

На ubuntu вам нужно запустить

sudo apt-get install postgresql-contrib

чтобы получить/usr/share/postgresql/8.4/contrib/pg_trgm.sql

Ответ №3

Если у вас установлено расширение pg_trgm не в схеме public, вы должны явно указать схему при использовании функции similarity, подобной этой

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

Ответ №4

Для Postgres 8.4 выполните следующие действия:

Как работает пользователь sudo:

sudo apt-get install postgresql-contrib-8.4

Переключиться на пользователя postgres:

sudo su - postgres

Run:

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

Перезапуск postgres

Ответ №5

У меня возникла такая же проблема в контексте запуска Django Test Runner для функции, которая использует ORM Django 1.11 для сходства триграмм в Postgres 9.4.

Я должен был сделать несколько вещей, чтобы это заработало:

1) OP правильно, что для этого необходимо включить расширение pg_trgm. Однако в postgres9.4 это включено для каждой -d атабазы. Поскольку Django удаляет и воссоздает тестовую базу данных при каждом запуске, в новой тестовой базе данных расширение не установлено. Чтобы это исправить, я инициализировал расширение pg_trgm в новом шаблоне базы данных -c по умолчанию в postgres. Команда для этого – psql -d template1 -c 'CREATE EXTENSION pg_trgm;' запустить как пользователь postgres.

2) Postgres пришлось перезапустить

3) Тестер Django не распознал это, поэтому мне пришлось обновить его с 1.11.12 до 1.11.18 (возможно, это также исправлено в более новых версиях Django)

@murdoch

Running bundle exec rake textacular:install_trigram RAILS_ENV=test installs the trigram module in my DB, but my cucumber features fail with the following message:

    PG::Error: ERROR:  function similarity(character varying, unknown) does not exist
    LINE 1: SELECT "projects".*, similarity("projects"."name", '24') AS ...

    HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

I’ve got trigram installed, and everything works fine in development. My tests used to pass up until yesterday. The thing that triggered this appears to be me running my rspec specs, and then switching to cucumber.

    Gemfile:
    gem 'textacular', :git => "git://github.com/textacular/textacular.git"

I have the most recent changes from master. I’ve run the rake task and it is successful.

@jeremyruppel

Is cucumber a new addition to this project? IIRC, cucumber runs in it’s own RAILS_ENV by default. Can you try bundle exec rake textacular:install_trigram RAILS_ENV=cucumber and report back?

@murdoch

@jeremyruppel thanks for your advice. Cucumber is not a new addition to the app, and I get the same error after running bundle exec rake textacular:install_trigram RAILS_ENV=cucumber.

If I run the textacular rake task twice in succession, then I see a message about trigram already being installed, but if I run the rake task straight after running my features, then I am informed that trigram was successfully installed.

@benhamill

Yeah. So… how are you running your tests? IIRC, running rake spec runs… rake db:setup or similar before running the tests. Or at least used to. It may be that Cucumber’s rake task does something similar. That would blow away the DB and then rebuild it from your schema. Unless you’ve got trigram in your schema, you’ll lose it when that happens.

So: Does this stop when you run the tests without using rake (like rspec spec/ and whatever’s the equivalent for Cucumber)? If so, then you’ll want to look at dumping your schema as SQL, rather than Ruby.

@jeremyruppel

Yeah agreed. There should be no reason to need to invoke the trigram rake task before test runs. The extension should already be there after db:test:prepare if the extension is in your SQL structure dump.

Was the trigram extension installed in your project in a migration or manually via our rake task?

Sent from my iPhone

On Jul 2, 2013, at 8:04 AM, Ben Hamill notifications@github.com wrote:

Yeah. So… how are you running your tests? IIRC, running rake spec runs… rake db:setup or similar before running the tests. Or at least used to. It may be that Cucumber’s rake task does something similar. That would blow away the DB and then rebuild it from your schema. Unless you’ve got trigram in your schema, you’ll lose it when that happens.

So: Does this stop when you run the tests without using rake (like rspec spec/ and whatever’s the equivalent for Cucumber)? If so, then you’ll want to look at dumping your schema as SQL, rather than Ruby.


Reply to this email directly or view it on GitHub.

@murdoch

@benhamill and @jeremyruppel thanks so much, you fixed it! Running cucumber and rspec on their own without rake work fine. I had no idea rake ran db:setup! That’s good to know. You saved me lots of time with this.

Я реализовал полнотекстовый поиск в своем приложении django с помощью postgresql. Но когда я нажимаю кнопку поиска, я получаю сообщение об ошибке:

ProgrammingError at /blog/search/
function similarity(character varying, unknown) does not exist
LINE 1: SELECT COUNT(*) FROM (SELECT SIMILARITY("blog_post"."title",...
                                     ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

Я не знаю, где ошибка, поэтому, если вам понадобятся какие-либо файлы, я отредактирую этот вопрос. Помогите мне, пожалуйста

1 ответ

Лучший ответ

Полагаю, вы забыли установить pg_trgm расширение. Чтобы установить его с помощью django, создайте файл с именем pg_trgm.py внутри каталога migrations вашего приложения:

from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('myapp', <last migration filename here>),
    ]
    operations = [
        migrations.RunSQL('CREATE EXTENSION IF NOT EXISTS pg_trgm'),
    ]

Не забудьте заменить <last migration filename here> именем файла последней миграции.


3

Elrond Supports Monica
8 Дек 2020 в 23:48

Я пытаюсь использовать функцию подобия в Postgres для сопоставления нечеткого текста, однако всякий раз, когда я пытаюсь ее использовать, я получаю сообщение об ошибке:

function similarity(character varying, unknown) does not exist

Если я добавлю к тексту явное приведение, я получаю сообщение об ошибке:

function similarity(text, text) does not exist

Мой запрос:

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

Мне нужно что-то сделать для инициализации pg_trgm?

6 ответы

Вам необходимо установить pg_trgm. В debian загрузите этот sql: /usr/share/postgresql/8.4/contrib/pg_trgm.sql. Из командной строки:

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

Или внутри оболочки psql:

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

По умолчанию сценарий устанавливается в общедоступной схеме, отредактируйте путь поиска вверху, если вы хотите установить его где-нибудь еще (чтобы удаление / обновление можно было выполнить, просто отбросив схему).

Создан 12 фев.

С postgresql 9.1:

после установки (на убунту) sudo apt-get install postgresql-contrib как ответил Томашбак.

вам просто нужно выполнить команду sql:

CREATE EXTENSION pg_trgm;

ответ дан 14 мая ’13, 22:05

На ubuntu нужно запустить

sudo apt-get install postgresql-contrib

чтобы получить /usr/share/postgresql/8.4/contrib/pg_trgm.sql

ответ дан 27 окт ’11, 14:10

Если у вас есть pg_trgm расширение установлено не в public schema вы должны явно указать схему при использовании similarity функционировать как это

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

Создан 12 июля ’14, 10:07

Для Postgres 8.4 сделать следующее:

Как пользователь sudo запускается:

sudo apt-get install postgresql-contrib-8.4

Переключитесь на пользователя postgres:

sudo su - postgres

Run:

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

Перезапустить postgres

Создан 06 ноя.

У меня была такая же проблема в контексте запуска Django Test Runner против функции, которая использует ORM Django 1.11 для схожести триграммы в Postgres 9.4.

Мне пришлось сделать несколько вещей, чтобы он заработал:

1) OP правильно, что для этого требовалось включение pg_trgm расширение. Однако в postgres9.4 это включено для каждой базы данных. Поскольку Django удаляет и воссоздает тестовую базу данных при каждом запуске, в новой тестовой базе данных не было установлено расширение. Чтобы исправить это, я инициализировал pg_trgm в недавно созданном шаблоне базы данных по умолчанию в postgres. Команда для этого: psql -d template1 -c 'CREATE EXTENSION pg_trgm;' бежать как postgres пользователь.

2) Postgres пришлось перезапустить

3) Средство выполнения тестов Django не распознало это, поэтому мне пришлось обновиться с Django 1.11.12 до 1.11.18 (предположительно, это также исправлено в более новых версиях Django)

Создан 24 янв.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

sql
postgresql
fuzzy-search

or задайте свой вопрос.

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?


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

ПОДСКАЗКА: ни одна функция не соответствует заданному имени и типам аргументов. Возможно, вам потребуется добавить явное приведение типов. ТриграммаПодобие Django

Я пытаюсь выполнить полнотекстовый поиск с помощью TrigramSimilarity. Я активировал расширение pg_trgm в PostgreSQL. и добавил django.contrib.postgres в мои установленные приложения. Но когда я пытаюсь запросить

blog.objects.annotate(similarity=TrigramSimilarity('name', 'abc'),).filter(similarity__gt=0.3).order_by('-similarity')

Но это дает мне ошибку

psycopg2.ProgrammingError: function similarity(character varying, unknown) does not exist
LINE 1: …others_2″, «blog_mod», SIMILARITY…
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

Почему возникает эта ошибка. Помогите, пожалуйста.


Abhimanyu, 19 октября 2018 г., 01:03

3

5 287

5


Ответы:

Решено

Ошибка указывает на то, что расширение не установлено. Я не знаю точно, почему это могло быть. Возможно, вы не установили расширение в базу данных, которую используете для django?

Можно выполнять необработанные запросы sql из вашего кода django. Это гарантирует, что вы выберете правильную базу данных / схему.

from django.db import connection
with connection.cursor() as cursor:
    cursor.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm')

Вы также можете использовать пользовательскую миграцию Django TrigramExtension. Запрос на создание расширения такой же. Но миграция — хорошая идея, если вы запускаете интеграционные тесты в тестовой базе данных, для которой также требуется включить pg_trgm.

Https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/operations/#database-migration-operations


Håken, 19 октября 2018 г., 02:36

У меня такая же проблема. Это произошло бы, если бы вы не включили схему, в которой будет использоваться TrigramSimilarity(), в путь поиска перед установкой этого расширения.

Пытаться

SET search_path TO my_schema

Потом

CREATE EXTENSION IF NOT EXISTS pg_trgm;

Szymon, 22 мая 2020 г., 05:41

Я предполагаю, что вы, вероятно, не подключились к правильной БД.

В Ubuntu. Пытаться…

$ sudo su postgres

$ psql <db_name>
   <db_name> = Name of DB being used by the Django project.
   e.g psql badass_db

$ CREATE EXTENSION pg_trgm;

Magere, 11 июля 2020 г., 20:47

Если расширение pg_trgm было создано в общедоступной схеме, вы можете получить ошибку в другой схеме. Это работает для меня:

select public.similarity('foo','bar');

Тогда как если я попробую решение Szymon, Postgres сообщит мне, что расширение уже существует. Я не нашел документации по этому поводу.


David, 9 октября 2020 г., 04:39

Это потому, что (я не знаю почему?) TrigramSimilarity не работает с search_query. вместо этого он будет работать со строками. или ни то, ни другое с SearchVectorField вместо этого используйте обычные поля.


Mahdi, 20 декабря 2020 г., 15:15

Интересные вопросы для изучения

@murdoch

Running bundle exec rake textacular:install_trigram RAILS_ENV=test installs the trigram module in my DB, but my cucumber features fail with the following message:

    PG::Error: ERROR:  function similarity(character varying, unknown) does not exist
    LINE 1: SELECT "projects".*, similarity("projects"."name", '24') AS ...

    HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

I’ve got trigram installed, and everything works fine in development. My tests used to pass up until yesterday. The thing that triggered this appears to be me running my rspec specs, and then switching to cucumber.

    Gemfile:
    gem 'textacular', :git => "git://github.com/textacular/textacular.git"

I have the most recent changes from master. I’ve run the rake task and it is successful.

@jeremyruppel

Is cucumber a new addition to this project? IIRC, cucumber runs in it’s own RAILS_ENV by default. Can you try bundle exec rake textacular:install_trigram RAILS_ENV=cucumber and report back?

@murdoch

@jeremyruppel thanks for your advice. Cucumber is not a new addition to the app, and I get the same error after running bundle exec rake textacular:install_trigram RAILS_ENV=cucumber.

If I run the textacular rake task twice in succession, then I see a message about trigram already being installed, but if I run the rake task straight after running my features, then I am informed that trigram was successfully installed.

@benhamill

Yeah. So… how are you running your tests? IIRC, running rake spec runs… rake db:setup or similar before running the tests. Or at least used to. It may be that Cucumber’s rake task does something similar. That would blow away the DB and then rebuild it from your schema. Unless you’ve got trigram in your schema, you’ll lose it when that happens.

So: Does this stop when you run the tests without using rake (like rspec spec/ and whatever’s the equivalent for Cucumber)? If so, then you’ll want to look at dumping your schema as SQL, rather than Ruby.

@jeremyruppel

Yeah agreed. There should be no reason to need to invoke the trigram rake task before test runs. The extension should already be there after db:test:prepare if the extension is in your SQL structure dump.

Was the trigram extension installed in your project in a migration or manually via our rake task?

Sent from my iPhone

On Jul 2, 2013, at 8:04 AM, Ben Hamill notifications@github.com wrote:

Yeah. So… how are you running your tests? IIRC, running rake spec runs… rake db:setup or similar before running the tests. Or at least used to. It may be that Cucumber’s rake task does something similar. That would blow away the DB and then rebuild it from your schema. Unless you’ve got trigram in your schema, you’ll lose it when that happens.

So: Does this stop when you run the tests without using rake (like rspec spec/ and whatever’s the equivalent for Cucumber)? If so, then you’ll want to look at dumping your schema as SQL, rather than Ruby.


Reply to this email directly or view it on GitHub.

@murdoch

@benhamill and @jeremyruppel thanks so much, you fixed it! Running cucumber and rspec on their own without rake work fine. I had no idea rake ran db:setup! That’s good to know. You saved me lots of time with this.

Возможно, вам также будет интересно:

  • Ошибка функционального контроля секрет нет
  • Ошибка функциональности ошибочная структура xml 1с мобильное приложение
  • Ошибка функционального контроля sns
  • Ошибка функциональности 3d secure повторите перевод альфа банк
  • Ошибка фотошопа kernel32 dll

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии