Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

Ubuntu 16.04에서 Sphinx 검색 엔진 설치 및 설정하는 완벽 가이드

이 글에서는 Ubuntu 16.04 환경에서 오픈소스 검색 엔진인 Sphinx를 설치하고 설정하는 방법을 단계별로 살펴봅니다. Sphinx는 전문(full-text) 검색을 지원하는 강력한 검색 엔진으로, SQL 데이터베이스나 일반 텍스트 파일 등 다양한 소스에서 대용량 데이터를 매우 효율적으로 검색할 수 있도록 설계되었습니다.

Sphinx의 주요 특징

  • 고급 인덱싱 기능과 우수한 쿼리 도구 제공

  • 뛰어난 검색 성능과 빠른 인덱싱 속도

  • 후처리(post-processing)를 위한 고급 결과 처리 기능

  • 고급 검색 기능과 함께 손쉬운 확장성 확보

  • SQL 및 XML 소스와의 간편한 통합 가능

  • 수천 개의 동시 쿼리를 처리할 수 있는 대규모 데이터 처리 능력

사전 준비 사항

설치를 시작하기 전에 다음 사항을 확인해야 합니다.

  • sudo 권한을 가진 non-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) ...
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) ...

Sphinx 테스트용 데이터베이스 생성

설치가 완료되면 패키지에 기본 포함된 샘플 데이터를 사용해 테스트 데이터베이스를 생성합니다. 이 데이터베이스는 이후 단계에서 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(검색 데몬) 세 가지 핵심 블록으로 구성됩니다. 이 설정들은 sphinx.conf 파일에서 관리되며, 기본 예제 파일은 /etc/sphinxsearch/sphinx.conf.sample 경로에 위치합니다. 먼저 샘플 파일을 복사하여 실제 설정 파일을 만듭니다.

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

Source 블록 설정

source 블록은 인덱싱할 데이터가 어디서 오는지 정의합니다. MySQL 연결 정보와 데이터를 가져올 SQL 쿼리를 지정합니다.

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
}

Index 블록 설정

index 블록은 source에서 가져온 데이터를 어떻게 인덱싱할지 정의합니다.

index test
{
    source = src1
    path = /var/lib/sphinxsearch/data/test
    docinfo = extern
}

Searchd 블록 설정

searchd 블록은 검색 데몬의 동작 방식을 정의하며, API 포트, 로그 경로, 성능 관련 옵션들을 포함합니다.

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

파일 맨 아래에 다음 내용을 추가합니다.

# m h dom mon dow command
@hourly /usr/bin/indexer --rotate --config /etc/sphinxsearch/sphinx.conf --all

위 설정은 매시간마다 --rotate 옵션과 함께 인덱서를 실행하여 서비스 중단 없이 인덱스를 자동 갱신합니다.

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

서비스 재시작 후 아래 명령어로 상태를 확인합니다.

$ 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 검색 테스트

이제 MySQL 인터페이스를 통해 9306 포트로 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.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

데이터베이스에서 "test" 단어 검색하기

접속이 완료되면 MATCH 구문을 사용해 실제 검색이 정상적으로 작동하는지 확인합니다.

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는 수십억 개의 문서와 수 테라바이트 규모의 데이터를 처리할 수 있으며, 초당 수천 건의 검색 쿼리를 실행할 수 있는 뛰어난 성능을 자랑합니다.