PostgreSQL 全文检索 - 词频统计

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云原生数据库 PolarDB 分布式版,标准版 2核8GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

标签

PostgreSQL , 全文检索 , 词频统计 , ts_stat , madlib


背景

TF(Term Frequency 词频)/IDF(Inverse Document Frequency 逆向文本频率)是文本分析中常见的术语。

《PostgreSQL结合余弦、线性相关算法 在文本、图片、数组相似 等领域的应用 - 1 文本(关键词)分析理论基础 - TF(Term Frequency 词频)/IDF(Inverse Document Frequency 逆向文本频率)》

PostgreSQL支持全文检索,支持tsvector文本向量类型。

如何在一堆文本中,找到热词,或者对词频进行分析呢?

方法1,ts_stat

第一种方法来自PostgreSQL的内置函数,ts_stat,用于生成lexeme的统计信息,例如我想知道某个问答知识库中,出现最多的词是哪个,出现在了多少篇文本中。

ts_stat介绍如下

https://www.postgresql.org/docs/devel/static/functions-textsearch.html

https://www.postgresql.org/docs/devel/static/textsearch.html

https://www.postgresql.org/docs/devel/static/textsearch-features.html

12.4.4. Gathering Document Statistics

The function ts_stat is useful for checking your configuration and for finding stop-word candidates.

ts_stat(sqlquery text, [ weights text, ]  
        OUT word text, OUT ndoc integer,  
        OUT nentry integer) returns setof record  

sqlquery is a text value containing an SQL query which must return a single tsvector column. ts_stat executes the query and returns statistics about each distinct lexeme (word) contained in the tsvector data. The columns returned are

  • word text — the value of a lexeme

  • ndoc integer — number of documents (tsvectors) the word occurred in

  • nentry integer — total number of occurrences of the word

If weights is supplied, only occurrences having one of those weights are counted.

For example, to find the ten most frequent words in a document collection:

SELECT * FROM ts_stat('SELECT vector FROM apod')  
ORDER BY nentry DESC, ndoc DESC, word  
LIMIT 10;  

The same, but counting only word occurrences with weight A or B:

SELECT * FROM ts_stat('SELECT vector FROM apod', 'ab')  
ORDER BY nentry DESC, ndoc DESC, word  
LIMIT 10;  

测试

1、创建生成随机字符串的函数

create or replace function gen_rand_str(int) returns text as $$    
  select substring(md5(random()::text), 4, $1);    
$$ language sql strict stable;    

2、创建生成若干个随机词的函数

create or replace function gen_rand_tsvector(int,int) returns tsvector as $$    
  select array_to_tsvector(array_agg(gen_rand_str($1))) from generate_series(1,$2);    
$$ language sql strict;   
postgres=# select gen_rand_tsvector(4,10);  
                           gen_rand_tsvector                             
-----------------------------------------------------------------------  
 '21eb' '2c9c' '4406' '5d9c' '9ac4' 'a27b' 'ab13' 'ba77' 'e3f2' 'f198'  
(1 row)  

3、创建测试表,并写入测试数据

postgres=# create table ts_test(id int, info tsvector);  
CREATE TABLE  
postgres=# insert into ts_test select generate_series(1,100000), gen_rand_tsvector(4,10);  
INSERT 0 100000  

4、查看词频,总共出现了多少次,在多少篇文本(多少条记录中出现过)

postgres=# SELECT * FROM ts_stat('SELECT info FROM ts_test')  
ORDER BY nentry DESC, ndoc DESC, word  
LIMIT 10;  
 word | ndoc | nentry   
------+------+--------  
 e4e6 |   39 |     39  
 9596 |   36 |     36  
 a84c |   35 |     35  
 2b44 |   32 |     32  
 5146 |   32 |     32  
 92f6 |   32 |     32  
 cd56 |   32 |     32  
 fd00 |   32 |     32  
 4258 |   31 |     31  
 5f18 |   31 |     31  
(10 rows)  

5、再写入一批测试数据,查看词频,总共出现了多少次,在多少篇文本(多少条记录中出现过)

postgres=# insert into ts_test select generate_series(1,100000), gen_rand_tsvector(2,10);  
INSERT 0 100000  
postgres=# SELECT * FROM ts_stat('SELECT info FROM ts_test')                               
ORDER BY nentry DESC, ndoc DESC, word  
LIMIT 10;  
 word | ndoc | nentry   
------+------+--------  
 30   | 4020 |   4020  
 a7   | 4005 |   4005  
 20   | 3985 |   3985  
 c5   | 3980 |   3980  
 e6   | 3970 |   3970  
 f1   | 3965 |   3965  
 70   | 3948 |   3948  
 5e   | 3943 |   3943  
 e4   | 3937 |   3937  
 2b   | 3934 |   3934  
