以前写过次sphinx的中文检索,今天接触了下elasticsearch 作下小结吧,及对比php
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful
web接口。Elasticsearch是用Java开发的,并做为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,可以达到实时搜索,稳定,可靠,快速,安装使用方便。html
全部功能集成在一个服务里面,能够经过restful api 各类语言的客户端甚至命令行与之交互node
上手容易,提供了不少合理的缺省值 开箱即用 学习成本低git
配置灵活github
能够参考下这里:http://blog.csdn.net/guochuny...web
原理:
相似于sphinx,建立索引,搜索索引的过程sql
用户输入查询的语句api
对查询语句进行词法,语法分析及语言处理服务器
搜索索引,获取到符合文档restful
首先咱们须要在服务器端配置elasticsearch 参考这里,http://blog.csdn.net/sinat_28...
使用composer库 安装相应的插件,参考这里:https://github.com/yiisoft/yi...
web.php中进行配置
'elasticsearch' => [ 'class' => 'yii\elasticsearch\Connection', 'nodes' => [ ['http_address' => 'localhost:9200'], // configure more hosts if you have a cluster ],
构建表单,这里get方式提交查询关键字到控制器
/*商品搜索*/ public function actionSearch() { $this->layout = "layout2"; //防止sql注入 $keyword = htmlspecialchars(Yii::$app->request->get("keyword")); //高亮数据 $highlight = [ "pre_tags" => ["<em>"], "post_tags" => ["</em>"], "fields" => [ "title" => new \stdClass(), "descr" => new \stdClass() ] ]; $searchModel = ProductSearch::find()->query([ "multi_match" => [ "query" => $keyword, "fields" => ["title", "descr"] ], ]); $count = $searchModel->count(); $pageSize = Yii::$app->params['pageSize']['frontproduct']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $res = $searchModel->highlight($highlight)->offset($pager->offset)->limit($pager->limit)->all(); $products = []; foreach ($res as $result) { $product = Product::findOne($result->productid); $product->title = !empty($result->highlight['title'][0]) ? $result->highlight['title'][0] : $product->title; $product->descr = !empty($result->highlight['descr'][0]) ? $result->highlight['descr'][0] : $product->descr; $products[] = $product; } return $this->render('index', ['all' => $products, 'pager' => $pager, 'count' => $count]); }
// 配置elasticsearch在控制器中
namespace app\models; use yii\elasticsearch\ActiveRecord; class ProductSearch extends ActiveRecord { /*指定要查询的数据*/ public function attributes() { return ["productid", "title", "descr"]; } /*指定索引*/ public static function index() { return "imooc_shop"; } public static function type() { return "products"; } }