sphinx+mysql+php做千万数据级别的搜索引擎

时间:2022-07-25 08:15:01

Sphinx是出自俄罗斯的开源全文搜索引擎软件,单一索引最大可包含1亿条记录,在1千万条记录情况下的查询速度为0.x秒(毫秒级)。

Sphinx创建索引的速度为:创建100万条记录的索引只需3~4分钟,创建1000万条记录的索引可以在50分钟内完成,而只包含最新10万条记录的增量索引,重建一次只需几十秒。

Sphinx是什么

  • Sphinx Search 是由俄罗斯人Andrew Aksyonoff 开发的高性能全文搜索软件包,在GPL与商业协议双许可协议下发行。
  • Sphinx的特征:
    1. 支持高速建立索引(可达10MB/秒,而Lucene建立索引的速度是1.8MB/秒)
    2. 高性能搜索(在2-4 GB的文本上搜索,平均0.1秒内获得结果)
    3. 高扩展性(实测最高可对100GB的文本建立索引,单一索引可包含1亿条记录)
    4. 支持分布式检索
    5. 支持基于短语和基于统计的复合结果排序机制
    6. 支持任意数量的文件字段(数值属性或全文检索属性)
    7. 支持不同的搜索模式(“完全匹配”,“短语匹配”和“任一匹配”)
    8. 支持作为Mysql的存储引擎
  • Sphinx是不负责文本字段的存储。 
    假设将数据库的id、date、title、body字段,用Sphinx建立搜索索引。根据关键字、时间、类别、范围等信息查询一下Sphinx,Sphinx只会将查询结果得到的ID号等非文本信息。如果要显示title、body等信息,我们还需要根据此ID号去查询MySQL数据库,或者从Memcachedb等其他的存储中取得。安装SphinxSE作为MySQL的存储引擎,将MySQL与Sphinx结合起来,是一种便捷的方法。

安装步骤 (在这里我们采用的是sphinx 0.9.9经典版本的)

  1. 下载tar包,并进入sphinx目录:( 下载链接 )
    $ tar xf sphinx-0.9.9.tar.gz
    $ cd sphinx-0.9.9
  2. 安装python(以下针对CentOS系统,其他Linux系统请使用相应的方法安装)
    $ yum install python
  3. 编译安装Sphinx
    $ ./configure --prefix=/usr/local/sphinx --with-mysql --with-python --enable-id64
    $ make
    $ make install
  4. 创建sphinx索引文件
    $ mkdir -p /usr/local/sphinx/var/data/document
    $ mkdir -p /dev/shm/sphinx/var/data/document

