How can I use SQL Server's full text search across multiple rows at once?

Posted by Morbo on Stack Overflow See other posts from Stack Overflow or by Morbo
Published on 2010-05-12T07:05:36Z Indexed on 2010/05/12 7:14 UTC
Read the original article Hit count: 151

Filed under:
|

I'm trying to improve the search functionality on my web forums. I've got a table of posts, and each post has (among other less interesting things):

  • PostID, a unique ID for the individual post.
  • ThreadID, an ID of the thread the post belongs to. There can be any number of posts per thread.
  • Text, because a forum would be really boring without it.

I want to write an efficient query that will search the threads in the forum for a series of words, and it should return a hit for any ThreadID for which there are posts that include all of the search words. For example, let's say that thread 9 has post 1001 with the word "cat" in it, and also post 1027 with the word "hat" in it. I want a search for cat hat to return a hit for thread 9.

This seems like a straightforward requirement, but I don't know of an efficient way to do it. Using the regular FREETEXT and CONTAINS capabilities for N'cat AND hat' won't return any hits in the above example because the words exist in different posts, even though those posts are in the same thread. (As far as I can tell, when using CREATE FULLTEXT INDEX I have to give it my index on the primary key PostID, and can't tell it to index all posts with the same ThreadID together.)

The solution that I currently have in place works, but sucks: maintain a separate table that contains the entire concatenated post text of every thread, and make a full text index on THAT. I'm looking for a solution that doesn't require me to keep a duplicate copy of the entire text of every thread in my forums. Any ideas? Am I missing something obvious?

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about sql-server-2008