Using Levenshtein function on each element in a tsvector?

守給你的承諾、 提交于 2019-12-21 06:12:13

问题


I'm trying to create a fuzzy search using Postgres and have been using django-watson as a base search engine to work off of.

I have a field called search_tsv that its a tsvector containing all the field values of the model that I want to search on.

I was wanting to use the Levenshtein function, which does exactly what I want on a text field. However, I dont really know how to run it on each individual element of the tsvector.

Is there a way to do this?


回答1:


I would consider using the extension pg_trgm instead of levenshtein(). It is several orders of magnitude faster if you back it up with a GiST index, that can make use of the new KNN feature in PostgreSQL 9.1.

Install the extension once per database:

CREATE EXTENSION pg_trgm;

And make use of the <-> or % operator, or the similarity() function. Several good answers have been posted on SO already, Search for pg_tgrm [PostgreSQL] ...


Wild shot at what you may want:

WITH x AS (
    SELECT unnest(string_to_array(trim(strip(
      'fat:2,4 cat:3 rat:5A'::tsvector)::text, ''''), ''' ''')) AS val
    )                                    -- provide ts_vector, extract strings
    , y AS( SELECT 'brat'::text AS term) -- provide term to match
SELECT val, term
      ,(val <-> term) AS trg_dist        -- distance operator
      ,levenshtein(val, term) AS lev_dist
FROM   x, y;

Returns:

 val | term | trg_dist | lev_dist
-----+------+----------+----------
 cat | brat |    0.875 |        2
 fat | brat |    0.875 |        2
 rat | brat | 0.714286 |        1


来源:https://stackoverflow.com/questions/12100983/using-levenshtein-function-on-each-element-in-a-tsvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!