The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

This post is a description of how to use the Microsoft.Office.Server.Search.Query.FullTextSqlQuery class for searching with the MOSS 2007 search engine using the Enterprise Search SQL syntax. I will at the end of this posting explain how to execute queries for optimal results rankings. 

But let me first establish the basics of using the FullTestSqlQuery class. You will only need to employ it for one of the following reasons:

  • You need to support Wildcard searches.
  • You need to search with date ranges.
  • You need to search properties with different operators (CONTAINS, =, >=, <=, <, >, LIKE).
  • You need to search properties for NULL values.
  • You need to use the NEAR operator.
  • You need nested Boolean queries.
  • You like the most flexible (or complicated ;-) ) solution.

Simple keyword and property queries are easier done with the Microsoft.Office.Server.Search.Query.KeywordQuery class. I will, however, not cover this class here.

Ok, let us get started. I have outlined the format of the SQL Syntax accepted by the MOSS 2007 search engine below. After that I will show how to talk to the search engine via the official .NET API.

SQL Syntax
A SQL query is a string that must adhere to the following structure:
SELECT <columns>
FROM <content source>
WHERE <conditions>
ORDER BY <columns>

SQL Syntax Examples

  1. Finds relevant results containing the keyword SharePoint.

    SELECT WorkId,Path,Title,Write,Author,HitHighlightedSummary,
    HitHighlightedProperties,CollapsingStatus
    FROM Scope()
    WHERE FREETEXT(defaultproperties, 'SharePoint')
    ORDER BY Rank Desc
  2. Finds relevant results containing at least one of the keywords SharePoint and Search.
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, 'SharePoint Search')
    ORDER BY Rank Desc
  3. Finds relevant results containing both the keywords SharePoint and Search.
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, '+SharePoint +Search')
    ORDER BY Rank Desc
  4. Finds relevant results containing the exact phrase SharePoint Search.
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, ' "SharePoint Search" ')
    ORDER BY Rank Desc
  5. Finds relevant results containing both the keywords SharePoint and Search but not the keyword WSS
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, '+SharePoint +Search -WSS')
    ORDER BY Rank Desc
  6. Finds relevant SharePoint results authored by persons named John.
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, 'SharePoint') AND CONTAINS(Author,' "John" ')
    ORDER BY Rank Desc
  7. Finds relevant SharePoint results modified within the last 30 days.
    SELECT WorkId,Path,Title,Write,Author,...
    FROM Scope()
    WHERE FREETEXT(defaultproperties, 'SharePoint') AND Write<=DATEADD(DAY,30,GETGMTDATE())
    ORDER BY Rank Desc

 .NET API
The following code should give you some inspiration how to execute a SQL query against the MOSS 2007 search engine.

// Execute Query
ResultTableCollection results = null;
using (FullTextSqlQuery query = new FullTextSqlQuery(ServerContext.Current))
{
query.StartRow = 0;
query.RowLimit = 10;
query.HighlightedSentenceCount = 3;
query.EnableStemming = true;
query.TrimDuplicates = true;
query.Culture = CultureInfo.CurrentCulture;

query.KeywordInclusion = KeywordInclusion.AnyKeyword;
query.SiteContext = new Uri("http://yourserver/sites/asite");




if (SPSecurity.AuthenticationMode != AuthenticationMode.Windows)

query.AuthenticationType = QueryAuthenticationType.PluggableAuthenticatedQuery;
else

    query.AuthenticationType = QueryAuthenticationType.NtAuthenticatedQuery;
query.QueryText = "SELECT ... FROM Scope() WHERE ... ORDER BY ...";
results = query.Execute();
}

// Parse results and create XML output
StringBuilder buffer = new StringBuilder(10240);
ResultTable relevantResults = results[ResultType.RelevantResults];
using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(buffer)))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("Results");
writer.WriteAttributeString("hits", relevantResults.TotalRows.ToString());
while (relevantResults.Read())
{
writer.WriteStartElement("Result");
for (int i=0; i<relevantResults.FieldCount; i++)
{
writer.WriteStartElement(relevantResults.GetName(i));
object val = relevantResults.GetValue(i);
if (val != null)
writer.WriteString(val.ToString());
else
writer.WriteString("null");
writer.WriteEndElement();
}     
writer.WriteEndElement();
}
  writer.WriteEndElement();
  string xml = buffer.ToString();
