25

I have a search table with, say, 4 columns of text data to search.

I do something like this:

SELECT * FROM dbo.SearchTable
WHERE CONTAINS((co1, col2, col3, col4), 'term1 AND term2')

It looks like Contains only returns true if term1 and term2 are in the same column. Is there any way to specify that all columns should be included with an AND?

If not, my idea is to JSON all search columns and stick them into one. That way I can full text search them but still easily extract the individual columns in .NET. I'm presuming that the indexer won't have a problem with this and will dispense with the JSON characters and quotes. Is this correct?

Thanks

EDIT

Thinking about the JSON idea, the crawler would also index the property names so I'd have to rename {name}, {details}, {long_details} to something like {x1}, {x2}, {x3} to ensure they'd not be picked in a search. Hopefully if they're so short they wouldn't be indexed anyway.

EDIT2

I can create a Stoplist, based on the system Stoplist and put the property names into that.

1 Answer 1

30

This should work:

SELECT * FROM dbo.SearchTable
WHERE CONTAINS((co1, col2, col3, col4), 'term1')
AND CONTAINS((co1, col2, col3, col4), 'term2');

Alternatively, you could add a new computed column with a full text index on it. Add a column like this:

computedCol AS col1 + ' ' + col2 + ' ' + col3 + ' ' + col4

And create the full text index:

CREATE FULLTEXT INDEX ON SearchTable (computedCol LANGUAGE 1033)
KEY INDEX pk_SearchTable_yourPrimaryKeyName

Then you can do this:

SELECT * FROM dbo.SearchTable
WHERE CONTAINS(*, 'term1 AND term2')
3
  • 1
    Hi, thanks. I don't like the 1st option because i'd have to parse the search term and build the query dynamically (also I think I read that, if possible, searches should be combined into 1 CONTAINS). I'd need to read more about computed columns. I think they can be persisted - but then I'd be storing twice as much data. If they're not persisted, would it have much of an impact on the query time?
    – user3083558
    Dec 9, 2013 at 16:55
  • 9
    Be aware that string concatenation in SQL where one of the values is null will replace the entire expression with null. You can solve this issue by wrapping each nullable term with isnull like "isnull(col, '')". Feb 12, 2016 at 16:55
  • 5
    Both of these suggestions are a hack. Is there seriously no way to get SQL Server full text search to behave the way the OP wants? The MS documentation on the topic seems to state (ambiguously as it turns out) that a search should span multiple columns. Nowhere does it say that the search terms MUST be found entirely in one column.
    – rory.ap
    Jan 29, 2019 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.