如何在PostgreSQL的ts_vector中拆分驼峰式字符串?
解决方案
问题出在PostgreSQL的simple分词器不会自动拆分驼峰命名的字符串——它只会将输入转为小写并移除停用词,所以logDescription被当作了一个完整的词元。要实现你要的拆分效果,可以分两种情况处理:
情况1:不需要保留词元的大小写
如果可以接受词元全小写,用正则先拆分驼峰再调用to_tsvector即可:
SELECT to_tsvector('simple', regexp_replace('logDescription', '([a-z])([A-Z])', '\1 \2', 'g'));
执行后输出:
to_tsvector ------------------------ 'description':2 'log':1
情况2:需要保留词元的大小写(如你示例中的Description)
因为simple分词器会强制将词元转为小写,所以需要手动构造tsvector:
SELECT string_agg(format('''%s'':1', word), ' ')::tsvector FROM unnest(string_to_array(regexp_replace('logDescription', '([a-z])([A-Z])', '\1 \2', 'g'), ' ')) AS word;
执行后输出:
tsvector ------------------------- 'Description':1 'log':1
代码解释
regexp_replace(...):通过正则匹配小写字母后跟大写字母的位置,插入空格,将logDescription拆分为log Descriptionstring_to_array(...):将拆分后的字符串转为数组unnest:将数组展开为单行记录format(...):将每个词格式化为'词元':1的tsvector元素格式string_agg(...):将所有元素拼接为完整的tsvector字符串,再强制转换为tsvector类型
内容的提问来源于stack exchange,提问作者Chinnmay B S
相关产品推荐
相关产品推荐

