PostgreSQL で textsearch_ja を使って日本語のテキストを全文検索する方法のメモ。
mecab のインストール
Groonga リポジトリを追加
sudo yum install https://packages.groonga.org/almalinux/9/groonga-release-latest.noarch.rpm
rpm パッケージをインストール
sudo yum install mecab mecab-devel mecab-ipadic
textsearch_ja のインストール
textsearch_ja をダウンロード
$ git clone https://github.com/oknj/textsearch_ja.git
インストール
$ make $ export PATH="${PATH}:/usr/pgsql-17/bin" $ sudo --preserve-env=PATH make install $ psql -f textsearch_ja--42.sql # 必要に応じて -h、-U オプションを指定
postgres にログインして textsearch_ja を有効化
$ psql -h 127.0.0.1 -U postgres # create extension textsearch_ja;
動作確認
# select ja_wakachi('日本語のテキストを単語に分割します。'); ja_wakachi ----------------------------------------------- 日本語 の テキスト を 単語 に 分割 し ます 。
テーブル作成、データ登録
$ psql -h 127.0.0.1 -U postgres # create database test_textsearch1; # create table textsearch1 ( id integer not null, body text, primary key (id) ); # create index on textsearch1 using gin (to_tsvector('japanese', body)); # insert into textsearch1 (id, body) values (0, '日本語のテキストです。'); # insert into textsearch1 (id, body) values (1, '英語のテキストではありません。'); # insert into textsearch1 (id, body) values (2, 'フランス語のテキストではありません。'); # insert into textsearch1 (id, body) values (3, '日本語の文章です。'); # insert into textsearch1 (id, body) values (4, '英語の文章ではありません。');
テーブル検索
単純な検索の場合
# select * from textsearch1 where to_tsvector('japanese', body) @@ to_tsquery('japanese', ' 日本語'); id | body ----+------------------------ 0 | 日本語のテキストです。 3 | 日本語の文章です。
複数ワードでのAND検索の場合
# select * from textsearch1 where (to_tsvector('japanese', body) @@ to_tsquery('japanese', '日本語')) and (to_tsvector('japanese', body) @@ to_tsquery('japanese', 'テキスト')); id | body ----+------------------------ 0 | 日本語のテキストです。