簡體   English   中英

為什么 PostgreSQL 不使用我的 gin_trgm_ops 索引來加速這個查詢?

[英]Why won't PostgreSQL use my gin_trgm_ops index to accelerate this query?

我在 Postgres 中使用 trigram 相似性來幫助我靈活地搜索數據庫中的名稱,並且(更重要的是)從自然語言句子中提取名稱並將它們與數據庫記錄匹配。

使用此查詢,我得到了第一個可靠地工作並且快速完成的任務:

SELECT *, similarity(name_column, 'name im searching for') AS sim
FROM table_with_names
WHERE name_column % 'name im searching for'
ORDER BY sim DESC
LIMIT 5;   

上面的查詢利用了name_column上的索引,該索引是用這個語句創建的:

CREATE INDEX name_sim_idx ON table_with_names USING GIN (name_column gin_trgm_ops);

我的其他任務(從完整的句子中靈活地提取名稱匹配)讓我感到沮喪。 似乎包含similarity() function 的pg_trgm 模塊也有一個word_similarity() function ,它完全符合我的需要。 事實上,我用這個查詢完成了任務:

SELECT *, word_similarity(name_column, 'sentence including the name im searching for') AS sim
FROM table_with_names
WHERE name_column <% 'sentence including the name im searching for'
ORDER BY sim DESC
LIMIT 5;   

然而。 雖然我列出的第一個查詢(相似性查找,而不是提取)非常快(1 毫秒),但第二個查詢在 ~350 毫秒時非常慢,並且不會使用我的 index

我不明白為什么第二個查詢不會使用我的 trgm 索引。 我嘗試使用SET enable_seqscan = off; ,但這不起作用。 據我所知,Postgres 的文檔聲稱,如果您想使用索引來加速word_similarity()查詢,則此<%運算符是正確的運算符,但他們的所有示例都以相反的方向使用它。

例如,文檔顯示:

WHERE 'search text' <% column

而我需要做相反的事情:

WHERE column <% 'search text

我想用 trgm 相似性做些什么? 或者我在這里旋轉我的輪子。 我無法想象為什么我的索引不能在這里使用。 這對我來說是 0 意義。 希望有人能幫我解決這個問題。 提前致謝。

編輯:這是 a_horse_with_no_name 建議的執行計划

Limit  (cost=10000000538.89..10000000538.90 rows=5 width=114) (actual time=349.292..349.295 rows=0 loops=1)
  Buffers: shared hit=407
  ->  Sort  (cost=10000000538.89..10000000538.91 rows=11 width=114) (actual time=349.290..349.292 rows=0 loops=1)
        Sort Key: (word_similarity(full_name, 'this is the sentence that contains the name i am trying to extract'::text)) DESC, period_start DESC
        Sort Method: quicksort  Memory: 25kB
        Buffers: shared hit=407
        ->  Seq Scan on patient_matching_lookup_v1  (cost=10000000000.00..10000000538.70 rows=11 width=114) (actual time=349.280..349.281 rows=0 loops=1)
              Filter: (full_name <% 'this is the sentence that contains the name i am trying to extract'::text)
              Rows Removed by Filter: 10534
              Buffers: shared hit=407
Planning Time: 0.172 ms
Execution Time: 349.335 ms

三元組索引將支持條件'constant' <% indexed_col ,但不indexed_col <% 'constant'

暫無
暫無

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

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