SharePoint Search Using KeywordQuery

To build custom search applications on top of SharePoint you should use the new  Microsoft.Office.Server.Search.Query object model. From code, you can use either the FullTextSQLQuery or the KeyWordQuery class. The common properties and methods for these classes are defined in the base Query class, note however that this class should never be used.

Whether to use the FullTextSQLQuery or KeywordQuery class depends on the complexity of the search queries that need to be implemented. FullTextSQLQuery allows for complex SQL queries to be executed whereas using KeywordQuery is considerably more simple – just pass the search terms in basic text format and retrieve the results.

SharePoint Search Using KeywordQuery

KeywordQuery class allows a keyword or a SharePoint property filter to be passed directing to the search service without needing to construct a SQL query. There are only two refinements supported for search using KeyWordQuery. Adding the + sign in front of a word mandates that the results must include that search term, adding a - sign in front of a word will mean that results results will specifically exclude that word.

The KeyWordQuery object is instantiated by passing in the SharePoint site to the constructor, then set the QueryText property of the object to the text you wish to search the SharePoint site for. The ResultTypes property should be set to ResultType.RelevantResults to retrieve the results. Then simply call the Execute method to execute the search. The below example demonstrates passing the results of the SharePoint search using KeyWordQuery to a DataTable.

For example:

DataTable resultsDataTable = new DataTable();

using (SPSite site = new SPSite("http://sharepointsite"))

{
KeywordQuery queryObj = new KeywordQuery(site);
queryObj.QueryText = "sharepoint +search -exchange";
queryObj.ResultTypes = ResultType.RelevantResults;

ResultTableCollection resultTables = queryObj.Execute();
if (resultTables.Count > 0)

{
ResultTable relevantResults = resultTables[ResultType.RelevantResults];
resultsDataTable.Load(relevantResults, LoadOption.OverwriteChanges);
}

} 

return resultsDataTable;

Continues…

Pages: 1 2




Array

No comments yet... Be the first to leave a reply!