[英]Postgres and Word Clouds
我想知道是否可以創建一個 Postgres 函數來掃描一些表行並創建一個包含WORD
和AMOUNT
(頻率)的表? 我的目標是使用這個表來創建一個詞雲。
有一種簡單的方法,但它可能很慢(取決於您的表大小)。 您可以將文本拆分為一個數組:
SELECT string_to_array(lower(words), ' ') FROM table;
使用這些數組,您可以使用unnest
來聚合它們:
WITH words AS (
SELECT unnest(string_to_array(lower(words), ' ')) AS word
FROM table
)
SELECT word, count(*) FROM words
GROUP BY word;
這是一種簡單的方法,但存在一些問題,例如,它僅按空格而不是標點符號來分割單詞。
其他可能更好的選擇是使用PostgreSQL 全文搜索。
遲到了,但我也需要這個,想使用全文搜索。
這可以方便地刪除 html 標簽。
所以基本上你將文本轉換為tsvector
然后使用ts_stat
:
select word, nentry
from ts_stat($q$
select to_tsvector('simple', '<div id="main">a b c <b>b c</b></div>')
$q$)
order by nentry desc
結果:
|word|nentry|
|----|------|
|c |2 |
|b |2 |
|a |1 |
但這不能很好地擴展,所以這是我最終的結果:
設置:
-- table with a gist index on the tsvector column
create table wordcloud_data (
html text not null,
tsv tsvector not null
);
create index on wordcloud_data using gist (tsv);
-- trigger to update the tsvector column
create trigger wordcloud_data_tsvupdate
before insert or update on wordcloud_data
for each row execute function tsvector_update_trigger(tsv, 'pg_catalog.simple', html);
-- a view for the wordcloud
create view wordcloud as select word, nentry from ts_stat('select tsv from wordcloud_data') order by nentry desc;
用法:
-- insert some data
insert into wordcloud_data (html) values
('<div id="id1">aaa</div> <b>bbb</b> <i attribute="ignored">ccc</i>'),
('<div class="class1"><span>bbb</span> <strong>ccc</strong> <pre>ddd</pre></div>');
之后,您的wordcloud
視圖應如下所示:
|word|nentry|
|----|------|
|ccc |2 |
|bbb |2 |
|ddd |1 |
|aaa |1 |
獎金特點:
將simple
替換為例如english
,postgres 將去除停用詞並為您進行詞干提取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.