Sphinx配置

  1. 创建Sphinx配置文件 
    缺省的配置文件名为 sphinx.conf. 全部的Sphinx提供的程序默认都在当前工作的目录下寻找该文件. 

    由configure 程序生成的示例配置文件sphinx.conf.dist 中包括全部选项的注释,复制并编辑这个文件使之适用于你的具体情况: (请确认 Sphinx 安装在 /usr/local/sphinx/)

    $ cd /usr/local/sphinx/etc
    $ cp sphinx.conf.dist sphinx.conf
    $ vim sphinx.conf

    配置文档,采用的是一元分词

    source document
    {
      type					= mysql
    
      sql_host				= 127.0.0.1
      sql_user				= root
      sql_pass				= 123456
      sql_db					= test
      sql_port				= 3306
      sql_query_pre 			        = SET NAMES UTF8
      sql_query				= SELECT id, title, content,update FROM t_doucment WHERE id>=$start AND id<=$end
      sql_query_range			        = SELECT MIN(id), MAX(id) FROM t_resources WHERE updated_at < UNIX_TIMESTAMP(DATE_FORMAT(CURDATE() - INTERVAL 1 DAY, '%Y-%m-%d 17:00:00')) sql_range_step = 1000 sql_attr_uint = updated_at sql_ranged_throttle = 0 sql_query_info = SELECT * FROM t_doucment WHERE id=$id } source document_delta : document { sql_query_range = SELECT MIN(id), MAX(id) FROM t_resources WHERE updated_at >= UNIX_TIMESTAMP(DATE_FORMAT(CURDATE() - INTERVAL 1 DAY, '%Y-%m-%d 17:00:00'))
    }
    
    
    index document
    {
      source			= document
      path			= /usr/local/sphinx/var/data/document
      docinfo			= extern
      mlock			= 0
      stopwords		=
      min_prefix_len	        = 0
      min_infix_len	        = 0
      min_word_len	        = 1
      html_strip		= 1
      charset_type	        = utf-8
      charset_table           = U+FF10..U+FF19->0..9, 0..9, U+FF41..U+FF5A->a..z, U+FF21..U+FF3A->a..z,A..Z->a..z, a..z, U+0149, U+017F, U+0138, U+00DF, U+00FF, U+00C0..U+00D6->U+00E0..U+00F6,U+00E0..U+00F6, U+00D8..U+00DE->U+00F8..U+00FE, U+00F8..U+00FE, U+0100->U+0101, U+0101,U+0102->U+0103, U+0103, U+0104->U+0105, U+0105, U+0106->U+0107, U+0107, U+0108->U+0109,U+0109, U+010A->U+010B, U+010B, U+010C->U+010D, U+010D, U+010E->U+010F, U+010F,U+0110->U+0111, U+0111, U+0112->U+0113, U+0113, U+0114->U+0115, U+0115, U+0116->U+0117,U+0117, U+0118->U+0119, U+0119, U+011A->U+011B, U+011B, U+011C->U+011D, U+011D,U+011E->U+011F, U+011F, U+0130->U+0131, U+0131, U+0132->U+0133, U+0133, U+0134->U+0135,U+0135, U+0136->U+0137, U+0137, U+0139->U+013A, U+013A, U+013B->U+013C, U+013C,U+013D->U+013E, U+013E, U+013F->U+0140, U+0140, U+0141->U+0142, U+0142, U+0143->U+0144,U+0144, U+0145->U+0146, U+0146, U+0147->U+0148, U+0148, U+014A->U+014B, U+014B,U+014C->U+014D, U+014D, U+014E->U+014F, U+014F, U+0150->U+0151, U+0151, U+0152->U+0153,U+0153, U+0154->U+0155, U+0155, U+0156->U+0157, U+0157, U+0158->U+0159, U+0159,U+015A->U+015B, U+015B, U+015C->U+015D, U+015D, U+015E->U+015F, U+015F, U+0160->U+0161,U+0161, U+0162->U+0163, U+0163, U+0164->U+0165, U+0165, U+0166->U+0167, U+0167,U+0168->U+0169, U+0169, U+016A->U+016B, U+016B, U+016C->U+016D, U+016D, U+016E->U+016F,U+016F, U+0170->U+0171, U+0171, U+0172->U+0173, U+0173, U+0174->U+0175, U+0175,U+0176->U+0177, U+0177, U+0178->U+00FF, U+00FF, U+0179->U+017A, U+017A, U+017B->U+017C,U+017C, U+017D->U+017E, U+017E, U+0410..U+042F->U+0430..U+044F, U+0430..U+044F,U+05D0..U+05EA, U+0531..U+0556->U+0561..U+0586, U+0561..U+0587, U+0621..U+063A, U+01B9,U+01BF, U+0640..U+064A, U+0660..U+0669, U+066E, U+066F, U+0671..U+06D3, U+06F0..U+06FF,U+0904..U+0939, U+0958..U+095F, U+0960..U+0963, U+0966..U+096F, U+097B..U+097F,U+0985..U+09B9, U+09CE, U+09DC..U+09E3, U+09E6..U+09EF, U+0A05..U+0A39, U+0A59..U+0A5E,U+0A66..U+0A6F, U+0A85..U+0AB9, U+0AE0..U+0AE3, U+0AE6..U+0AEF, U+0B05..U+0B39,U+0B5C..U+0B61, U+0B66..U+0B6F, U+0B71, U+0B85..U+0BB9, U+0BE6..U+0BF2, U+0C05..U+0C39,U+0C66..U+0C6F, U+0C85..U+0CB9, U+0CDE..U+0CE3, U+0CE6..U+0CEF, U+0D05..U+0D39, U+0D60,U+0D61, U+0D66..U+0D6F, U+0D85..U+0DC6, U+1900..U+1938, U+1946..U+194F, U+A800..U+A805,U+A807..U+A822, U+0386->U+03B1, U+03AC->U+03B1, U+0388->U+03B5, U+03AD->U+03B5,U+0389->U+03B7, U+03AE->U+03B7, U+038A->U+03B9, U+0390->U+03B9, U+03AA->U+03B9,U+03AF->U+03B9, U+03CA->U+03B9, U+038C->U+03BF, U+03CC->U+03BF, U+038E->U+03C5,U+03AB->U+03C5, U+03B0->U+03C5, U+03CB->U+03C5, U+03CD->U+03C5, U+038F->U+03C9,U+03CE->U+03C9, U+03C2->U+03C3, U+0391..U+03A1->U+03B1..U+03C1,U+03A3..U+03A9->U+03C3..U+03C9, U+03B1..U+03C1, U+03C3..U+03C9, U+0E01..U+0E2E,U+0E30..U+0E3A, U+0E40..U+0E45, U+0E47, U+0E50..U+0E59, U+A000..U+A48F, U+4E00..U+9FBF,U+3400..U+4DBF, U+20000..U+2A6DF, U+F900..U+FAFF, U+2F800..U+2FA1F, U+2E80..U+2EFF,U+2F00..U+2FDF, U+3100..U+312F, U+31A0..U+31BF, U+3040..U+309F, U+30A0..U+30FF,U+31F0..U+31FF, U+AC00..U+D7AF, U+1100..U+11FF, U+3130..U+318F, U+A000..U+A48F,U+A490..U+A4CF
      ngram_len             = 1 
      ngram_chars           = U+4E00..U+9FBF, U+3400..U+4DBF, U+20000..U+2A6DF, U+F900..U+FAFF,U+2F800..U+2FA1F, U+2E80..U+2EFF, U+2F00..U+2FDF, U+3100..U+312F, U+31A0..U+31BF,U+3040..U+309F, U+30A0..U+30FF, U+31F0..U+31FF, U+AC00..U+D7AF, U+1100..U+11FF,U+3130..U+318F, U+A000..U+A48F, U+A490..U+A4CF
    }
    
    index document_delta : document
    {
      source			= document_delta
      path			= /dev/shm/sphinx/var/data/document
    }
    
    indexer
    {
        mem_limit               = 64M
        # max_iops              = 40
        # max_iosize            = 1048576
    }
    
    searchd
    {
      listen                  = 127.0.0.1:3312
      log                     = /usr/local/sphinx/var/log/searchd.log
      query_log               = /usr/local/sphinx/var/log/query.log
      read_timeout            = 5
      client_timeout          = 300
      max_children            = 50
      pid_file                = /var/run/searchd.pid
     max_matches             = 320000
     seamless_rotate         = 1
     preopen_indexes         = 1
     unlink_old              = 1
    
     mva_updates_pool        = 1M
     max_packet_size         = 8M
    
     max_filters             = 256
     max_filter_values       = 4096
    }
  2. 初始化sphinx.conf中配置的全部索引

    $ /usr/local/sphinx/bin/indexer --all

    如果searchd处于运行状态,则执行

    $ /usr/local/sphinx/bin/indexer --all --rotate