(10 rows)  

方法2,madlib

实际上MADlib也提供了词频统计的训练函数

http://madlib.apache.org/docs/latest/group__grp__text__utilities.html

Term frequency

Term frequency tf(t,d) is to the raw frequency of a word/term in a document, i.e. the number of times that word/term t occurs in document d. For this function, 'word' and 'term' are used interchangeably. Note: the term frequency is not normalized by the document length.

    term_frequency(input_table,  
                   doc_id_col,  
                   word_col,  
                   output_table,  
                   compute_vocab)  

Arguments:

input_table

TEXT. The name of the table storing the documents. Each row is in the form <doc_id, word_vector> where doc_id is an id, unique to each document, and word_vector is a text array containing the words in the document. The word_vector should contain multiple entries of a word if the document contains multiple occurrence of that word.

id_col

TEXT. The name of the column containing the document id.

word_col

TEXT. The name of the column containing the vector of words/terms in the document. This column should of type that can be cast to TEXT[].

output_table

TEXT. The name of the table to store the term frequency output. The output table contains the following columns:

  • id_col: This the document id column (same as the one provided as input).

  • word: A word/term present in a document. This is either the original word present in word_col or an id representing the word (depending on the value of compute_vocab below).

  • count: The number of times this word is found in the document.

compute_vocab

BOOLEAN. (Optional, Default=FALSE) Flag to indicate if a vocabulary is to be created. If TRUE, an additional output table is created containing the vocabulary of all words, with an id assigned to each word. The table is called output_table_vocabulary (suffix added to the output_table name) and contains the following columns:

  • wordid: An id assignment for each word

  • word: The word/term

参考

《PostgreSQL结合余弦、线性相关算法 在文本、图片、数组相似 等领域的应用 - 1 文本(关键词)分析理论基础 - TF(Term Frequency 词频)/IDF(Inverse Document Frequency 逆向文本频率)》

《一张图看懂MADlib能干什么》

http://madlib.apache.org/docs/latest/group__grp__text__utilities.html

https://www.postgresql.org/docs/devel/static/functions-textsearch.html

https://www.postgresql.org/docs/devel/static/textsearch.html

https://www.postgresql.org/docs/devel/static/textsearch-features.html

http://madlib.incubator.apache.org/

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
相关文章
|
Web App开发 关系型数据库 数据库
用PostgreSQL 做实时高效 搜索引擎 - 全文检索、模糊查询、正则查询、相似查询、ADHOC查询
用PostgreSQL 做实时高效 搜索引擎 - 全文检索、模糊查询、正则查询、相似查询、ADHOC查询作者digoal 日期2017-12-05 标签PostgreSQL , 搜索引擎 , GIN , ranking , high light , 全文检索 , 模糊查询 , 正则查询 , 相似查询 , ADHOC查询 背景字符串搜索是非常常见的业务需求,它包括: 1、前缀+模糊查询。
10240 1
|
9月前
|
存储 SQL 自然语言处理
如何使用AnalyticDB PostgreSQL 版实现“一站式全文检索”业务
本文从阿里云用户使用云原生数据仓库AnalyticDB PostgreSQL版(以下简称ADB PG)的实际体验出发,介绍ADB PG如何实现“一站式全文检索”业务,并详细阐述ADB PG使用的优势技术,最后提供对应业务案例分析。
32152 33
|
存储 关系型数据库 Linux
centos7 postgresql10 安装 zhparser,配置中文全文检索
centos7 postgresql10 安装 zhparser,配置中文全文检索
227 0
centos7 postgresql10 安装 zhparser,配置中文全文检索
|
存储 SQL 人工智能
4 PostgreSQL 索引,全文检索,模糊匹配,近似度匹配(三)
4 PostgreSQL 索引,全文检索,模糊匹配,近似度匹配(三)
888 1
4 PostgreSQL 索引,全文检索,模糊匹配,近似度匹配(三)
|
自然语言处理 关系型数据库 PostgreSQL
PostgreSQL中文全文检索
一 安装必备软件 1.1 安装SCWS 下载scws:http://www.xunsearch.com/scws/down/scws-1.2.2.tar.
2443 0
|
自然语言处理 算法 关系型数据库
PostgreSQL的全文检索插件zhparser的中文分词效果
PostgreSQL支持全文检索,其内置的缺省的分词解析器采用空格分词。因为中文的词语之间没有空格分割,所以这种方法并不适用于中文。要支持中文的全文检索需要额外的中文分词插件。网上查了下,可以给PG用的开源中文分词插件有两个:nlpbamboo和zhparser。
2305 0

相关产品

  • 云原生数据库 PolarDB