sphinx 索引服务的启动和测试

󰃭 2016-04-27

导读

上一篇我们成功创建了索引, 现在我们来看看如何将索引服务启动并且测试是否可用

启动索引服务

启动索引服务有多种方式, 这里我只说两种, 一种是直接通过searchd启动, 另外一种是通过supervisord 启动, 不过也是利用了searchd

searchd命令启动

在我们创建好了索引后, 我们就可以通过searchd这个命令启动了, 通过searchd -h 我们查看其帮助信息

基本的使用如下

sudo -u searchuser searchd -c sphinx_test.conf

输出信息如果看到

using config file 'sphinx_test.conf'...
listening on all interfaces, port=3316
listening on 127.0.0.1:9306
precaching index 'article'
precached 1 indexes in 0.035 sec

索引服务就启动成功了, 监听了3316和9306两个端口

通过ps -ef | grep searchd 我们可以看到索引服务进程

supervisord 启动

supervisord 是使用 python 写的一个进程管理工具, 我们使用他来启动服务是因为他能够在服务崩溃时自动启动

首先我们先安装一个supervisord

sudo apt-get install supervisor

然后我们就可以配置searchd 服务在supervisord 中的启动配置了 配置文件一般在 /etc/supervisor/conf.d/ 下, 以.conf为后缀的文件 以下是我们索引服务的启动文件

[program:searchd]
command=searchd -c /path/to/sphinx/config/sphinx_test.conf --nodetach
user=sphinx
autorestart=true
startretries = 3

然后通过supervisorctl 工具将服务启动即可, 我们的配置表示服务崩溃后supervisord会尝试重启服务, 最多三次

本质还是调用了searchd命令

服务验证和测试

至此, 我们已经把索引服务启动起来了, 下面我们通过sphinx 源码包中自带的python的客户端进行验证

我们之前下载的源码包中, 有个api的目录, 这里面包含了各种语言的sphinx 接口, 还有几个测试的脚本

java/
lgpl-3.0.txt
libsphinxclient/
ruby/
sphinxapi.php
sphinxapi.py
test2.php
test2.py
test.php
test.py

test2.py 是一个 sphinx 的python 接口使用例子(PHP同理),我们使用test.py 进行测试,

python test.py

输出的是帮助信息

Usage: python test.py [OPTIONS] query words

Options are:
-h, --host <HOST>       connect to searchd at host HOST
-p, --port              connect to searchd at port PORT
-i, --index <IDX>       search through index(es) specified by IDX
-s, --sortby <EXPR>     sort matches by 'EXPR'
-a, --any               use 'match any word' matching mode
-b, --boolean           use 'boolean query' matching mode
-e, --extended          use 'extended query' matching mode
-f, --filter <ATTR>     filter by attribute 'ATTR' (default is 'group_id')
-v, --value <VAL>       add VAL to allowed 'group_id' values list
-g, --groupby <EXPR>    group matches by 'EXPR'
-gs,--groupsort <EXPR>  sort groups by 'EXPR'
-l, --limit <COUNT>     retrieve COUNT matches (default is 20)

我们要对 --extended 通过这个参数, 我们可以写个查询表达式对数据进行查询

以下是我的测试:

python test.py -h 127.0.0.1 -p 3316 -i article -e '动态'

即查询动态这个关键字 输出结果如下:

DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API
Query '动态 ' retrieved 2 of 2 matches in 0.000 sec
Query stats:
        '动' found 4 times in 2 documents
        '态' found 4 times in 2 documents

Matches:
1. doc_id=10, weight=4696, title=工作动态1, content=<p>工作动态1</p>, cid=6, ctime=2016-04-25 01:34:54, mtime=2016-04-24 17:34:54
2. doc_id=11, weight=4696, title=工作动态2, content=<p>工作动态2</p>, cid=6, ctime=2016-04-25 01:35:06, mtime=2016-04-24 17:35:06

不仅仅将命中的结果展示出来了(Matches中展示,默认最多只显示相关性最高的20个), 还将我们请求的关键字的所有匹配统计都打印出来了

今天暂且说到这里, 下一篇我们将会说一说如何新的数据和更新在索引中体现出来