创建shell脚本,一个用来创建主索引、一个用来创建增量索引

  1. 主索引更新脚本并赋予可执行权限

    $ vim /usr/local/sphinx/bin/build_main_index.sh
    #!/bin/sh
    /usr/local/sphinx/bin/indexer --rotate document
    chmod +x /usr/local/sphinx/bin/build_main_index.sh

    每天凌晨定时重建主索引

    crontab -e
    #每天凌晨4点19分重建一次搜索引擎的主索引
    19 4 * * * /bin/sh /usr/local/sphinx/bin/build_main_index.sh
  2. 增量索引更新脚本并赋予可执行权限

    $ vim /usr/local/sphinx/bin/build_delta_index.sh
    #!/bin/sh
    /usr/local/sphinx/bin/indexer --rotate document_delta
    chmod +x /usr/local/sphinx/bin/build_delta_index.sh

    每3分钟自动重建一次搜索引擎的增量索引

    crontab -e
    #每3分钟自动重建一次搜索引擎的增量索引
    0-57/3 * * * * /bin/sh /usr/local/sphinx/bin/build_delta_index.sh
  3. 启动Sphinx守护进程(searchd)

    $ /usr/local/sphinx/bin/searchd

    配置服务器开机启动时需要自动执行的命令

    $ vim /etc/rc.local
    mkdir -p /dev/shm/sphinx/var/data/document
    /bin/sh /usr/local/sphinx/bin/build_delta_index.sh  2>&1 > /dev/null
    /usr/local/sphinx/bin/searchd

