首页 > 解决方案 > 从文本值中提取特定单词

问题描述

我有一个查询和一个返回值,如下所示:

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 文本字段进行切片吗?

标签: postgresqlsplit

解决方案


要“按字符位置切片”,您可以简单地使用以下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;

推荐阅读