MySQL
 Computer >> コンピューター >  >> プログラミング >> MySQL

Ubuntu 16.04に全文検索エンジンSphinxをインストールしてセットアップする方法

この記事では、Ubuntu 16.04にSphinxをインストールし、セットアップする方法を詳しく解説します。Sphinxはオープンソースの検索エンジンで、フルテキスト検索を可能にします。SQLデータベースやプレーンテキストファイルなど、あらゆるソースからの大量データに対して、高速かつ効率的な検索を実現できる点が大きな魅力です。

Sphinxの主な特徴

  • 高度なインデックス機能と優れたクエリツールを備えている。

  • 高い検索パフォーマンスとインデックス速度を実現。

  • 後処理に活かせる柔軟な検索結果の出力。

  • 高度な検索機能により容易にスケール可能。

  • SQLやXMLソースとのシームレスな統合が可能。

  • 数千件規模の同時クエリにも耐えられる大容量データ処理に対応。

前提条件

作業を始める前に、以下の環境が整っていることを確認してください。

  • sudo権限を持つ非rootユーザーが設定されたUbuntuマシン。

  • マシンにMySQLがインストール済みであること。

Sphinxのインストール

Sphinxは、Ubuntuのネイティブパッケージリポジトリからapt-getコマンドを使って直接インストールできます。以下のコマンドを実行してください。

