Skip to content

Commit 6e0b69a

Browse files
authored
Merge pull request #5 from askdkc/pgroonga
PGroonga記事追加
2 parents 41428ce + 7884a80 commit 6e0b69a

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
---
2+
layout: post
3+
categories: blog
4+
author:
5+
- dkc
6+
---
7+
8+
PGroongaを使うと読み方が一緒でも漢字が異なる文字を簡単に検索出来るようになります👍
9+
10+
## サンプルSQL
11+
12+
やり方のサンプルSQLを下記に載せます:
13+
14+
```sql
15+
-- 必要な拡張機能追加
16+
CREATE EXTENSION IF NOT EXISTS pgroonga;
17+
18+
-- 同じ読みに使われる文字を登録するテーブルを作ります
19+
CREATE TABLE synonyms (
20+
target text,
21+
normalized text
22+
);
23+
24+
-- 検索用インデックスと異なる漢字の辞書データを作ります
25+
CREATE INDEX pgroonga_synonyms_index ON synonyms
26+
USING pgroonga (target pgroonga_text_term_search_ops_v2)
27+
INCLUDE (normalized);
28+
29+
INSERT INTO synonyms VALUES ('', '');
30+
INSERT INTO synonyms VALUES ('', '');
31+
INSERT INTO synonyms VALUES ('', '');
32+
INSERT INTO synonyms VALUES ('', '');
33+
34+
35+
-- 検索を実行させたいサンプルテーブルを作成
36+
-- WITHで指定しているインデックスのnormalizedのところが肝です
37+
CREATE TABLE names (
38+
name text
39+
);
40+
CREATE INDEX pgroonga_names_index
41+
ON names
42+
USING pgroonga (name pgroonga_text_full_text_search_ops_v2)
43+
WITH (normalizers='
44+
NormalizerNFKC150,
45+
NormalizerTable(
46+
"normalized", "${table:pgroonga_synonyms_index}.normalized",
47+
"target", "target"
48+
)
49+
');
50+
51+
INSERT INTO names
52+
(name)
53+
VALUES ('斉藤さん'),('齊藤さん'),('斎藤さん'),('鈴木さん'),('田中さん'),('佐藤さん'),('高橋さん'),('髙橋さん');
54+
55+
56+
-- 斉藤で検索、どの斉藤もヒットする
57+
SELECT name AS synonym_names from names where name &@~ '斉藤さん';
58+
-- synonym_names
59+
-- ---------------
60+
-- 斉藤さん
61+
-- 齊藤さん
62+
-- 斎藤さん
63+
-- (3 rows)
64+
65+
66+
-- 同じく今度は高橋で検索している例、同じく全ての高橋がヒット
67+
SELECT name AS synonym_names from names where name &@~ '高橋さん';
68+
-- synonym_names
69+
-- ---------------
70+
-- 高橋さん
71+
-- 髙橋さん
72+
-- (2 rows)
73+
```
74+
75+
日本語難しい🫠
76+
77+
### 他の漢字とか
78+
79+
「渡辺」とか「沢田」みたいなのに対応させる時はこんな感じでデータを入れておきます
80+
81+
```sql
82+
INSERT INTO synonyms VALUES ('', '');
83+
INSERT INTO synonyms VALUES ('', '');
84+
INSERT INTO synonyms VALUES ('', '');
85+
```

0 commit comments

Comments
 (0)