β

Yii2使用composer安装Elasticsearch扩展和简单使用

与您分享电脑世界 88 阅读

依旧安装composer这里就不多说了, ElasticSearch安装 看这里,先cmd进入项目目录

prefer-dist参数前面是两个半角英文-

执行:

composer require –prefer-dist  yiisoft/yiisoft/ yii2 -elasticsearch “*”

php composer.phar require –prefer-dist yiisoft/yiisoft/yii2-elasticsearch “*”

安装成功后扩展目录就有了

在\advanced\common\config\main-local.php下添加

<?php
return [
    'components' => [
        'elasticsearch' => [
            'class' => 'yii\elasticsearch\Connection',
            'nodes' => [
                ['http_address' => 'localhost:9200'],
                // configure more hosts if you have a cluster
            ],
        ],
    ],
];
随便找个控制器添加以下代码,这里使用的是query查询找个控制器
use yii\elasticsearch\Query;
      $query = new Query;
      $query->fields(['id','title','content'])
         ->from('myweb', 'news')//读取已经添加好的对应索引
         //->query(['match' => ['id'=>418076]])
//       ->query(['match' => ['title'=>['query'=>"汽车 2016","operator"=>"and"]]])
         ->query(['multi_match' => ['query'=>"安全","fields"=>["title","content"]]])
         ->orderBy(['_score' => ['order' => 'desc'],'updatetime'=>['order' => 'desc']])
         ->options(['track_scores'=>true])//指定order by一般就不计算scores了 可以强制计算其相关性,可以设置track_scores为 true。
         ->highlight([
            'pre_tags' => '<em>',
            'post_tags' => '</em>',
            'fields' => ['title'=>new \stdClass(),'content'=>new \stdClass()]
         ])
         ->limit(100);
      // build and execute the query
      $command = $query->createCommand();
      $rows = $command->search(); // this way you get the raw output of elasticsearch.
      print_r($rows);
 使用Command来创建删除索引
use yii\elasticsearch\Command;
//Elasticsearch集群可以包含多个索引(indices)(数据库),每一个索引可以包含多个类型(types)(表),每一个类型包含多个文档(documents)(行),然后每个文档包含多个字段(Fields)(列)。
      $cmd=new Command();
      $db = Yii::$app->get('elasticsearch');
      $cmd->db=$db;
      $Mapping=["news"=>
         ["properties"=>[
            'id' => array('type' => 'long'),
            'title' => array('type' => 'string', 'analyzer'=>'ik', 'searchAnalyzer' => 'ik'),
            'content'  => array('type' => 'string', 'analyzer'=>'ik', 'searchAnalyzer' => 'ik'),
            'url'  => array('type' => 'string'),
            'updatetime' => array('type' => 'long'),
         ]]
      ];
//    $cmd->indexExists('myweb');//判断是否有对应索引
//    $cmd->typeExists('myweb','news');//判断是否有对应类型

      print_r($cmd->createIndex('myweb'),[
      'settings' => [ 'index' => ['refresh_interval' => '1s'] ],
            'mappings' => $Mapping,
        ]);//创建节点索引 deleteIndex 删除
      //exit;
      //print_r($cmd->closeIndex('myweb'));//关掉索引
      //根据map插入索引
      //cmd insert
      $posts = YII::$app->db->createCommand('SELECT * FROM news order by updatetime desc limit 1000')->queryAll();
      foreach ($posts as $rows) {//查询新闻插入
         print_r($cmd->insert('myweb', 'news',
            [
               'id' => $rows['contentid'],
               'title' => $rows['title'],
               'content' => $rows['description'],
               'url' => $rows['url'],
               'updatetime' => $rows['updatetime'],
            ],null, ['op_type' => 'create']
         ));
      }

      //cmd update
/*    print_r($cmd->update('myweb', 'news',1000,
         [
            'id'=>'1',
            'title' => '测试1',
         ]
      ));*/

      //exit;

也可以使用ActiveRecord 这里就不介绍了
作者:与您分享电脑世界
NetPc.com.cn
原文地址:Yii2使用composer安装Elasticsearch扩展和简单使用, 感谢原作者分享。

发表评论