elasticsearch在php中的使用

elasticsearch 环境搭建(windows)

安装es

要运行es,首先得安装配置 jdk,具体的步骤谷歌即可。基本的环境配置好之后,就可以去官网上下载 windows 专属的 zip 压缩包了。es 6.0.0下载地址,下载好直接打开 bin 目录下的 elasticsearch.bat 文件就可以了。这时使用浏览器访问 localhost:9200 应该就能看es的相关版本信息了。

安装head插件

这个插件提供了一个可视化界面操作es,包括索引、文档的建立,以及 resful 风格的查询。这里推荐一个安装链接:head插件安装

使用elasticsearch/elasticsearch扩展操作es

这里,我选择了 Laravel 框架来安装,操作 es(纯属个人爱好),也可以直接使用 composer 安装。接下来进行搜索前的一些准备工作:

  1. 创建索引
  2. 创建类型
  3. 创建文档
  4. 将 mysql 中的记录导入 es

上面的这些步骤都是可以通过这个 elasticsearch/elasticsearch 扩展封装的方法来完成的。

执行搜索

接下来的内容才是我要重点记录的,直接上代码

public function search(Request $request)
{
     $search = $request->input('key');
     $curr_page = $request->input('curr_page', 1);
     $page_size = $request->input('page_size', 5);
     //最大值为10000;
     if ($page_size > 10000) {
        $page_size = 10000;
     }
     $market =  $request->input('market_key', '');
     $coin =  $request->input('coin_key', '');
     $currency =  $request->input('currency_key', '');
     $offset = ($curr_page-1) * $page_size;

     //搜索条件
     $query_condition[] = [
         'term' => ['online' => 1],
     ];

     if (!empty($market)) {
         $query_condition[] = [
             'term' => ['market' => strtolower($market)],
         ];
     }
     if (!empty($coin)) {
         $query_condition[] = [
             'term' => ['coin' => strtolower($coin)],
         ];
     }
     if (!empty($currency)) {
         $query_condition[] = [
             'term' => ['currency' => strtolower($currency)],
         ];
     }
     
     $params = [
         'index' => 'search_index',
         'type'  => 'fulltext',
         'from'  => $offset,
         'size'  => $page_size,
         'body'  => [
             'query' => [
                 'bool' => [
                     'should' => [
                         ['match' => ['show' => $search]],
                     ],
                     'filter' => [
                         $query_condition
                     ]
                 ]
             ]
         ]
     ];

     $response = $this->client->search($params);

     $result['count'] = 0;
     $result['list'] = [];
     if (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {
         $hits = $response['hits']['hits'];

         foreach ($hits as $hit) {
             $result['list'][] = $hit['_source'];
         }
     }

     $result['count'] = $response['hits']['total'] ?? 0;
     return $result;
 }

params 参数说明:index 为创建的索引,type 为类型,from 代表从第几个记录开始取值,size 则是一次返回的数量,body 里包含了查询条件及过滤条件,值得注意的是查询结果里hits对象里面的total字段包含了这次查询匹配的记录总数。

猜你喜欢

转载自blog.csdn.net/MShuang6666/article/details/83448305