加快在 1000000 条活动记录上花费 2 秒的查询速度,也在 PostgreSQL Sql
speed up the query which is taking 2 seconds on 1000000 on active records also on PostgreSQL Sql
我正在参数旁边的服务器端创建一个动态查询。但是,我的查询需要 2 秒来获取记录。我正在通过活动记录传递查询让我共享查询和活动记录 rails 代码
SELECT (custom_attribute_values.attributable_id) 从 custom_attribute_values WHERE (("custom_attribute_id" = '12' AND "value_string" = 'Female') OR ("custom_attribute_id" = '12' AND "value_string" = 'Male')) INTERSECT SELECT custom_attribute_values.attributable_id FROM custom_attribute_values WHERE (("custom_attribute_id" = '17' AND "value_string" = 'Widowed') 或 ("custom_attribute_id" = '17' AND "value_string" = 'Divorced') 或 ("custom_attribute_id" = '17' AND "value_string" = 'Never married') 或 ("custom_attribute_id" = '17 ' AND "value_string" = 'Married') OR ("custom_attribute_id" = '17' AND "value_string" = 'Separated'))
这是 Postgres 花费的时间 SQL
def fetch_members
begin
@filter_result = CustomAttributeValue.find_by_sql(segmentation_query).size
rescue Exception => e
render_json_response(response, @success, e.message, e)
end
end
以上是Rails代码
你知道如何加速我的查询吗?我已经厌倦了索引,但在我的情况下,索引是非常昂贵的操作
首先我可能会尝试这样的事情:
SELECT DISTINCT a.attributable_id FROM custom_attribute_values a
where custom_attribute_id = '12'
and value_string IN ('Female', 'Male')
and EXISTS(
SELECT 1 FROM custom_attribute_values b
where custom_attribute_id = '17'
and value_string IN ('Widowed', 'Divorced', 'Never married', 'Married', 'Separated')
and b.attributable_id = a.attributable_id
)
(可能有一些错误我没有尝试执行查询,但它应该给你一个想法)
但正如 Frank Heikens 在对问题的评论中所说,我们需要更多信息。
我正在参数旁边的服务器端创建一个动态查询。但是,我的查询需要 2 秒来获取记录。我正在通过活动记录传递查询让我共享查询和活动记录 rails 代码
SELECT (custom_attribute_values.attributable_id) 从 custom_attribute_values WHERE (("custom_attribute_id" = '12' AND "value_string" = 'Female') OR ("custom_attribute_id" = '12' AND "value_string" = 'Male')) INTERSECT SELECT custom_attribute_values.attributable_id FROM custom_attribute_values WHERE (("custom_attribute_id" = '17' AND "value_string" = 'Widowed') 或 ("custom_attribute_id" = '17' AND "value_string" = 'Divorced') 或 ("custom_attribute_id" = '17' AND "value_string" = 'Never married') 或 ("custom_attribute_id" = '17 ' AND "value_string" = 'Married') OR ("custom_attribute_id" = '17' AND "value_string" = 'Separated'))
这是 Postgres 花费的时间 SQL
def fetch_members
begin
@filter_result = CustomAttributeValue.find_by_sql(segmentation_query).size
rescue Exception => e
render_json_response(response, @success, e.message, e)
end
end
以上是Rails代码
你知道如何加速我的查询吗?我已经厌倦了索引,但在我的情况下,索引是非常昂贵的操作
首先我可能会尝试这样的事情:
SELECT DISTINCT a.attributable_id FROM custom_attribute_values a
where custom_attribute_id = '12'
and value_string IN ('Female', 'Male')
and EXISTS(
SELECT 1 FROM custom_attribute_values b
where custom_attribute_id = '17'
and value_string IN ('Widowed', 'Divorced', 'Never married', 'Married', 'Separated')
and b.attributable_id = a.attributable_id
)
(可能有一些错误我没有尝试执行查询,但它应该给你一个想法)
但正如 Frank Heikens 在对问题的评论中所说,我们需要更多信息。