Search code examples
postgresqlsearchfull-text-searchescaping

PSQLException: ERROR: syntax error in tsquery


Which characters must be avoided to make sure PSQLException: ERROR: syntax error in tsquery will not occur? The documentation does not say anything about how to escape the search string: http://www.postgresql.org/docs/8.3/static/datatype-textsearch.html


Solution

  • Use quotes around your terms if you want them as phrases/verbatim or they contain characters used in the syntax:

    select to_tsquery('"hello there" | hi');
    

    Bear in mind that you shouldn't really have crazy characters in your terms, since they are not going to match anything in the tsvector.

    The (non-token) characters recognized by the tsquery parser are: \0 (null), (, ), (whitespace), |, &, :, * and !. But how you tokenize your query should be based on how you have setup your dictionary. There are a great many other characters that you will likely not want in your query, not because they will cause a syntax error but because it means you are not tokenizing your query correctly.

    Use the plainto_tsquery version if it's a simple AND query and you don't want to deal with creating the query manually.