sphinx关键字套红

    sphinx定义搜索结果,搜索的内容着重显示,可以使用下面代码

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: pc00001
 5  * Date: 2015/4/10
 6  * Time: 14:18
 7  */
 8 header('Content-type:text/html;charset=utf-8');
 9 include_once('sphinxapi.php');
10 
11 $sp = new SphinxClient();
12 
13 $sp ->SetServer('127.0.0.1',9312);  //server连接
14 $sp ->SetConnectTimeout(5); //超时时间
15 $sp ->SetLimits(0,10);  //取出条数
16 
17 $keywords = isset($_REQUEST['ky'])?$_REQUEST['ky']:'新款';
18 
19 $res = $sp ->Query($keywords,'*');
20 
21 
22 $res_id = (implode(',',array_keys($res['matches'])));
23 
24 $conn= mysql_connect('127.0.0.1','root','');
25 mysql_query('set names utf8');
26 mysql_query('use ldds');
27 $sql = "select*from ld_goods where goods_id in ($res_id)";
28 $tmp = mysql_query($sql,$conn);
29 
30 $query_res = array();
31 while($row = mysql_fetch_assoc($tmp)){
32     $query_res[] = $row;
33 }
34 
35 
36 $goods_name = array();
37 $res = array();
38 //定义关键字标注内容
39 $build_opts = array(
40     'before_match'=>"<font color='red'>",   //在关键字之前添加的html
41     'after_match'=> '</font>'          //在关键字之后添加的html
42 );
43 
44 
45 foreach($query_res as $k=>$v){
46     $goods_name[$k] = $v['goods_name'];
47 }
48 
49 //参数分别是 (需要标注的内容,索引名称,关键字,定义关键字设置数组)
50 $res = $sp -> BuildExcerpts($goods_name,'mysql',$keywords,$build_opts);
51 print_r($res);
52 //var_dump($goods_name);exit;

结果显示类似下面内容

[0] => 正品 2014春装新款 女 绣花针织衫 开衫外套浮桑初 蓝色 [1] => 正品 2014春装新款 女 绣花针织衫 开衫外套浮桑初 绿色 

其他常用方法

其他Sphinxapi中常用方法 1

      $sp -> SetMatchMode(          );
     SPH_MATCH_ALL, 匹配所有查询词(默认模式)
     SPH_MATCH_ANY, 匹配查询词中的任意一个
    SPH_MATCH_PHRASE, 将整个查询看作一个词组,要求按顺序完整匹配
    SPH_MATCH_BOOLEAN, 将查询看作一个布尔表达式  (实现不包含关键词的搜索)
     SPH_MATCH_EXTENDED, 将查询看作一个Sphinx内部查询语言的表达式

      $sp->SetFilterRange ( $attribute, $min, $max, $exclude=false );
      添加新的整数范围过滤器
          $sp->SetFilterRange (‘dateline’,time()-3600,time());//查询某个时间段

      $sp->SetFilter ( $attribute, $values, $exclude=false );//查询指定字段为value,如通过uid查
                     增加整数值过滤器。

      $sp->SetSortMode ( $mode, $sortby=“” ) ;
                     设置匹配项的排序模式,6种模式
                  SPH_SORT_EXPR 模式,按某个算术表达式排序。
           $uptime = time() - 60*60*24*60;
           $sp->SetSortMode(SPH_SORT_EXPR, "@weight + IF(dateline > $uptime,1,0)“)

    $sp->SetFieldWeights ( $weights );//按字段名称设置字段的权值

           if (!$is_bytitle) {

  $weight = array(

  'title'=> 10,'content'=> 100,

  );

           } else {

  $weight = array(

  'title'=> 100,'content'=> 10,

                                    );

           }

           $sp->SetFieldWeights($weights); // 适用于按标题搜索,或者按内容搜索

        $sp->SetFilterFloatRange( $attribute, $min, $max, $exclude=false );

              增加新的浮点数范围过滤器。使用方法类似于整型过滤

注意:使用这些方法,需要将数据所在字段的内容加入到索引中。如配置文件中:

    sql_attr_uint  = click

    sql_attr_timestamp      = dateline

    另外这些方法必须在Query()方法执行前执行。

原文地址:https://www.cnblogs.com/gophper/p/4419094.html