尽管在where子句的列上存在索引,但活动记录查找也会间歇性地缓慢进行

问题描述 投票:0回答:1

我有一个简单的新API端点,它涉及查询我的新设置和填充的表-库存产品。

库存产品表的模式是:

CREATE TABLE `inventory_products` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `inventory_product_id` binary(16) DEFAULT NULL,
  `product_id` binary(16) DEFAULT NULL,
  `status` enum('ACTIVE','INACTIVE','DELETED') DEFAULT 'ACTIVE',
  `priority` int(11) DEFAULT '0',
  `inventory_service_id` tinyint(3) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_inventory_product_id` (`inventory_product_id`),
  KEY `idx_product_status` (`product_id`,`status`)
) ENGINE=InnoDB AUTO_INCREMENT=76312817 DEFAULT CHARSET=utf8;

API端点主要执行以下操作:

def lookup_inventory_service_id
    return render_error_response(AUTH_ERROR, {status: 403}) unless client.name == PERMITTED_NAME

    ip_fetch_start = Time.now
    inventory_product = InventoryProducts.find_by_inventory_product_id(resource_attributes[:inventory_product_id])
    Rails.logger.info({inventory_product_id: resource_attributes[:inventory_product_id], inventory_product_fetch_time_ms: (Time.now - ip_fetch_start)*1000}.as_json)
    return head :not_found unless inventory_product
....

问题:库存产品查询(find_by_inventory_product_id)是Rails的ActiveRecord提供的标准功能(我没有在模型中覆盖它)。此功能从10毫秒到有时甚至是650毫秒(可从我添加的日志中找到)。尽管在查询中使用的列上存在Mysql索引,为什么在某些情况下这会占用很多时间而在其他情况下却占用更少的时间呢?

我已经在我的模式中提到了stock_product_id作为唯一键,并且由上述函数触发的MySQL查询正在使用stock_product_id作为以下explain语句的索引。

解释选择inventory_products。*从inventory_productsinventory_productsinventory_product_id = 0x3a288cdce78d44618eadd72e240f26a4限制1

id select_type表的类型1 SIMPLE stock_products const uc_inventory_product_id uc_inventory_product_id 17 const 1 NULL

我的模式有问题吗?我是否需要在架构中明确提及stocking_product_id作为mysql索引?有点像

KEY `idx_product_status` (`product_id`,`status`)

非常感谢您的协助,因为我长期在这个问题上苦苦挣扎,无法找到解决方法。谢谢,提前!

我使用Mysql 5.6和rails-3.2.8。另外,我的rails应用程序在jruby(1.7.0)内的tomcat服务器(版本-Apache Tomcat / 7.0.16)上运行。

我有一个简单的新API端点,该端点涉及查询我新设置并填充的表-ventory_products。库存产品表的架构为:CREATE TABLE`库存产品'('...

mysql ruby-on-rails indexing rails-activerecord unique-constraint
1个回答
0
投票

我在架构文件中看不到索引(我认为是架构文件?),只是一个唯一的键引用

© www.soinside.com 2019 - 2024. All rights reserved.