如何优化Sequelize查询?

时间:2019-03-28 08:19:33

标签: node.js performance sequelize.js

Sequelize运行简单的查询,耗时35ms。

我尝试优化查询,因为phpMyAdmin花费了0.4毫秒以上的时间。我知道-Sequelize具有ORM,但不能花34.6ms。

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是索引。

节点应用:

server.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毫秒

ItemPage.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
}

我希望能得到大约10ms,但实际输出是35ms-47ms。

0 个答案:

没有答案