Sql-server – Fulltext search limiting users possibilities

full-text-searchsql servert-sql

We have a web site with a search box. The search uses a fulltext index column. However, we just cant feed the text the user has input into this stored procedure.

CREATE PROCEDURE [dbo].[SearchPages]
    @Term varchar(200)
AS
BEGIN
    SELECT pc.SearchData, from PageContent pc
    where contains(pc.SearchData, @Term)
END

Searches with space in them fails, also there is a pletora of sql functions we do not want to expose to the users like

NEAR((bike,control), 10, TRUE)

and the like or binary operators like AND or OR.

So we need to escape the term in some way.

One way that immediately comes in mind is to put an AND between every word.
However, it doesnt feel acceptable.

So is there any better suggestions?

Best Answer

Here are three suggestions.

Suggestion 1. Use plainto_tsquery when you convert the user provided search string to PostgreSQL's tsquery, see the PostgreSQL docs. — I think that plainto_tsquery discards any special magical characters + AND, OR etcetera. (But I'm not completely sure. You'd better verify this so you don't do anything dangerous) Oops I didn't notice that this was about SQL Server not PostgreSQL.

Suggestion 2. Build a HTML form for advanced search queries, with fields like:

Include all these words: ...
Include any of these words: ...
Exclude all these ...

And so on. Next, construct the otherwise dangerous full text search expression yourself in SQL Server syntax.

Suggestion 3. You could provide a single search text field, and let e.g. "-someword" mean that "someword" should be excluded, and "+anotherword" mean that "anotherword" must be included. Then, you build your own parser for this search field, and convert the resulting "abstract search tree" to something SQL Server understands, and give it to SQL Server.