您现在的位置是:首页 > 博客日记 > Php Php

yii2使用solr扩展

2018-12-30 00:00:00 【Php】 人已围观

yii2使用solr扩展

Install

  1. composer require tinymeng/yii2-solr dev-master

类库使用的命名空间为\\tinymeng\\solr

注意

  • 不必安装PHP的Solr扩展(由于solr扩展很久没有更新过了,仅支持PHP5.6左右的版本,PHP7.0以上版本安装不上)
  • 暂时只实现了AR查询的使用
  • 未实现AR的增删改,可以使用 \yii::$app->solr 进行操作

引用小部件 main.php

  1. 'components' => [
  2. 'solr'=>[
  3. 'class'=> 'tinymeng\solr\Client',
  4. 'options' => [
  5. 'endpoint'=>[
  6. [
  7. 'scheme' => 'http',
  8. 'host' => '127.0.0.1',
  9. 'port' => 8080,
  10. 'path' => '/solr/',
  11. 'core' => 'collection1',
  12. ],
  13. [
  14. 'scheme' => 'http',
  15. 'host' => '127.0.0.1',
  16. 'port' => 8080,
  17. 'path' => '/solr/',
  18. 'core' => 'collection2',
  19. ],
  20. ],
  21. ]
  22. ],
  23. ]

yii AR 查询模式

create Model

  1. <?php
  2. namespace models\solr;
  3. use \tinymeng\solr\ActiveRecord;
  4. class Collection extends ActiveRecord
  5. {
  6. /** solr core name */
  7. public static function tableName()
  8. {
  9. return 'collection1';
  10. }
  11. /** solr core attr */
  12. public function attributes()
  13. {
  14. return [
  15. 'id',
  16. 'title',
  17. 'name',
  18. ];
  19. }
  20. }

查询方法

  1. $where = [
  2. 'id'=>1,
  3. 'type'=>28,
  4. ['between','type',1,100]
  5. ];
  6. $select = ['id,title'];
  7. $page = 1;
  8. $page_size = 20;
  9. $list = Collection::find()
  10. ->select($select)
  11. ->where($where)
  12. ->offset(($page-1)*$page_size)
  13. ->limit($page_size)
  14. ->orderBy('id asc,type asc')
  15. ->asArray()
  16. ->all();

查询高亮方法

  1. $keywords = '汽车';
  2. Collection::find()
  3. ->select($select)
  4. ->where(['keywords'=>$keywords])
  5. ->highlight([
  6. "pre_tags"=>'<font color="#ff0000">',
  7. "post_tags"=>'</font>',
  8. "fields"=>['title','content']
  9. ])
  10. ->asArray()
  11. ->all();


关注TinyMeng博客,更多精彩分享,敬请期待!
 

很赞哦! ()