...






}

The using statement around the usage scope of the FullTextSqlQuery class is very important to remember as you will otherwise get an OutOfMemoryException after running a good number of queries. This is so because the search engine is a COM server that the .NET API maintains a handle to.

A closer look at the FREETEXT predicate
Take a look at following two keyword searches using the FREETEXT predicate (rest of SQL string omitted for simplicity):

FREETEXT(defaultproperties, '+sharepoint +search')
FREETEXT(defaultproperties, 'sharepoint') AND FREETEXT(defaultproperties, 'search')

Both queries are valid and yield the same results buth with different ranking. Which one yields the best results ranking? Answer: The first one! It is recommended that you only use one FREETEXT predicate in a search query. Results ranking will otherwise not be optimal.

The defaultproperties keywords references the default set of properties to include in the ranking algorithm. This is also recommended for optimal ranking of results. You can alternatively use the WITH predicate to define your own set of properties if you are not happy with the default one. This is helpful if you need to promote results containing the keywords on your own custom properties. Note: The standard MOSS 2007 search center simply uses the defaultproperties.

The FREETEXT predicate can also be configured for implicit AND search or implicit OR search. This means that a query like:

FREETEXT(defaultproperties, 'sharepoint search')

can respectively find results containing both the keywords sharepoint and search or find results containing at least one of the keywords. Use the the KeywordInclusion property on the FulltextSqlQuery object to control this behavior. See the code example earlier in this posting.

Conclusion
I have just described the key concepts of using the FulltextSqlQuery class. I have not described all of its features nor have I described the SQL Syntax in full. I refer you to the MOSS 2007 SDK for a complete reference.

Stay stuned for more postings on the inner workings of the MOSS 2007 search engine!

Print | posted on Tuesday, July 31, 2007 11:43 PM

Feedback

8/6/2007 10:50 AM
#1

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Hi Lars,

nice "to-the-point" article.

just one question: how did you determine the "magic number" 10240 (or 0x2800) on the buffer? :-)
8/6/2007 4:32 PM
#2

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Really very useful article,for a guy who is exploring MOSS search.
Sai
8/7/2007 4:07 PM
#3

# How to publish a MOSS website to Public Website

Hi,

I am pretty new to this MOSS technology.
Recently, I ve developed a MOSS web site and my goal is to publish the site to internet zone.

Let's say my MOSS web Site is http://eh-moss and I want to expose it to the internet as http://moss.com
How can I do that,can u please give some Step by Step administration on the above scenario.
Sai
8/8/2007 1:05 PM
#4

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

This code should work whether you have a seperate indexing server from the front-end web server or do you need to make use of the web service for that?
8/21/2007 8:18 PM
#5

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Anders - yes, that secret I forgot to explain ;-)
8/21/2007 8:23 PM
#6

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Henri - no the server topology is transparent to client's of the object model. You only need the web service when quering from remove servers where the MOSS object model is not available. This could be from a Windows XP box or simply from a WSS only server.
8/21/2007 8:25 PM
#7

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Sai - this is not the right forum for your question. I would like to point your attention to Joel Oleson's blog for SharePoint admin related stuff: http://blogs.msdn.com/joelo/
9/20/2007 3:25 PM
#8

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Found strange behaviour of "order by Rank desc" construction.

If desc exists, search engine return one less results that where desc is omitted.

"order by Rank" - 301 results
"order by Rank desc" - 300 results

"order by Rank asc" - equal "order by Rank"

and always results were returned ordered by desc :)

"order by LastModifiedTime" - 301 results
11/5/2007 5:28 PM
#9

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Hi,
Really Good Article!
Covers almost every aspect of SQL SYNTAX.
I Need your help on the below mentioned query.

