<?php
namespace Wd\Aliyun;

class Search{

    //默认配置
    public $config = array(
		//杭州公网API地址：http://opensearch-cn-hangzhou.aliyuncs.com
		//北京公网API地址：http://opensearch-cn-beijing.aliyuncs.com 
        'host'           => 'http://opensearch-cn-hangzhou.aliyuncs.com',                    
        'index'         => '',                         // 认证方式，1为实时认证；2为登录认证。
        'query_string'        => '',        // 用户组数据表名
        'hits' => '20', // 用户-用户组关系表
        'format'         => 'json',         // 权限规则表
        'sort'         => '-RANK',
		'filter'       =>'',
		'starthit'     =>'0',
		'fields'       =>''
    );
	
	function search(){
		import("Wd.Aliyun.Search.CloudsearchClient");
		import("Wd.Aliyun.Search.CloudsearchSearch");
		$access_key = C('ALIYUN.ACCESS_KEY');
		$secret = C('ALIYUN.SECRET');
		$key_type = "aliyun";  //固定值，不必修改
		$opts = array('host'=>$this->config['host']);
		$client = new \CloudsearchClient($access_key,$secret,$opts,$key_type);
		
		
		// 实例化一个搜索类
		$search_obj = new \CloudsearchSearch($client);
		// 指定一个应用用于搜索
		$search_obj->addIndex($this->config['index']);
		// 指定搜索关键词
		$search_obj->setQueryString($this->config['query_string']);
		
		//条数
		$search_obj->setHits($this->config['hits']);
		//排序
		$sort=preg_split('/[,]+/s', $this->config['sort'],-1,PREG_SPLIT_NO_EMPTY);
		foreach($sort as $v){
			$search_obj->addSort(substr($v,1), substr($v,0,1));	
		}
		
		//过滤
		foreach($this->config['filter'] as $k=>$v){
			$search_obj->addFilter($v['filter'],$v['operator']);
		}
		// 指定返回的搜索结果的格式为json
		$search_obj->setFormat($this->config['format']);
		//设置返回结果的offset偏移量
		$search_obj->setStartHit($this->config['starthit']);
		//添加指定结果集返回的字段
		$fields=preg_split('/[,]+/s', $this->config['fields'],-1,PREG_SPLIT_NO_EMPTY);
		foreach($fields as $v){
			$search_obj->addFetchFields($v);
		}
		// 执行搜索，获取搜索结果
		$json = $search_obj->search();
		$list = json_decode($json,true);
		return $list['result'];	
	}
	

}