postgresql - 从文本值中提取特定单词
问题描述
我有一个查询和一个返回值,如下所示:
select properties->>'text' as snippet from table where id = 31;
snippet
-----------------------------------
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.
(1 row)
根据我的查询,这将按我的预期返回。
例如,有没有一种方法可以将返回的文本切片以仅返回从位置 5 到位置 8 的单词?或者,按字符位置切片,我可以将其用作解决方法?
我试过使用:
select properties->>'text'[0:13] as snippet from table where id = 31;
我希望会回来:
There are many
但它没有奏效。
这可能是对 jsonb 文本字段进行切片吗?
解决方案
要“按字符位置切片”,您可以简单地使用以下substr()
功能:
select substr(properties->>'text', 1, 15) as snippet
from the_table
where id = 31;
如果你真的想要“单词”,你可以使用 eg 将文本拆分成一个数组regexp_split_to_array
。一旦你有了一个数组,你就可以使用切片语法:
select (regexp_split_to_array(properties->>'text','\s+'))[5:8] as snippet
from the_table
where id = 31;
这将返回一个数组,如果你想要它作为一个字符串,你可以使用array_to_string()
select array_to_string((regexp_split_to_array(properties->>'text','\s+'))[5:8],' ') as snippet
from the_table
where id = 31;
如果您经常需要它,我会将它包装成一个函数:
create function extract_words(p_input text, p_start int, p_end int)
returns text
as
$$
select array_to_string((regexp_split_to_array(p_input,'\s+'))[p_start:p_end],' ');
$$
language sql
immutable;
然后查询更容易阅读:
select extract_words(properties->>'text', 5, 8) as snippet
from the_table
where id = 31;
推荐阅读
- discord.js - 获取此错误代码:“(节点:25096)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性'通道'”
- android - 我的 Android 应用程序覆盖了 Lyft 应用程序?
- jquery - 如何从可能被修改的链接打开模式
- c++ - 如何更改 cmake 中的默认 CMAKE_INSTALL_PREFIX?
- c# - 使用鼠标位置 Unity 3D 在画布上绘制线条
- ionic-framework - Ionic 4:如何从脚本中更新或刷新离子选择?
- xml - XML 表格列在行内垂直堆叠
- groovy - 尝试在 Jenkinsfile 中全局设置通道和消息环境变量,但不确定两种方法中哪一种最好
- phpmailer - PHPmail-联系表格没有收到邮件并且没有错误
- google-chrome - 你能在 Chrome Devtools Element Inspector 中隐藏#shadowroot 吗?