↑↓ 选择↵ 打开⌫ 切换范围完整搜索

PG.CENTER 连接 PostgreSQL 文档、百科与生态知识。由 Pigsty 维护。

支持中的版本: 当前版本 (18) / 17 / 16 / 15 / 14
开发中的版本: 19 / 20devel
已结束支持的版本: 13 / 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3
历史版本。 PostgreSQL 8.3 已结束支持。 请参阅 当前版本手册.

F.9. fuzzystrmatch — 确定字符串的相似性和距离 #

fuzzystrmatch模块提供多个函数,用于确定字符串的相似性和距离。

F.9.1. Soundex

Soundex 系统是一种通过将发音相近的名字转换为相同代码来进行匹配的方法。它最初在 1880 年、1900 年和 1910 年的美国人口普查中使用。注意,Soundex 对非英语名字并不是很有用。

fuzzystrmatch模块提供两个用于处理 Soundex 代码的函数:

   soundex(text) returns text
   difference(text, text) returns int
  

soundex函数将字符串转换为其 Soundex 代码。difference函数将两个字符串转换为各自的 Soundex 代码,然后返回代码中相同位置上匹配的个数。由于 Soundex 代码有四个字符,因此结果范围为 0 到 4,其中 0 表示没有匹配,4 表示完全匹配。(因此,这个函数的命名并不贴切,similarity 会是更好的名字。)

下面是一些用法示例:

SELECT soundex('hello world!');

SELECT soundex('Anne'), soundex('Ann'), difference('Anne', 'Ann');
SELECT soundex('Anne'), soundex('Andrew'), difference('Anne', 'Andrew');
SELECT soundex('Anne'), soundex('Margaret'), difference('Anne', 'Margaret');

CREATE TABLE s (nm text);

INSERT INTO s VALUES ('john');
INSERT INTO s VALUES ('joan');
INSERT INTO s VALUES ('wobbly');
INSERT INTO s VALUES ('jack');

SELECT * FROM s WHERE soundex(nm) = soundex('john');

SELECT * FROM s WHERE difference(s.nm, 'john') > 2;
  

F.9.2. Levenshtein

该函数计算两个字符串之间的 Levenshtein 距离:

   levenshtein(text source, text target) returns int
  

source 和 target 可以是任何非空字符串,最大长度为 255 个字符。

示例:

test=# SELECT levenshtein('GUMBO', 'GAMBOL');
 levenshtein
-------------
            2
(1 row)
  

F.9.3. Metaphone

Metaphone 与 Soundex 一样,基于为输入字符串构造一个代表性代码的思想。如果两个字符串具有相同的代码,则认为它们相似。

该函数计算输入字符串的 Metaphone 代码:

   metaphone(text source, int max_output_length) returns text
  

source 必须是非空字符串,最大长度为 255 字节。max_output_length 设置输出 Metaphone 代码的最大长度;如果超过该长度,输出会被截断为该长度。

示例:

test=# SELECT metaphone('GUMBO', 4);
 metaphone
-----------
 KM
(1 row)
  

F.9.4. Double Metaphone

Double Metaphone 系统会为给定输入字符串计算两个“近音”代码,即一个“主”代码和一个“备选”代码。在大多数情况下,它们相同,但尤其对于非英语名字,这两个代码可能会因发音不同而略有差异。这些函数分别计算主代码和备选代码:

   dmetaphone(text source) returns text
   dmetaphone_alt(text source) returns text
  

输入字符串没有长度限制。

示例:

test=# select dmetaphone('gumbo');
 dmetaphone
------------
 KMP
(1 row)
  

报告文档问题

阅读 上游文档. 反馈更正前请先核对 当前版本手册.