← 中文资源

简体中文版本

levenshtein 拼写容错排序

用户把 postgresql 拼错也能命中:fuzzystrmatch 的 levenshtein 算编辑距离,按距离升序取前三,最近的排在最前。

阅读英文原文

实现说明

语句实际拼装出的结构:ORDER BY 固定了输出顺序;LIMIT 限制返回行数。

常见问题

这段 SQL 涉及哪些关系?

引用的是 products。

核心语句

SELECT product_id,
       name,
       levenshtein(lower(name), 'postgreql') AS edit_distance
FROM products
ORDER BY edit_distance
LIMIT 3;
INSERT INTO products (product_id, name) VALUES
    (1, 'postgresql'),
    (2, 'postgis'),
    (3, 'pgbackrest'),
    (4, 'patroni');
CREATE TABLE products (
    product_id int PRIMARY KEY,
    name       text NOT NULL
);

代码示例

-- fuzzystrmatch's levenshtein: rank mistyped input by edit distance
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;

CREATE TABLE products (
    product_id int PRIMARY KEY,
    name       text NOT NULL
);

INSERT INTO products (product_id, name) VALUES
    (1, 'postgresql'),
    (2, 'postgis'),
    (3, 'pgbackrest'),
    (4, 'patroni');

-- the user typed 'postgreql': ascending levenshtein distance puts the closest match first
SELECT product_id,
       name,
       levenshtein(lower(name), 'postgreql') AS edit_distance
FROM products
ORDER BY edit_distance
LIMIT 3;