PostgreSQL查询优化,阅读EXPLAIN

时间:2017-08-24 15:50:12

标签: postgresql sql-execution-plan

我正在阅读对查询运行解释的输出。结果如下:https://explain.depesz.com/s/5EfR

我在第34行看到,数据库正在进行非常昂贵的索引扫描,导致删除单行。

我是否正确阅读?还有什么可能导致这种想法?

查询:

'ABC PQR XYZ'.split('').reduce((state, value) => {
    return value + state;
});

1 个答案:

答案 0 :(得分:1)

尝试在连接之前限制数据。您可以使用CTE,因为它们已实现一次,如果您愿意,可以像优化栅栏或临时表一样工作。

所以你的查询看起来像这样:

WITH cte_posts AS (
  select type, created, image_url, id as post_id, organization_id as id, url_id,
         ts_headline('english',
                     text,
                     to_tsquery('english', 'state'),
                     $$StartSel='<span class="text-highlight">',StopSel=</span>, HighlightAll=true$$) as text,
         ts_headline('english',
                     attachment_description,
                     to_tsquery('english', 'state'),
                     $$StartSel='<span class="text-highlight">',StopSel=</span>, HighlightAll=true$$) as attachment_description,
         ts_headline('english',
                     attachment_title,
                     to_tsquery('english', 'state'),
                     $$StartSel='<span class="text-highlight">',StopSel=</span>, HighlightAll=true$$) as attachment_title
  from vision2.posts15
  where Date(created) BETWEEN '2017-08-10' AND '2017-08-24'
  and Date(partition_date) BETWEEN '2017-08-10' AND '2017-08-24'
  AND chunks @@ to_tsquery('english', 'state') --is that column in posts15 table?
)
SELECT cte_posts.*, urls.image_url as url_image_url
FROM cte_posts
join vision2.organizations on organizations.id = cte_posts.id
left join vision2.urls on urls.id = cte_posts.url_id
      --you could try moving this WHERE to CTE as well, depending on your data
where string_to_array(upper(organizations.irs_state), '') && array['NJ']
order by cte_posts.created desc
offset 0
limit 40