简体   繁体   English

针对postgres中的视图的查询非常慢-可以增强吗?

[英]Very slow query against view in postgres - possible to enhance?

I have a postgres DB with some million entries (and growing fast). 我有一个Postgres数据库,其中有大约一百万个条目(并且正在快速增长)。 I've created a view of that DB where some of the columns of each row is concatenated and aggreagated (in this format): 我已经创建了该数据库的视图,其中每一行的某些列是连接在一起的(并以这种格式):

concat         | count
david55single    5

What I'm doing is getting a string in this format, and I check the view if that exact string is in the view, and what the count is. 我正在做的是获取这种格式的字符串,然后检查视图中该字符串是否在视图中以及计数是多少。 This is my query: 这是我的查询:

SELECT count from concatview WHERE concat = '<somestring>'; 

This query takes a really long time, which is bad since we do this query on each request from a user. 此查询会花费很长时间,这很糟糕,因为我们对用户的每个请求都执行此查询。 Is there any way to enhance the time of the query? 有什么方法可以延长查询时间? From what I've understood from the documentation it's only possible to index materialized view? 根据我从文档中了解到的,只能对物化视图编制索引? Do I need to create a materialized view instead and refresh the view quite often, or is there any other ways to enhance the regular view? 我是否需要创建实例化视图并经常刷新视图,或者是否有其他方法可以增强常规视图?

 create index on mytab(col1||col2||col3)

being certain to use the same exact syntax on the index as you do in the view. 确保在索引上使用与视图相同的语法。 If you're using the concat() function to do your concatenation, you'll need to create an IMMUTABLE version of concat() (immutable means that given the same input, it always returns the same output, and the standard concat is not marked immutable, but in many use cases it can safely be wrapped in an immutable function). 如果您使用concat()函数进行串联,则需要创建IMMUTABLE版本的concat()(不可变表示在给定相同输入的情况下,它始终返回相同的输出,而标准concat则不是)标记为不可变的,但是在很多情况下,可以安全地将其包装为不可变的函数)。 This will allow queries against the view to utilize the index. 这将允许对视图的查询利用索引。

Note: the || 注意:|| concatenation operator won't play well if ANY of the columns are nullable. 如果任何列可为空,则串联运算符将不能很好地发挥作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM