node.js - 如何优化 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 毫秒。
解决方案
推荐阅读
- sql - BigQuery SQL 将元数据添加到列
- linux - 通过 api 远程触发 jenkins 构建
- python - 由于下载失败,Virtualenv 停止工作
- python - 根据列的最小值获取行的更便宜的方法
- python - Selenium driver.execute_script("return window.pageYOffset;") 返回 0 即使它不是 0
- vmware - 当具有嵌套虚拟化的 ESXi 位于 KVM 之上时,无法安装 VMware vCenter 设备
- python - 比较字符串化的数值列表
- reactjs - react-router-dom(^5.3.0) -> redirect
- node.js - GRPC intermittent connection, read ECONNRESE error
- firebase - how to create query based on the result of another query using firestore flutter?