PostgreSQL - 使 ts_rank 按原样获取 ts_vector 位置或定义自定义 ts_rank 函数

PostgreSQL - making ts_rank take the ts_vector position as-is or defining a custom ts_rank function

我正在对电子商务平台中的一系列商品执行加权搜索。我遇到的问题是 ts_rank 为不同的单词组合提供完全相同的值,即使 ts_vector 为每组单词提供不同的位置。

让我用一个例子来说明这一点:

如果我给 ts_vector 这个词 camas,它会给我以下内容:

'cam':1

如果我给 ts_vector 单词 sofas camas,它会给我以下内容:

'cam':2 'sof':1

因此 camas 根据单词组合获得不同的位置。

当我执行以下语句时:

select ts_rank(to_tsvector('camas'),to_tsquery('spanish','cama'));

PostgreSQL 给我 0.0607927 作为 ts_rank 计算值,而以下语句的计算值:

select ts_rank(to_tsvector('sofas camas'),to_tsquery('spanish','cama'));

是相同的值:0.0607927.

怎么会这样?

我想到的问题如下:ts_rank 是否有办法按原样考虑 ts_vector 结构中包含的单词的位置,或者是否有办法为我定义一个自定义 ts_rank 函数,按照解释的方式为单词定位?

如有任何帮助,我们将不胜感激。

正如 documentation 关于函数 ts_rankts_rank_cd:

they consider how often the query terms appear in the document, how close together the terms are in the document, and how important is the part of the document where they occur

就是这些函数在计算时忽略了其他单词。例如,您可以获得这些查询的不同结果:

postgres=# select ts_rank(to_tsvector('spanish', 'famoso sofas camas'),to_tsquery('spanish','famoso & cama'));
  ts_rank  
-----------
 0.0985009
(1 row)

postgres=# select ts_rank(to_tsvector('spanish', 'famoso camas'),to_tsquery('spanish','famoso & cama'));
  ts_rank  
-----------
 0.0991032
(1 row)

postgres=# select ts_rank(to_tsvector('spanish', 'sofas camas camas'),to_tsquery('spanish','cama'));
  ts_rank  
-----------
 0.0759909
(1 row)

文档还说:

Different applications might require additional information for ranking, e.g., document modification time. The built-in ranking functions are only examples. You can write your own ranking functions and/or combine their results with additional factors to fit your specific needs.

您可以从 GitHub 获取 PostgreSQL 代码。需要的函数是ts_rank_tt.

您还可以更改规范化选项以将其考虑到默认情况下被忽略的文档长度。

例如,如果您添加1作为第三个参数,它将排名除以1 + 文档长度的对数。以你的例子:

postgres=# select ts_rank(to_tsvector('spanish', 'camas'),to_tsquery('spanish','camas'), 1); 
  ts_rank  
-----------
 0.0607927
(1 row)

postgres=# select ts_rank(to_tsvector('spanish', 'sofas camas'),to_tsquery('spanish','camas'), 1); 
  ts_rank  
-----------
 0.0383559
(1 row)

文档:https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING