2016-07-25 74 views
1

我有一个查询,表现不佳,数据是hstore列:如何获得一个hstore查询来搜索多个词来使用索引?

SELECT "vouchers".* FROM "vouchers" WHERE "vouchers"."type" IN ('VoucherType') AND ((data -> 'giver_id')::integer = 1) AND ((data -> 'recipient_email') is NULL)

我试着加入以下指标:

CREATE INDEX free_boxes_recipient ON vouchers USING gin ((data->'recipient_email')) WHERE ((data->'recipient_email') IS NULL);

CREATE INDEX voucher_type_giver ON vouchers USING gin ((data->'giver_id')::int)

除了作为总体指数:CREATE INDEX voucher_type_data ON vouchers USING gin (data)

下面是当前查询计划:

Seq Scan on vouchers (cost=0.00..15158.70 rows=5 width=125) (actual time=122.818..122.818 rows=0 loops=1) 
    Filter: (((data -> 'recipient_email'::text) IS NULL) AND ((type)::text = 'VoucherType'::text) AND (((data -> 'giver_id'::text))::integer = 1)) 
    Rows Removed by Filter: 335148 
Planning time: 0.196 ms 
Execution time: 122.860 ms 

我如何索引此hstore列得到它下降到一个比较合理的查询?

+0

'((数据 - > 'RECIPIENT_EMAIL')IS NULL' - 这是一样的' NOT(data?'recipient_email')'在你的上下文中吗?替代是否改进了任何东西? –

+0

哦,没关系,我没有在这里看到关键的GIN索引,所以我匆忙得出结论。认为GIN在这里特别有用,因为你索引**一个字符串**。尝试一个普通的旧B树而不是? –

+0

“通过过滤器删除的行”大约是330k。表中有多少行?如果这是行只有1%的表格,这是一个很大的差异erence。 ;)还... 0.12秒正在执行中?此查询每秒运行多少次?尽管如此,+1。好问题(至少在我看来)。 – jpmc26

回答

1

对于the documentation

hstore有依据和GIN索引支持@>,? &和?|运营商。

您正在寻找一个整数值,所以你可以使用简单的B树索引是这样的:

CREATE INDEX ON vouchers (((data->'giver_id')::int)); 

EXPLAIN ANALYSE 
SELECT * 
FROM vouchers 
WHERE vtype IN ('VoucherType') 
AND (data -> 'giver_id')::integer = 1 
AND (data -> 'recipient_email') is NULL; 

                 QUERY PLAN               
---------------------------------------------------------------------------------------------------------------------------- 
Bitmap Heap Scan on vouchers (cost=4.66..82.19 rows=1 width=34) (actual time=0.750..0.858 rows=95 loops=1) 
    Recheck Cond: (((data -> 'giver_id'::text))::integer = 1) 
    Filter: (((data -> 'recipient_email'::text) IS NULL) AND (vtype = 'VoucherType'::text)) 
    Heap Blocks: exact=62 
    -> Bitmap Index Scan on vouchers_int4_idx (cost=0.00..4.66 rows=50 width=0) (actual time=0.018..0.018 rows=95 loops=1) 
     Index Cond: (((data -> 'giver_id'::text))::integer = 1) 
Planning time: 2.115 ms 
Execution time: 0.896 ms 
(8 rows) 
+0

啊完美,谢谢! –

相关问题