PostgreSQL: websearch_to_tsquery precedence / predicate ordering

full-text-searchpostgresql

How does precedence work in websearch_to_tsquery? I have below example query:

websearch_to_tsquery('exp1 exp2 OR "multi word expression" -weak')

The issue I have is that the results include text containing 'weak' because they match 'exp1 exp2'.

However when I remove OR "multi word expression eg query being

websearch_to_tsquery('exp1 exp2 -weak')

then it works as expected and weak is not present in results.

I suspect the initial query is interpreted as

(exp1 and exp2) OR ("multi word expression" and not weak)

instead of my intention of
(exp1 and exp2) OR ("multi word expression") and not weak

So how would I write the later query using `websearch_to_tsquery?

Best Answer

This is how PostgreSQL interprets your query:

SELECT websearch_to_tsquery('english', 'exp1 exp2 OR "multi word expression" -weak');

                     websearch_to_tsquery                     
--------------------------------------------------------------
 'exp1' & 'exp2' | 'multi' <-> 'word' <-> 'express' & !'weak'
(1 row)

Since & ties stronger than |, your suspicion is correct.

I don't think that there is a simpler way to express what you want with websearch_to_tsquery than

exp1 exp2 -weak OR "multi word expression" -weak