如何在Postgresql中查询带标点符号的单词?

Lan*_*ard 7 sql postgresql search

如果我有这样的字符串/短语存储在数据库中:

  • 什么是Q型操作?
  • 程序员指南
  • ABC的编码

有没有一种方法来传递的查询参数在像"Programmers""abc""q-type"并找到它"Programmer's","A.B.C""Q-type"

int*_*tgr 6

的tsvector

使用tsvector类型,它是PostgreSQL文本搜索功能的一部分.

postgres> select 'What are Q-type Operations?'::tsvector;
              tsvector               
-------------------------------------
 'Operations?' 'Q-type' 'What' 'are'
(1 row)
Run Code Online (Sandbox Code Playgroud)

您也可以在tsvector上使用熟悉的运算符:

postgres> select 'What are Q-type Operations?'::tsvector
postgres>        || 'A.B.C''s of Coding'::tsvector;
                           ?column?                           
--------------------------------------------------------------
 'A.B.C''s' 'Coding' 'Operations?' 'Q-type' 'What' 'are' 'of'
Run Code Online (Sandbox Code Playgroud)

从tsvector文档:

tsvector值是不同词汇的排序列表,这些词汇已被规范化以合并相同单词的不同变体(有关详细信息,请参阅第12章).在输入期间自动完成排序和重复消除

如果您还想进行特定于语言的规范化,例如删除常用词('the','a'等)和乘法,请使用该to_tsvector函数.它还为不同的单词分配权重以进行文本搜索:

postgres> select to_tsvector('english',
postgres> 'What are Q-type Operations? A.B.C''s of Coding');
                      to_tsvector                       
--------------------------------------------------------
 'a.b.c':7 'code':10 'oper':6 'q':4 'q-type':3 'type':5
(1 row)
Run Code Online (Sandbox Code Playgroud)

全面的文本搜索

显然,对查询中的每一行执行此操作都会很昂贵 - 因此您应该将tsvector存储在单独的列中并使用ts_query()来搜索它.这也允许您在tsvector上创建GiST索引.

postgres> insert into text (phrase, tsvec)
postgres>   values('What are Q-type Operations?',
postgres>   to_tsvector('english', 'What are Q-type Operations?'));
INSERT 0 1
Run Code Online (Sandbox Code Playgroud)

使用tsquery和@@运算符进行搜索:

postgres> select phrase from text where tsvec @@ to_tsquery('q-type');
           phrase            
-----------------------------
 What are Q-type Operations?
(1 row)
Run Code Online (Sandbox Code Playgroud)