0

Postgres 9.1 shopping cart contains product table

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

Cart has search field. If something is entered into it, autocomplete dropdown must show best matching products ordered by number products matched to this criteria.

How to implement such query in postgres 9.1 ? Search should performed by name and description fields in products table. It is sufficient to use substring match. Full text search with sophisticated text match is not strictly required.

Update

Word joote can be part of product name or description.

For example for first match in image text may contain

.. See on jootetina ..

and for other product

Kasutatakse jootetina tegemiseks ..

and another with upper case

Jootetina on see ..

In this case query should return word jootetina and matching count 3. How to make it working like auotcomplete which happens when search term is typed in Google Chrome address bar ?

How to implement this ?

Or if this is difficult, how to return word jootetina form all those texts which matches search term joote ?

Andrus
  • 26,339
  • 60
  • 204
  • 378

2 Answers2

1
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
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • This query does not return matching words inside text. How to make it work more like real search, like autocomplete when something is typed in chrome toolbar? I updated question and provided sample. – Andrus Sep 30 '16 at 06:13
  • There is related question in http://stackoverflow.com/questions/39790930/how-to-get-best-matching-words-from-name-and-description – Andrus Sep 30 '16 at 11:53
1

First of all, do not use the data type char(n). You want varchar(n) or just text. I suggest text. See:

With that fixed, you need a smart index-based approach or this is a performance nightmare. Either trigram GIN indexes on the original columns or a text_pattern_ops btree index on a materialized view of individual words (with count).

The MV approach is probably superior for many repetitions among words.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228