安装scws

  1. 下载编译并安装
    $ wget http://www.xunsearch.com/scws/down/scws-1.2.2.tar.bz2
    $ tar xf scws-1.2.2.tar.bz2
    $ cd scws-1.2.2
    $ ./configure
    $ make
    $ make install
    $ cp -R etc /etc/scws
  2. 下载词库并移动到SCWS配置
    $ wget http://www.xunsearch.com/scws/down/scws-dict-chs-utf8.tar.bz2
    $ tar xf scws-dict-chs-utf8.tar.bz2
    $ mv dict.utf8.xdb /etc/scws
  3. 安装httpscws系统
    $ git clone https://github.com/ivanszl/httpscws.git httpscws
    $ cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/httpscws
    $ make
    $ make install
  4. 编写httpscws启动脚本
    $ vim /etc/init.d/httpscws
    
    #!/bin/bash
    # HTTPSCWS Startup script for the SCWS HTTP Server
    # this script create it by ivan at 2016.01.14.
    #
    # chkconfig: - 95 15
    # description: HTTPSCWS is an Chinese Word Segmentation System Based on the HTTP protocol.
    # processname: httpscws
    # pidfile: /var/run/httpscws.pid
    # config: /etc/scws/
    
    httpscws=/usr/local/httpscws/bin/httpscws
    httpscws_config=/etc/scws/
    pid=/var/run/httpscws.pid
    
    RETVAL=0
    prog="httpscws"
    
    # Source function library.
    . /etc/rc.d/init.d/functions
    
    # Source networking configuration.
    . /etc/sysconfig/network
    
    # Check that networking is up.
    [ ${NETWORKING} = "no" ] && exit 0
    [ -x $httpscws ] || exit 0
    
    # Start searchd daemons functions.
    start(){
      if [ -e $pid ]; then
        echo "$prog already running..."
        exit 1
      fi
      echo -n $"Starting $prog:"
      daemon $httpscws -l 127.0.0.1 -d -i ${pid} -x ${httpscws_config}
      RETVAL=$?
      echo
      [ $RETVAL = 0 ] && touch /var/lock/subsys/httpscws
      return $RETVAL
    }
    
    # Stop searchd daemons functions.
    stop(){
      echo -n $"Stopping $prog:"
      killproc $httpscws
      RETVAL=$?
      echo
      [ $RETVAL = 0 ] && rm -f /var/lock/subsys/httpscws $pid
    }
    
    # See how we were called.
    case "$1" in
      start)
        start
        ;;
      stop)
        stop
        ;;
      restart)
        stop
        start
        ;;
      status)
        status $prog
        RETVAL=$?
        ;;
      *)
        echo $"Usage: $prog {start|stop|restart|status|help}"
        exit 1
      esac
    exit $RETVAL
    $ chmod +x /etc/init.d/httpscws
    $ chkconfig --add httpscws
    $ chkconfig httpscws on
    $ service httpscws start
  5. PHP测试代码
    <?php
    $q = urlencode($q);
    $result = file_get_contents("http://127.0.0.1:1985/?w=" . $q);
    $result = trim($result);
    require_once 'sphinxapi.php';
    $sc = new SphinxClient();
    $sc->SetServer('127.0.0.1',3312);
    $sc->SetMatchMode(SPH_MATCH_ALL);
    $sc->SetArrayResult(TRUE);
    $res = $sc->Query($words);
    var_dump($res);