簡體   English   中英

正確的全文索引Rails / PostgreSQL / pg_search

[英]Proper full text index Rails/PostgreSQL/pg_search

我正在測試PostgreSQL全文搜索(使用pg_search gem)和solr(sunspot_solr gem)的性能。

對於400萬條記錄,我獲得了13456毫秒的Tsearch800毫秒的SOLR (即SOLR查詢+ DB回溯)。 很明顯,我需要索引,但我不知道如何創建一個全文搜索。 我調查並發現,對於全文搜索,我應該使用GIN索引。

execute "CREATE INDEX products_gin_title ON products USING GIN(to_tsvector('english', title))"

但我正在搜索另外兩列,我需要多值索引,我不知道如何實現它? 我對DB部分不是很熟悉。 我的搜索代碼如下:

@results = Product.search_title(params[:search_term]).where("platform_id=? AND product_type=?", params[:platform_id], params[:type_id]).limit(10).all

如何為此類情況創建正確的查詢?

這是來自rails的搜索詞車的 SQL輸出。

Product Load (12494.0ms)
SELECT 
    "products".*, 
    ( ts_rank((to_tsvector('simple', coalesce("products"."title"::text, ''))), (to_ tsquery('simple', ''' ' || 'car' || ' ''')), 2) ) AS pg_search_rank 
FROM "products" 
WHERE (((to_tsvector('simple', coalesce("products"."tit le"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'car' || ' ''')))) 
    AND (platform_id='26' AND product_type='2') 
ORDER BY pg_search_rank DESC, "products"."id" ASC 
LIMIT 10

編輯:

我正在使用PostgreSQL 8.4.11, EXPLAIN ANALYZE輸出如下。

Limit  (cost=108126.34..108126.36 rows=10 width=3824) (actual time=12228.736..12228.738 rows=10 loops=1)   
->  Sort (cost=108126.34..108163.84 rows=14999 width=3824) (actual time=12228.733..12228.734 rows=10 loops=1)
    Sort Key: (ts_rank(to_tsvector('simple'::regconfig, COALESCE((title)::text, ''::text)), '''car'''::tsquery, 2)), id
    Sort Method:  top-N heapsort  Memory: 18kB
    ->  Seq Scan on products  (cost=0.00..107802.22 rows=14999 width=3824) (actual time=7.532..12224.585 rows=977 loops=1)
        Filter: ((platform_id = 26) AND (product_type = 2) AND (to_tsvector('simple'::regconfig, COALESCE((title)::text, ''::text)) @@ '''car'''::tsquery)) 

Total runtime: 12228.813 ms

這個表達式:

to_tsvector('simple', (COALESCE(title::TEXT), ''))

不能對你的索引進行抨擊。

您應該在查詢中使用的表達式上聲明索引:

CREATE INDEX products_gin_title
ON products
USING GIN(to_tsvector('simple', COALESCE(title::TEXT,'')))

(或使ruby生成索引中使用的表達式)。

如果要將多列編入索引,只需將它們連接起來:

CREATE INDEX products_gin_title
ON products
USING GIN(to_tsvector('simple', title || ' ' || product_type || ' ' || platform_id))

但同樣,Ruby應該過濾完全相同的表達式,以便使用索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM