Postgresql gin不能在联接中的两列上同时使用
我有两个表,Postgresql gin不能在联接中的两列上同时使用,postgresql,postgresql-9.4,Postgresql,Postgresql 9.4,我有两个表,products和products\u name 我在两个表中使用GIN索引在两列中进行ILIKE匹配,但只有在一列中进行ILIKE匹配时,才会使用GIN 我通过使用UNION来解决问题,但我想知道为什么它不能像我认为的那样工作 两列,n.name和e.producer都是VARCHAR,上面都有GIN索引: CREATE INDEX products_producer_gin_idx ON products USING gin (producer gin_trgm_ops); CR
products
和products\u name
我在两个表中使用GIN索引在两列中进行ILIKE
匹配,但只有在一列中进行ILIKE
匹配时,才会使用GIN
我通过使用UNION来解决问题,但我想知道为什么它不能像我认为的那样工作
两列,n.name
和e.producer
都是VARCHAR,上面都有GIN索引:
CREATE INDEX products_producer_gin_idx ON products USING gin (producer gin_trgm_ops);
CREATE INDEX products_names_name_gin_idx ON products_names USING gin (name gin_trgm_ops);
使用JOIN和ILIKE选择不使用GIN的:
在使用GIN的单列n.name上选择:
这些只是一种变通办法。你可以通过这个来推动postgres做索引
SELECT * from
(SELECT n.name, e.producer
FROM products e
INNER JOIN products_names n ON
n.product_id = e.product_id) a
WHERE
name ilike '%eda%' or producer ilike '%eda%'
编辑-或者试试这个
那对我根本不起作用。它没有使用GIN,速度甚至慢得多(3秒),可能是因为内部选择基本上是将表与所有内容连接在一起,然后ILIKE进行过滤。你能试试第二个方法吗。第二个方法很有效,这是一个好主意,但它提供了错误的结果,因为内部选择按名称过滤,而生产者完全被忽略。如果没有“eda”的制作人,则不会返回任何不正确的内容抱歉,是“或”,我认为是“和”,因此与工会合作是一个好的选择。试着在这里问一下。你会得到一个更好的解决方案,可能是重复的
testdb=# explain (analyze, verbose)
SELECT n.name, e.producer
FROM products e
INNER JOIN products_names n ON
n.product_id = e.product_id
WHERE
n.name ilike '%eda%'
limit 20;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=58.34..260.70 rows=20 width=60) (actual time=0.257..0.458 rows=20 loops=1)
Output: n.name, e.producer
-> Nested Loop (cost=58.34..49564.37 rows=4893 width=60) (actual time=0.256..0.454 rows=20 loops=1)
Output: n.name, e.producer
-> Bitmap Heap Scan on public.products_names n (cost=57.92..14890.29 rows=4893 width=39) (actual time=0.245..0.333 rows=20 loops=1)
Output: n.product_id, n.lang, n.name, n.name2, n.name3, n.products
Recheck Cond: ((n.name)::text ~~* '%eda%'::text)
Heap Blocks: exact=18
-> Bitmap Index Scan on products_names_name_gin_idx (cost=0.00..56.70 rows=4893 width=0) (actual time=0.160..0.160 rows=797 loops=1)
Index Cond: ((n.name)::text ~~* '%eda%'::text)
-> Index Scan using products_pkey on public.products e (cost=0.42..7.08 rows=1 width=29) (actual time=0.005..0.006 rows=1 loops=20)
Output: e.producer, e.product_id
Index Cond: (e.product_id = n.product_id)
Planning time: 1.000 ms
Execution time: 0.494 ms
(15 Zeilen)
Zeit: 2,563 ms
SELECT * from
(SELECT n.name, e.producer
FROM products e
INNER JOIN products_names n ON
n.product_id = e.product_id) a
WHERE
name ilike '%eda%' or producer ilike '%eda%'
SELECT * FROM
(SELECT n.name, e.producer
FROM products e
INNER JOIN products_names n ON
n.product_id = e.product_id
WHERE
n.name ilike '%eda%' )a
WHERE a.producer ilike '%eda%'