$ sudo apt-get install sphinxsearch
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libmysqlclient20 libstemmer0d
The following NEW packages will be installed:
libmysqlclient20 libstemmer0d sphinxsearch
0 upgraded, 3 newly installed, 0 to remove and 92 not upgraded.
Need to get 2,608 kB of archives.
After this operation, 20.5 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 https://in.archive.ubuntu.com/ubuntu xenial/universe amd64 libstemmer0d amd64 0+svn585-1 [62.1 kB]
Get:2 https://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libmysqlclient20 amd64 5.7.15-0ubuntu0.16.04.1 [809 kB]
Get:3 https://in.archive.ubuntu.com/ubuntu xenial/universe amd64 sphinxsearch amd64 2.2.9-1build1 [1,737 kB]
Fetched 2,608 kB in 2s (986 kB/s)
Selecting previously unselected package libstemmer0d:amd64.
(Reading database ... 117542 files and directories currently installed.)
Preparing to unpack .../libstemmer0d_0+svn585-1_amd64.deb ...
Unpacking libstemmer0d:amd64 (0+svn585-1) ...
Selecting previously unselected package libmysqlclient20:amd64.
Preparing to unpack .../libmysqlclient20_5.7.15-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libmysqlclient20:amd64 (5.7.15-0ubuntu0.16.04.1) ...
Selecting previously unselected package sphinxsearch.
Preparing to unpack .../sphinxsearch_2.2.9-1build1_amd64.deb ...
Unpacking sphinxsearch (2.2.9-1build1) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu4) ...
Setting up libstemmer0d:amd64 (0+svn585-1) ...
Setting up libmysqlclient20:amd64 (5.7.15-0ubuntu0.16.04.1) ...
Setting up sphinxsearch (2.2.9-1build1) ...
Adding system user `sphinxsearch' (UID 119) ...
Adding new group `sphinxsearch' (GID 125) ...
Adding new user `sphinxsearch' (UID 119) with group `sphinxsearch' ...
Not creating home directory `/var/run/sphinxsearch'.
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu4) ...

テスト用データベースの作成

続いて、パッケージに標準で同梱されているサンプルデータを使ってテスト用データベースを作成します。これにより、後のステップでSphinxの検索機能を実際に試すことができます。

まずMySQLにログインし、テストデータベースを作成してサンプルデータをインポートしましょう。

$ mysql –u root –p
mysql> create database test;
Query OK, 1 row affected (0.01 sec)
mysql> SOURCE /etc/sphinxsearch/example.sql;
Query OK, 0 rows affected, 1 warning (0.01 sec)
Query OK, 0 rows affected (0.03 sec)
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 10 rows affected (0.01 sec)
Records: 10 Duplicates: 0 Warnings: 0
Mysql> quit

Sphinxの検索設定

Sphinxでは、自分の環境に合わせて「source」「index」「searchd」の3つの主要ブロックを編集・設定する必要があります。これらは設定ファイルsphinx.confに定義されており、サンプルファイルは/etc/sphinxsearch/sphinx.conf.sampleとして配置されています。まず、既存のサンプル設定ファイルを/etc/sphinxsearchディレクトリにコピーします。

$ cp /etc/sphinxsearch/sphinx.conf.sample /etc/sphinxsearch/sphinx.conf
$ sudo vi /etc/sphinxsearch/sphinx.conf

設定ファイルは、以下のような各ブロックで構成されます。

sphinx.confのSourceブロック

source src1
{
    type = mysql
    #SQL settings (for 'mysql' and 'pgsql' types)
    sql_host = localhost
    sql_user = root
    sql_pass = ubuntu
    sql_db = test
    sql_port = 3306 # optional, default is 3306
    sql_query = \
    SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
    FROM documents
    sql_attr_uint = group_id
    sql_attr_timestamp = date_added
}

sphinx.confのIndexブロックとSearchdブロック

index test
{
    source = src1
    path = /var/lib/sphinxsearch/data/test
    docinfo = extern
}
searchd
{
    listen = 9312:sphinx #SphinxAPI port
    listen = 9306:mysql41 #SphinxQL port
    log = /var/log/sphinxsearch/searchd.log
    query_log = /var/log/sphinxsearch/testquery.log
    read_timeout = 5
    max_children = 30
    pid_file = /var/run/sphinxsearch/testsearchd.pid
    seamless_rotate = 1
    preopen_indexes = 1
    unlink_old = 1
    binlog_path = /var/lib/sphinxsearch/data/test
}

設定ファイルの編集が完了したら、次にSphinxのインデックスを作成します。

Sphinxのインデックス管理

ここでは、前のステップで編集した設定ファイルをもとにインデックスを作成します。

$ sudo indexer –all
Sphinx 2.2.9-id64-release (rel22-r5006)
Copyright (c) 2001-2015, Andrew Aksyonoff
Copyright (c) 2008-2015, Sphinx Technologies Inc (https://sphinxsearch.com)
using config file '/etc/sphinxsearch/sphinx.conf'...
indexing index 'test'...
collected 4 docs, 0.0 MB
sorted 0.0 Mhits, 100.0% done
total 4 docs, 193 bytes
total 0.007 sec, 24319 bytes/sec, 504.03 docs/sec
total 4 reads, 0.000 sec, 0.1 kb/call avg, 0.0 msec/call avg
total 12 writes, 0.000 sec, 0.1 kb/call avg, 0.0 msec/call avg

本番環境では、インデックスを常に最新の状態に保つ必要があります。そのためには、cronジョブを作成しておくのが効果的です。

$ crontab –e

ファイルの末尾に以下の行を追加してください。

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
@hourly /usr/bin/indexer --rotate --config /etc/sphinxsearch/sphinx.conf –all

Sphinxサービスの起動

設定ファイルを使ってインデックスを作成したら、Sphinxの起動設定を行います。デフォルトではSphinxデーモンは自動的に起動しないため、/etc/default/sphinxsearchファイルを編集する必要があります。

$ vi /etc/default/sphinxsearch
#
# Settings for the sphinxsearch searchd daemon
# Please read /usr/share/doc/sphinxsearch/README.Debian for details.
#
# Should sphinxsearch run automatically on startup? (default: no)
# Before doing this you might want to modify /etc/sphinxsearch/sphinx.conf
# so that it works for you.
START=yes

以下のコマンドでSphinxデーモンを起動します。

$ sudo systemctl restart sphinxsearch.service

sphinxsearchサービスの再起動後、以下のコマンドでステータスを確認できます。

$ sudo systemctl status sphinxsearch.service
sphinxsearch.service - LSB: Fast standalone full-text SQL search engine
Loaded: loaded (/etc/init.d/sphinxsearch; bad; vendor preset: enabled)
Active: active (exited) since Mon 2016-09-19 13:00:20 IST; 1h 10min ago
Docs: man:systemd-sysv-generator(8)
Tasks: 0 (limit: 512)
Memory: 0B
CPU: 0
Sep 19 13:00:20 ubuntu-16 systemd[1]: Starting LSB: Fast standalone full-text SQL search engine...
Sep 19 13:00:20 ubuntu-16 sphinxsearch[7804]: To enable sphinxsearch, edit /etc/default/sphinxsearch and set START=yes
Sep 19 13:00:20 ubuntu-16 systemd[1]: Started LSB: Fast standalone full-text SQL search engine.

Sphinx検索のテスト

次に、ポート9306経由でMySQLインターフェースを使ってSphinxQLに接続します。

$ mysql -h0 -P9306
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 2.2.9-id64-release (rel22-r5006)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

データベース内の「test」というキーワードを検索する

mysql> SELECT * FROM test WHERE MATCH('test '); SHOW META;
+------+----------+------------+
| id   | group_id | date_added |
+------+----------+------------+
|    1 |        1 | 1474272578 |
|    2 |        1 | 1474272578 |
|    4 |        2 | 1474272578 |
+------+----------+------------+
3 rows in set (0.00 sec)
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| total         | 3     |
| total_found   | 3     |
| time          | 0.000 |
| keyword[0]    | test  |
| docs[0]       | 3     |
| hits[0]       | 5     |
+---------------+-------+
6 rows in set (0.00 sec)

以上の手順でセットアップと設定を行えば、Sphinxを強力な検索エンジンとして運用できます。Sphinxは高い効率性を誇り、大規模データの処理に最適です。数十億件のドキュメントやテラバイト級のデータを取り扱え、毎秒数千件もの検索クエリを実行することも可能です。

  1. 【徹底解説】Windows 7を完全に削除してUbuntuだけをインストールする方法

    純粋なLinux環境へ本格的に移行したいと考えている方でも、Windows 7のインストールが壊れてしまったノートパソコンを復活させたい方でも、ドライブ上の既存データをすべて消し去り、新しいOSに入れ替えることは可能です。Ubuntuのインストールガイドの多くはデュアルブートの設定方法に重点を置いていますが、必ずしもデュアルブートが必要というわけではありません。古いOSを完全に排除するのも同じように簡単です。作業前の注意点まず最初に、残しておきたいデータをWindowsエクスプローラーやコマンドラインを使って、USBメモリやクラウドストレージにコピーしておきましょう。多くの場合、ドライブをゼロ

  2. Windows 10 / 11 に Ubuntu をインストールする3つの方法【WSL・USB起動・仮想マシン】

    Windows 10 や Windows 11 のパソコンで Ubuntu Linux を使ってみたいと思ったことはありませんか?この記事では、その手順を初心者の方にもわかりやすく解説します。 実は、Windows 上で Ubuntu をインストールして動かす方法はひとつだけではありません。本記事では、代表的な3つのアプローチをご紹介します。① Windows Subsystem for Linux(WSL)を使って Linux コマンドを実行する方法、② USB メモリから直接起動する方法、そして③ 仮想マシン(VM)上で動かす方法です。 それぞれの特徴と手順を順番に見ていきましょう。 方法