fecmall 的 service 层,如何创建mongodb索引,用于提高mongodb数据查询效率
mongodb可以直接在mongodb数据库里面进行直接创建索引,也可以在fecmall代码里面创建,首先,先看一下,fecmall的mongodb的表的索引是怎么创建的
1.migrate部分:https://github.com/fecshop/yii2_fecshop/blob/master/migrations/mongodb/m170228_072455_fecshop_tables.php
<?php class m170228_072455_fecshop_tables extends \yii\mongodb\Migration { public function up() { \fecshop\models\mongodb\Product::create_index(); \fecshop\models\mongodb\cms\Article::create_index(); \fecshop\models\mongodb\cms\StaticBlock::create_index(); \fecshop\models\mongodb\customer\Newsletter::create_index(); \fecshop\models\mongodb\product\Favorite::create_index(); \fecshop\models\mongodb\product\Review::create_index(); \fecshop\models\mongodb\url\UrlRewrite::create_index(); } public function down() { echo "m170228_072455_fecshop_tables cannot be reverted.\n"; return false; } }
以\fecshop\models\mongodb\Product::create_index();为例子
\fecshop\models\mongodb\Product::create_index();
打开这个文件:https://github.com/fecshop/yii2_fecshop/blob/master/models/mongodb/Product.php#L130
/** * 给model对应的表创建索引的方法 * 在indexs数组中填写索引,如果有多个索引,可以填写多行 * 在migrate的时候会运行创建索引,譬如: * @fecshop/migrations/mongodb/m170228_072455_fecshop_tables */ public static function create_index() { $indexs = [ ['spu' => -1], ['sku' => -1], ['category' => -1,'score' => 1], ['category' => -1,'review_count' => 1], ['category' => -1,'favorite_count' => 1], ['category' => -1,'created_at' => 1], ['category' => -1,'final_price' => 1], ]; $options = ['background' => true]; foreach ($indexs as $columns) { self::getCollection()->createIndex($columns, $options); } }
您可以照葫芦画瓢自己写一下
大佬,fecmall 的 service 层查询数据,如何才能知道是否使用了mongodb的索引
自己研究下mongodb数据库吧
public function coll($filter = '') { $model = $this->_infoModel; $query = $model->find(); $query = Yii::$service->helper->ar->getCollByFilter($query, $filter); return [ 'coll' => $query->all(), 'count'=> $query->limit(null)->offset(null)->count(), 'explain' => $model->getCollection()->explain([]) ]; }
$model->getCollection()->explain([]) 如何使用explain命令来查看查询语句的执行情况, 我这样使用报错了,,Calling unknown method: yii\mongodb\Collection::explain(),,,找不到方法,,大佬指点下,
看了一下,yii2-mongodb文档 https://www.yiiframework.com/extension/yiisoft/yii2-mongodb/doc/api/2.1/yii-mongodb-debug-explainaction#explainQuery()-detail ,,我不太会看yii的相关文档,,,文档中说的 explainQuery() 方法,,在上面的coll()方法中,如何使用