トップ 最新

かってきままな日々

2024-11-05 (Tu) [長年日記]

_ PGroonga

yay -S groonga

mecab もインストールされる。groonga がインストールされるけど、バージョンがちと古いので、 PKGBUILD を編集して新しくした。

yay -S pgroonga
sudo su -
su -l postgres -c "initdb --locale=C.UTF-8 --encoding=UTF8 -D '/var/lib/postgres/data'"
sudo systemctl start postgresql.service
su - postgres
psql -c 'CREATE DATABASE pgroonga_test'
psql -d pgroonga_test -c 'CREATE EXTENSION pgroonga'
[postgres@luna ~]$ psql -d pgroonga_test
psql (16.3)
Type "help" for help.

pgroonga_test=# \d
Did not find any relations.
pgroonga_test=# create table memos (
pgroonga_test(# id integer,
pgroonga_test(# content text
pgroonga_test(# );
CREATE TABLE
pgroonga_test=# 
CREATE INDEX pgroonga_content_index ON memos USING pgroonga (content);
INSERT INTO memos VALUES (1, 'PostgreSQLはリレーショナル・データベース管理システムです。');
INSERT INTO memos VALUES (2, 'Groongaは日本語対応の高速な全文検索エンジンです。');
INSERT INTO memos VALUES (3, 'PGroongaはインデックスとしてGroongaを使うためのPostgreSQLの拡張機能です。');
INSERT INTO memos VALUES (4, 'groongaコマンドがあります。');
SET enable_seqscan = off;
pgroonga_test=# select * from memos where content &@~ 'groonga コマンド';
 id |           content           
----+-----------------------------
  4 | groongaコマンドがあります。
(1 row)

おー簡単だった。

select * from memos where content &@~ 'groonga コマン';

これでも同じ結果だったので、mecab を使ってるわけじゃなさそう。

どのくらいのスピードが出るんだろう。

20万通のメールを突っ込んでみた。

sudo su - postgres
psql
create database pgrep;
psql -d pgrep
CREATE EXTENSION pgroonga;
GRANT ALL ON DATABASE pgrep TO masm;
GRANT ALL ON SCHEMA public TO masm;
exit
psql -U masm pgrep
create table mails (
  path varchar,
  body text
);
#!/usr/bin/env ruby

require 'pg'

@conn = PG::Connection.new(dbname: 'pgrep')

@conn.prepare('insert', 'INSERT INTO mails (path, body) VALUES ($1, $2)')

@conn.exec 'BEGIN'

def recurse(dir)
  Dir.glob("#{dir}/*").each do |f|
    puts f
    if File.directory? f
      recurse f
    else
      body = File.read(f)
      body.scrub!
      body.tr! "\0", ''
      @conn.exec_prepared('insert', [ f, body ])
    end
  end
end

recurse 'tmp'

@conn.exec 'COMMIT'

↑データ投入 3分。

psql -U masm pgrep  
psql -U masm pgrep -c 'create index idx_mails on mails using pgroonga (body);'

9分でインデックス作成が完了。

select * from mails where body &@~ 'masm pgtk';

検索も瞬時。 速っ!

ちなみに CPU は、Intel(R) Celeron(R) J4125 CPU @ 2.00GHz