R
R
rraderio2017-02-07 12:01:09
PostgreSQL
rraderio, 2017-02-07 12:01:09

How to make columns more weighty in PostreSQL when searching?

In Elasticsearch I can do like this

GET /_search
{
  "query": {
    "multi_match" : {
      "query" : "this is a test",
      "fields" : [ "subject^3", "message" ] 
    }
  }
}

We are looking for "this is a test" in 2 fields/columns: subject, message. The subject field is three times more powerful than the message field.
How to achieve the same with PostgreSQL?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry MiksIr, 2017-02-07
@miksir

You, I hope, about FTS in PostgreSQL? Then, most likely, the answer is contained here https://www.postgresql.org/docs/9.5/static/textsea...
Creating an index

UPDATE  table SET ftsindex = 
setweight(to_tsvector(coalesce(subject,'')), 'A') ||
setweight(to_tsvector(coalesce(message,'')), 'D');

When creating an index, you can assign a conditional weight to different fields, from A to D.
When querying, you can specify a real weight for the conditional weight .
SELECT id, ts_rank_cd({1.0, 1.0, 1.0, 3.0}, ftsindex, query) AS rank
FROM table, to_tsquery('this is a test') query
WHERE query @@ ftsindex
ORDER BY rank DESC
LIMIT 10;

F
freeExec, 2017-02-07
@freeExec

SELECT * FROM
(SELECT id, 3 AS rank FROM mail WHERE subject like '%query%'
UNION ALL
SELECT id, 1 AS rank FROM mail WHERE message like '%query%') AS t
ORDER BY rank DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question