gpt4 book ai didi

sql - 从 tsvector 中检索词素出现的位置和数量

转载 作者:行者123 更新时间:2023-11-29 11:24:45 25 4
gpt4 key购买 nike

有什么方法可以从 tsvector 中获取有关词位在句子中的位置和出现次数的信息吗?

像这样

SELECT *
FROM get_position(to_tsvector('english', 'The Fat Rats'), to_tsquery('Rats'));

将返回 3

SELECT *
FROM get_occurrences(to_tsvector('english', 'The Fat Rats'), to_tsquery('Rats'));

将返回 1。

最佳答案

tsvector 的文本表示包含特定词位出现的列表:

test=# select to_tsvector ( 'english', 'new bar in New York' );
to_tsvector
----------------------------
'bar':2 'new':1,4 'york':5

下面是依赖它的示例函数。它接受文本参数并在内部将它们转换为 ts_vector,但可以很容易地重写以接受 ts_vector。

CREATE OR REPLACE FUNCTION lexeme_occurrences (
IN _document text
, IN _word text
, IN _config regconfig
, OUT lexeme_count int
, OUT lexeme_positions int[]
) RETURNS RECORD
AS $$
DECLARE
_lexemes tsvector := to_tsvector ( _config, _document );
_searched_lexeme tsvector := strip ( to_tsvector ( _config, _word ) );
_occurences_pattern text := _searched_lexeme::text || ':([0-9,]+)';
_occurences_list text := substring ( _lexemes::text, _occurences_pattern );
BEGIN
SELECT
count ( a )
, array_agg ( a::int )
FROM regexp_split_to_table ( _occurences_list, ',' ) a
WHERE _searched_lexeme::text != '' -- preventing false positives
INTO
lexeme_count
, lexeme_positions;
RETURN;
END $$ LANGUAGE plpgsql;

示例用法:

select * from lexeme_occurrences ( 'The Fat Rats', 'rat', 'english' );
lexeme_count | lexeme_positions
--------------+-----------------
1 | {3}
(1 row)

关于sql - 从 tsvector 中检索词素出现的位置和数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com