以前寫過次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"; } }