In The OOB advanced Search webpart, user would be able to give Title contains "hare" and it would return if there is a title with value "Sharepoint".How Microsoft has done this?
The contains predicate can take a wildcard "*" after few start charecter of a word, meaning it can do a prefix matching, like "shar*" would return sharepoint.
But how microsoft has implemented the search to give "sharepoint", when a user gives "hare".
I tried LIKE predicate and MATCHES predicate it does not help.I think you can reply me a perfect answer... Hoping to hear from you.
11/17/2007 5:08 AM
#10

# modern mythology in graphic novel as a source in animation

please help me in search for this subject :modern mythology in graphic novel as a source in animation
11/26/2007 11:48 AM
#11

# aasfpjvb

aasfpjvb
11/27/2007 1:57 AM
#12

# The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

I've been handing this blog post URL (below) so much lately that I thought I'd share it here. The secrets
11/27/2007 2:27 AM
#13

# The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

I&amp;#39;ve been handing out this blog post URL (below) so much lately that I thought I&amp;#39;d share it here
11/27/2007 5:09 PM
#14

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

The only way to do an equals search on a date eg. 1 March 2007, is with a query like this:
Write >= '2007-03-01' AND Write < '2007-03-02'

[Write = '2007-03-01'] doesn't work cause the time is included when SharePoint does the compare.

Please tell me if this is the best way to perform an exact date compare without the time.
12/4/2007 11:14 AM
#15

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Hi Mikaelo,

I have also experienced issues with ORDER BY Rank Desc . In my case, I am losing more than one row of data, depending on the search criteria.

Example:

RETURNS 4 ROWS

SELECT Title, Path, Description, Write, Rank, Size FROM Scope() WHERE (site = 'http://site1.com' OR site = 'http://site2.com')FREETEXT('sometext') ORDER BY Rank


RETURNS 2 ROWS ( Only includes results from site1.com)

SELECT Title, Path, Description, Write, Rank, Size FROM Scope() WHERE (site = 'http://site1.com' OR site = 'http://site2.com')FREETEXT('sometext') ORDER BY Rank Desc


Has anyone else seen this problem? Does anyone have any ideas why this is happening or have a fix?
12/28/2007 2:51 PM
#16

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Hi,
I need some help in using FulltextSQlQuery for Property query. I have a custom webpart for getting search results from Sharepoint index database using FullTextSQlQuery. It works finr for the search works well with the normal string search input.
If i specify property query in the search input like Author:John, my query didn't return any results. I am using search input as it is while using FulltextSQLQuery.
Do I need to do any processing before passing search input to query, and modify the query to use Something like this freetext(Author,'John') instead of freetext(defaultproperties,'Author:John').

Any help is appreciated.
1/15/2008 12:29 PM
#17

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

Hi!
I've been googling for some time now to find out more about the magic "defaultproperties" used by default in searches. Which are the default properties? Can I in some way add properties to that collection?
In some (yes, in some - not all) installations I've done, the PublishingPageContent column doesn't seem to be included.
On the other hand, a new site column I created seems to be included automatically.
Do I have to map the crawled ows_PublishingPageContent to a special Managed property?

Thanx!
4/22/2009 6:13 PM
#18

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

My search queries work fine until I add a scope

in the queryText it looks like

FROM Scope() WHERE \"scope\" = 'valid scope' AND...

once I add the WHERE \"scope... the query just hangs and hangs and hangs

I have tried shared scopes and site collection scopes but always the same thing.

everything works fine until I add the scope (for FullTextSQL)if I use the HiddenConstraints on the Keyword query and add a scope, I get the same behavior

any ideas?
4/22/2009 8:02 PM
#19

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

nevermind, I found it

I was refering to using Microsoft.SharePoint.Search.Query;

when I should have been refering to
using Microsoft.Office.Server.Search.Query;


crazy :)
6/3/2009 10:25 AM
#20

# re: The secrets of SQL Syntax Queries for Relevant Results in MOSS 2007 Enterprise Search

I need some help in using FulltextSQlQuery for Property query. I have a custom webpart for getting search results from Sharepoint index database using FullTextSQlQuery. It works finr for the search works well with the normal string search input.
Title  
Name  
Email
Url
Comments   
Please add 6 and 1 and type the answer here: