首页 > 解决方案 > 如何优化 Sequelize 查询?

问题描述

Sequelize 正在运行简单查询,它占用了 35 毫秒以上。

我试过优化查询,因为 phpMyAdmin 占用了 0.4 毫秒。我知道 - Sequelize 有 ORM,但它不能花费 34.6 毫秒。

MySql 表有 16 行 12 列。phpMyAdmin 查询:

SELECT `is_paid`, `page` FROM `i_items_pages` AS `ItemPage` WHERE `ItemPage`.`item_id` = 1 AND `ItemPage`.`page` = 1

它花了0.4毫秒。item_id 和 page 是索引。

节点应用:

服务器.js

mysql = require('./app/models')
global.sqlCon = mysql

ItemPageRepository.js

async findAll() { 
        try {

            const start = performance.now()
            const result = await sqlCon 
                .ItemPage 
                .findAll({
                    where: this._whereClause(),
                    attributes: [
                        'is_paid',
                        'page'
                    ]
                })
                const total = performance.now() - start
                console.log(`rep blocked for ${total}.`)
            return result
        } catch(e) {
            logger.error( e)
            this._next()
        }
    }

_whereClause(){
        if (this._isFullArticle) {
            return {
                item_id: this._articleId
            }
        } else {
            return {
                item_id: this._articleId,
                page: this._pageId
            }
        }

    }

耗时 35 毫秒

项目页面.js

module.exports = (sequelize, DataTypes) => {
  const ItemPage = sequelize.define('ItemPage', {
    id: {
      type: DataTypes.BIGINT(15),
      primaryKey: true,
      autoIncrement: true
    },
    item_id: {
        type: DataTypes.BIGINT(15),
        allowNull: false
    }, 
    page: {
        type: DataTypes.INTEGER(10),
        allowNull: true
    }, 
    title: {
        type: DataTypes.TEXT,
        allowNull: false
    }, 
    article: {
        type: DataTypes.TEXT,
        allowNull: false
    }, 
    is_published: {
        type: DataTypes.INTEGER(1),
        allowNull: false
    }, 
    is_paid: {
        type: DataTypes.INTEGER(1),
        defaultValue: 0
    }, 
    reads: {
        type: DataTypes.INTEGER(10),
        defaultValue: 0
    }, 
    views: {
        type: DataTypes.INTEGER(10),
        defaultValue: 0
    },
    user_id: {
        type: DataTypes.INTEGER(10),
        allowNull: true
    }
  }, {
    underscored: true, 
    tableName: 'i_items_pages'
  })

  ItemPage.associate = (models) => {
    ItemPage.belongsTo(models.Item)
}

  return ItemPage
}

我预计会得到大约 10 毫秒,但实际输出是 35 毫秒 - 47 毫秒。

标签: node.jsperformancesequelize.js

解决方案


推荐阅读