从文本值中提取特定单词

时间:2021-01-04 11:12:09

标签: postgresql split

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

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 文本字段吗?

1 个答案:

答案 0 :(得分:1)

要“按字符位置切片”,只需使用 substr() 函数:

select substr(properties->>'text', 1, 15) as snippet 
from the_table 
where id = 31;

如果你真的想要“单词”,你可以使用例如将文本分割成一个数组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;
相关问题