为文本搜索添加去除重音的功能
我想在文本搜索中加入 unaccent 扩展。
配置:
create extension if not exists unaccent;
drop text search configuration if exists portugues_sem_acento;
create text search configuration portugues_sem_acento (copy = portuguese);
alter text search configuration portugues_sem_acento
alter mapping for numhword, word, asciiword, numword
with unaccent, portuguese_stem;
alter database cpn set default_text_search_config to 'portugues_sem_acento';
我希望对 cacao 的搜索在 cação 时返回 true。
select
to_tsvector('Cação')
, to_tsquery('cacao')
, to_tsvector('Cação') @@ to_tsquery('cacao')
;
输出:
to_tsvector | to_tsquery | ?column?
-------------+------------+----------
'cação':1 | 'cacao' | f
(1 row)
我还缺少什么?
解决方案
使用
ALTER DATABASE和ALTER ROLE设置的值仅在启动一个全新的数据库会话时生效。
你已经修改了 default_text_search_config 设置在数据库范围内的默认值,但要让它对当前会话(包括你的会话)生效,你需要重新连接。你可以在会话内不重新连接的情况下改变当前值,使用常规的 set:
db<>fiddle上的演示
alter database postgres set default_text_search_config to 'portugues_sem_acento';
select current_setting('default_text_search_config',false)
, to_tsvector('Cação')
, to_tsquery('cacao')
, to_tsvector('Cação') @@ to_tsquery('cacao') as "@@";
| current_setting | to_tsvector | to_tsquery | @@ |
|---|---|---|---|
| pg_catalog.simple | 'cação':1 | 'cacao' | False |
set default_text_search_config to 'portugues_sem_acento';
select current_setting('default_text_search_config',false)
, to_tsvector('Cação')
, to_tsquery('cacao')
, to_tsvector('Cação') @@ to_tsquery('cacao') as "@@";
| current_setting | to_tsvector | to_tsquery | @@ |
|---|---|---|---|
| public.portugues_sem_acento | 'caca':1 | 'caca' | True |
select*from ts_debug('portugues_sem_acento', 'Cação');
| alias | description | token | dictionaries | dictionary | lexemes |
|---|---|---|---|---|---|
| word | Word, all letters | Cação | {unaccent,portuguese_stem} | unaccent | {Cacao} |
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。