Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1egejv-0003mK-Nx for pgsql-general@arkaria.postgresql.org; Tue, 30 Jan 2018 22:50:56 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1egeju-0001GX-6z for pgsql-general@arkaria.postgresql.org; Tue, 30 Jan 2018 22:50:54 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1egejt-0001GO-TK for pgsql-general@lists.postgresql.org; Tue, 30 Jan 2018 22:50:54 +0000 Received: from mail.postgrespro.ru ([93.174.131.138]) by magus.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1egejo-0005Ep-V1 for pgsql-general@lists.postgresql.org; Tue, 30 Jan 2018 22:50:53 +0000 Received: from localhost (localhost [127.0.0.1]) by mail.postgrespro.ru (Postfix) with ESMTP id 811A021C1C4F for ; Wed, 31 Jan 2018 01:50:47 +0300 (MSK) X-Virus-Scanned: Debian amavisd-new at postgrespro.ru X-Spam-Flag: NO X-Spam-Score: 0 X-Spam-Level: X-Spam-Status: No, score=x tagged_above=-99 required=4 WHITELISTED tests=[] autolearn=unavailable Received: from [192.168.1.142] (ppp109-252-62-9.pppoe.spdop.ru [109.252.62.9]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (Client did not present a certificate) by mail.postgrespro.ru (Postfix) with ESMTPSA id 4DD5B21C1C34 for ; Wed, 31 Jan 2018 01:50:47 +0300 (MSK) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=postgrespro.ru; s=mail; t=1517352647; bh=wllYni7XUh7Ru62EVkK12Pa0l8cYqsO5FfYqCANJ/zE=; h=Subject:To:References:From:Date:In-Reply-To; b=hRXKztXy7uH8A1Kx7wnA+ABP4iEVrVNcFRcBMRu5dtOKTZJ91Mks/qDMdNhrkmFl9 zeyEnetpT3pk3WzdvG76pAV6n36Tr2kumWdziLF8DOsE37SrQzUknYLQY6LWjSofdq a+ipUX1xbXm86fr1ON3/otcHcRW3NEegeOVP9+ZI= Subject: Re: How to Optimize pg_trgm Performance To: pgsql-general@lists.postgresql.org References: <0676f27e-118b-892b-f44d-c60ab13eb37c@lucee.org> From: "Ivan E. Panchenko" Message-ID: Date: Wed, 31 Jan 2018 01:50:46 +0300 User-Agent: Mozilla/5.0 (X11; Linux i686; rv:52.0) Gecko/20100101 Thunderbird/52.5.0 MIME-Version: 1.0 In-Reply-To: <0676f27e-118b-892b-f44d-c60ab13eb37c@lucee.org> Content-Type: multipart/alternative; boundary="------------9D39D3E02E79C4AFD474B502" Content-Language: en-US List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk This is a multi-part message in MIME format. --------------9D39D3E02E79C4AFD474B502 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Hi Igal, 29.01.2018 02:42, Igal @ Lucee.org пишет: > > I want to use pg_trgm for auto-suggest functionality.  I created a > Materialized View with the information that I need, with the relevant > columns being (keywords text, rank int). keywords is the column from > which I build the tri-grams, and rank is some popularity factor so > that popular results will show up higher than less popular results > given the same tri-gram distance. > > I want to return results in the order of [distance], [distance_word], > [rank].  The input comes from the user and is not known in advance.  > My query is as follows: > >     SELECT title >         ,id >         ,(input <-> keywords) AS distance >         ,(input <<-> keywords) AS distance_word >         ,rank >     FROM  (VALUES (cast('red pill' AS text))) consts(input) >         ,mv_autosuggest >     ORDER BY 3, 4, 5 >     LIMIT 20; > > This gives me pretty good results, but it takes too long and is not > likely to scale well. > > I have created two indexes but neither seem to be used: > > CREATE INDEX mv_autosuggest_keywords_tgrm_gist ON > staging.mv_autosuggest USING gist (keywords gist_trgm_ops); > > CREATE INDEX mv_autosuggest_keywords_tgrm_gin ON > staging.mv_autosuggest USING gin (keywords gin_trgm_ops); > > This is the result of explain analyze: > > QUERY PLAN | > -------------------------------------------------------------------------------------------------------------------------------------------| > Limit  (cost=356.41..356.46 rows=20 width=51) (actual > time=163.132..163.135 rows=20 > loops=1)                                               | >   ->  Sort  (cost=356.41..372.96 rows=6619 width=51) (actual > time=163.130..163.131 rows=20 > loops=1)                                        | >         Sort Key: (('red pill'::text <-> mv_autosuggest.keywords)), > (('red pill'::text <<-> mv_autosuggest.keywords)), mv_autosuggest.rank | >         Sort Method: top-N heapsort  Memory: 28kB | >         ->  Seq Scan on mv_autosuggest  (cost=0.00..180.29 rows=6619 > width=51) (actual time=0.263..161.289 rows=6619 loops=1)              | > Planning time: 0.139 ms | > Execution time: 163.174 ms | > > How can I improve the performance here? > This can be improved if you use sort only by distances (try ORDER BY 3,4 or ORDER BY 3 or ORDER BY 4 Than you should get  plan  like Index Scan using mv_autosuggest_keywords_tgrm_gist on mv_autosuggest          Order By: ((keywords <-> 'red pill'::text) AND (keywords <->> 'red pill'::text)) Which means that KNN  index search is enabled : http://www.sai.msu.su/~megera/postgres/talks/pgcon-2010-1.pdf If you want to sort it also by rank, you can make a two-level construction like: SELECT * FROM (    SELECT .... ORDER BY 3,4 LIMIT ....  /* make some empirical redundant limit here */ ) foo ORDER BY 5 LIMIT .... Regards, Ivan Panchenko > Thank you, > > Igal Sapir > Lucee Core Developer > Lucee.org > --------------9D39D3E02E79C4AFD474B502 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: 8bit

Hi Igal,

29.01.2018 02:42, Igal @ Lucee.org пишет:

I want to use pg_trgm for auto-suggest functionality.  I created a Materialized View with the information that I need, with the relevant columns being (keywords text, rank int).  keywords is the column from which I build the tri-grams, and rank is some popularity factor so that popular results will show up higher than less popular results given the same tri-gram distance.

I want to return results in the order of [distance], [distance_word], [rank].  The input comes from the user and is not known in advance.  My query is as follows:

    SELECT title
        ,id
        ,(input <-> keywords) AS distance
        ,(input <<-> keywords) AS distance_word
        ,rank
    FROM  (VALUES (cast('red pill' AS text))) consts(input)
        ,mv_autosuggest
    ORDER BY 3, 4, 5
    LIMIT 20;

This gives me pretty good results, but it takes too long and is not likely to scale well.

I have created two indexes but neither seem to be used:

CREATE INDEX mv_autosuggest_keywords_tgrm_gist ON staging.mv_autosuggest USING gist (keywords gist_trgm_ops);

CREATE INDEX mv_autosuggest_keywords_tgrm_gin ON staging.mv_autosuggest USING gin (keywords gin_trgm_ops);

This is the result of explain analyze:

QUERY PLAN                                                                                                                                 |
-------------------------------------------------------------------------------------------------------------------------------------------|
Limit  (cost=356.41..356.46 rows=20 width=51) (actual time=163.132..163.135 rows=20 loops=1)                                               |
  ->  Sort  (cost=356.41..372.96 rows=6619 width=51) (actual time=163.130..163.131 rows=20 loops=1)                                        |
        Sort Key: (('red pill'::text <-> mv_autosuggest.keywords)), (('red pill'::text <<-> mv_autosuggest.keywords)), mv_autosuggest.rank |
        Sort Method: top-N heapsort  Memory: 28kB                                                                                          |
        ->  Seq Scan on mv_autosuggest  (cost=0.00..180.29 rows=6619 width=51) (actual time=0.263..161.289 rows=6619 loops=1)              |
Planning time: 0.139 ms                                                                                                                    |
Execution time: 163.174 ms                                                                                                                 |

How can I improve the performance here?

This can be improved if you use sort only by distances
(try ORDER BY 3,4
or ORDER BY 3
or ORDER BY 4

Than you should get  plan  like

Index Scan using mv_autosuggest_keywords_tgrm_gist on mv_autosuggest 
         Order By: ((keywords <-> 'red pill'::text) AND (keywords <->> 'red pill'::text))

Which means that KNN  index search is enabled : http://www.sai.msu.su/~megera/postgres/talks/pgcon-2010-1.pdf

If you want to sort it also by rank, you can make a two-level construction like:

SELECT * FROM (
   SELECT .... ORDER BY 3,4 LIMIT ....  /* make some empirical redundant limit here */
) foo ORDER BY 5 LIMIT ....


Regards,
Ivan Panchenko




Thank you,

Igal Sapir
Lucee Core Developer
Lucee.org


--------------9D39D3E02E79C4AFD474B502--