如何通过postgres中的匹配次数获得最佳匹配产品

How to get best matching products by number of matches in postgres

Postgres 9.1 购物车包含产品 table

create table products (
  id char(30) primary key,
  name char(50),
  description text );

购物车有搜索栏。如果输入内容,自动完成下拉列表必须显示按符合此条件的产品数量订购的最佳匹配产品。

如何在 postgres 9.1 中实现这样的查询?应按产品中的名称和描述字段执行搜索 table。 使用子串匹配就足够了。不严格要求使用复杂的文本匹配进行全文搜索。

更新

word joote 可以是产品名称或描述的一部分。

例如,图片中的第一个匹配文本可能包含

.. See on jootetina ..

以及其他产品

Kasutatakse jootetina tegemiseks ..

还有一个大写

Jootetina on see ..

在这种情况下查询应该 return 字 jootetina 和匹配计数 3。 如何使它像在 Google Chrome 地址栏中输入搜索词时发生的 auotcomplete 一样工作?

如何实现?

或者如果这很困难,如何 return 单词 jootetina 形成所有与搜索词 joote 匹配的文本?

select word, count(distinct id) as total
from (
    select id,
        regexp_split_to_table(name || ' ' || description, E'\s+') as word
    from products
) s
where position(lower('joote') in lower(word)) > 0
group by word
order by 2 desc, 1

首先,不要使用数据类型char(n)。这是一个误会,你想要 varchar(n) 或者只是 text。我建议 text.

  • Any downsides of using data type "text" for storing strings?

解决了这个问题后,您需要一种基于索引的智能方法,否则这将是一场性能噩梦。原始列上的 trigram GIN 索引或单个单词的物化视图上的 text_pattern_ops btree 索引(带计数)。

MV 方法可能更适合单词间的多次重复。