PostgreSQL:子字符串匹配的Levenshtein数字

问题描述

问题:我正在提取长描述字段中带有“ posthole”一词的行。这些通常是拼写错误的。我使用Levenshtein函数创建了一个字段,以计算描述和术语“ posthole”之间的差异,但它与整个字符串匹配。我需要找到一种方法修改它,以计算到最接近术语“ posthole”的字符串的子字符串的距离

解决方案:我唯一能想到的就是将字符串分成空格上的子字符串,并将每个子字符串与搜索词匹配。我只是想检查是否有人知道这样做的更好方法

目前这是纯Postgresql,但是如果有处理此问题的模块,我可以将一些Python代码插入数据库中。

解决方法

您可以将字符串拆分成单词,作为行:

with inputs (id,textcol) as (
  values (1,'this is a test of postole and some other posthole expressions'),(2,'just another posthole entry')
)
select id,word,levenshtein(upper(word),'POSTHOLE') 
  from inputs
       cross join lateral regexp_split_to_table(textcol,'\y') r(word) 
 where length(word) > 5
   and levenshtein(upper(word),'POSTHOLE') < 4
;

┌────┬──────────┬─────────────┐
│ id │   word   │ levenshtein │
├────┼──────────┼─────────────┤
│  1 │ postole  │           1 │
│  1 │ posthole │           0 │
│  2 │ posthole │           0 │
└────┴──────────┴─────────────┘
(3 rows)