⭐️

[PostgreSQL]PGroongaでの検索結果ハイライト表示

に公開
  • 前回の記事では、PGroongaを利用したPostgreSQLでの高速な全文検索環境を構築しました。
  • 今回は、PGroongaの便利な機能の1つであるpgroonga_snippet_htmlを使って、検索結果のキーワードをハイライト表示する方法をご紹介します。

手順

  • 前回構築した環境(既に起動している前提)で、実際に試してみます。

シンプルなハイライト表示

  • まず検索文字列をシンプルにハイライト表示は以下です。
docker compose exec -T db psql -U sample -d sample -c "
SELECT
  id,
  title,
  pgroonga_snippet_html(
    title,
    pgroonga_query_extract_keywords('検索')
  ) AS highlighted
FROM books
WHERE title &@~ '検索'
"
  • 実行結果は以下です。
    • デフォルトでは<span class="keyword">タグでキーワードが囲まれます。結果は配列形式で返されます。
id   |    title     |                   highlighted
-------+--------------+-------------------------------------------------
   1 | 検索タイトル | {"<span class=\"keyword\">検索</span>タイトル"}
50000 | 検索タイトル | {"<span class=\"keyword\">検索</span>タイトル"}
(2 rows)

複数キーワードのハイライト

  • 次にOR検索で複数キーワードを指定した場合のハイライト表示は以下です。
docker compose exec -T db psql -U sample -d sample -c "
SELECT
  id,
  title,
  pgroonga_snippet_html(
    title,
    pgroonga_query_extract_keywords('検 OR 索')
  ) AS highlighted
FROM books
WHERE title &@~ '検 OR 索'
"
  • 実行結果は以下です。
id   |    title     |                                  highlighted
-------+--------------+--------------------------------------------------------------------------------
   1 | 検索タイトル | {"<span class=\"keyword\">検</span><span class=\"keyword\">索</span>タイトル"}
50000 | 検索タイトル | {"<span class=\"keyword\">検</span><span class=\"keyword\">索</span>タイトル"}
(2 rows)

表示形式変更

  • デフォルトの結果が配列形式なので、展開してのハイライト表示は以下です。
docker compose exec -T db psql -U sample -d sample -c "
SELECT
  id,
  title,
  unnest(pgroonga_snippet_html(
    title,
    pgroonga_query_extract_keywords('検索')
  )) AS highlighted
FROM books
WHERE title &@~ '検索'
"
  • 実行結果は以下です。
    • unnestを利用して、ネストを解除して展開表示してくれます。
id   |    title     |                highlighted
-------+--------------+-------------------------------------------
   1 | 検索タイトル | <span class="keyword">検索</span>タイトル
50000 | 検索タイトル | <span class="keyword">検索</span>タイトル
(2 rows)
  • JSON形式での表示は以下です。
docker compose exec -T db psql -U sample -d sample -c "
SELECT
  id,
  title,
  array_to_json(pgroonga_snippet_html(
    title,
    pgroonga_query_extract_keywords('検索')
  )) AS highlighted
FROM books
WHERE title &@ '検索'
"
  • 実行結果は以下です。
    • array_to_jsonを利用してJSON変換して表示してくれます。
id   |    title     |                highlighted
-------+--------------+-------------------------------------------------
   1 | 検索タイトル | ["<span class=\"keyword\">検索</span>タイトル"]
50000 | 検索タイトル | ["<span class=\"keyword\">検索</span>タイトル"]
(2 rows)

まとめ

  • pgroonga_snippet_htmlを活用することで、検索結果のキーワードを自動ハイライトが容易に行えます。
  • HTMLで返してくれるので、フロントエンドでCSSで調整するだけで、ユーザビリティの高い検索機能がシンプルに実装可能です。

参考

Discussion