locked
How to get search results data programatically? RRS feed

  • Question

  • Hi,

    In my SharePoint 2010 environment, I am making a visual web part that does searches, and I want to make my custom search results.

    The problem is I need a way (from C# or JavaScript/jQuery) that can send a request to the SharePoint search results page would be like "http://server/sites/SearchCenter/Pages/results.aspx" and then get an XML (or maybe html) response of the search results. This or some other way that does the same thing.

    How can I do this?

    Thanks.

    Thursday, May 16, 2013 1:51 PM

Answers

  • Your requirement can be achive Out-of-the box in SharePoint 2010, not sure why you are planning to custimise in C#. Any reason?

    1. You need to configure PDF Ifilter to search the contents within PDF

    2. You can configure Metadata properties for the custom columns you added in document library.

    3. Configure advanced search.

    4. You are done...

    ----------------------------------------------------------------
    If my post is helpful, please vote!
    If you think my solution worked for you, please mark as Answer!
    Thanks.

    • Marked as answer by Qiao Wei Friday, May 24, 2013 9:45 AM
    Thursday, May 16, 2013 2:47 PM
  • Hi Sp.User,

    If you do want to use C#, you can use the KeywordQuery class (http://msdn.microsoft.com/en-us/library/microsoft.office.server.search.query.keywordquery(v=office.14).aspx) to query SharePoint Search Index. You don't need to worry about ifilters in your code, as you're just querying SharePoints search index. As long as the ifilter is installed on the SharePoint server, and your PDF files have been index, then it will work fine.

    An example of using the KeywordQuery class (from a test webpart):

    using System;
    using System.ComponentModel;
    using System.Data;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.Office.Server.Search.Administration;
    using Microsoft.Office.Server.Search.Query;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    
    namespace SharePointTesting.GetSearchItem
    {
     [ToolboxItemAttribute(false)]
     public class GetSearchItem : WebPart
     {
      protected override void CreateChildControls()
      {
       Controls.Add(SearchKeyword);
       Controls.Add(RunSearch);
       Controls.Add(Results);
      }
    
      private TextBox SearchKeyword;
      private Button RunSearch;
      private Label Results;
    
      protected override void OnInit(EventArgs e)
      {
       base.OnInit(e);
       SearchKeyword = new TextBox();
       RunSearch = new Button();
       RunSearch.Text = "Search";
       RunSearch.Click += RunSearchOnClick;
       Results = new Label();
      }
    
      private void RunSearchOnClick(object sender, EventArgs eventArgs)
      {
       try
       {
        var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
        var keywordQuery = new KeywordQuery(ssaProxy);
        keywordQuery.RowLimit = 1;
        keywordQuery.SelectProperties.Clear();
        keywordQuery.SelectProperties.Add("Title");
        keywordQuery.SelectProperties.Add("Size");
        keywordQuery.SelectProperties.Add("Path");
        keywordQuery.ResultsProvider = SearchProvider.Default;
        keywordQuery.QueryText = String.Format("{0} AND Path:\"{1}\"", SearchKeyword.Text, "http://yourwebsite/PathToYourPdfDocumentsLibrary*");
        keywordQuery.ResultTypes |= ResultType.RelevantResults;
        keywordQuery.EnableStemming = true;
        ResultTableCollection searchResults;
        try
        {
         searchResults = keywordQuery.Execute();
        }
        catch (Exception)
        {
         Results.Text = String.Format("Your query is malformed. Please rephrase your query.");
         return;
        }
        if (searchResults.Exists(ResultType.RelevantResults))
        {
         var searchResult = searchResults[ResultType.RelevantResults];
         var result = new DataTable { TableName = "SearchResults" };
         result.Load(searchResult, LoadOption.OverwriteChanges);
         if (result.Rows.Count > 0)
         {
          DataRow dataRow = result.Rows[0];
          var urlToItem = dataRow["Path"] as String;
          var web = SPContext.Current.Web;
          var item = web.GetListItem(urlToItem);
          Results.Text = String.Format("Found the item: {0}", item[SPBuiltInFieldId.FileLeafRef]);
          return;
         }
         Results.Text = String.Format("No items found for search term: {0}", SearchKeyword.Text);
         
        }
       }
       catch (Exception e)
       {
        Results.Text = String.Format("Unhandled Exception running query. Error: {0}", e.Message);
       }
      }
     }
    }


    Regards, Matthew
    MCPD | MCITP
    My Blog
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.

    I just added a webpart to the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here: Upload and Crop User Profile Photos

    • Marked as answer by Qiao Wei Friday, May 24, 2013 9:45 AM
    Thursday, May 16, 2013 3:25 PM

All replies

  • Are you looking for fulltextquery or keywordquery of sharepoint ? which is the programmatic way of getting sharepoint search results as datatable for your search query.

    Thanks


    Thursday, May 16, 2013 2:05 PM
  • I'm not sure, but maybe if I give more information, you can decide for me.

    Basically, I have PDF documents in a document library. I want to be able to search through them, like all their fields, and a full text search. The search results page can already do this (using ifilter plugin), but you have to type the query in the search box, but I am looking to do the same thing but in c#.


    • Edited by sp.user Thursday, May 16, 2013 2:14 PM
    Thursday, May 16, 2013 2:13 PM
  • Try adding the Search core results webpart in the page where you are planning to add the visual webpart.

    Then, You can modify XSLT of the Search core results webaprt as per your look and feel.

    ----------------------------------------------------------------
    If my post is helpful, please vote!
    If you think my solution worked for you, please mark as Answer!
    Thanks.

    Thursday, May 16, 2013 2:14 PM
  • So how does it all work?

    I'll have my own text box, then how do I (in c#) run the search using the text in the textbox, and populate the search core results webpart with the results?

    Thursday, May 16, 2013 2:18 PM
  • As mentioned in the previous reply... you can acheive my modifying xslt . if you want to do entire thing programmatically then you can use fulltextquery for your requirement.


    Thanks

    Thursday, May 16, 2013 2:19 PM
  • Yes, I would rather do it all using c#. I'll give it a try and post back if there are any issues.
    Thursday, May 16, 2013 2:32 PM
  • Your requirement can be achive Out-of-the box in SharePoint 2010, not sure why you are planning to custimise in C#. Any reason?

    1. You need to configure PDF Ifilter to search the contents within PDF

    2. You can configure Metadata properties for the custom columns you added in document library.

    3. Configure advanced search.

    4. You are done...

    ----------------------------------------------------------------
    If my post is helpful, please vote!
    If you think my solution worked for you, please mark as Answer!
    Thanks.

    • Marked as answer by Qiao Wei Friday, May 24, 2013 9:45 AM
    Thursday, May 16, 2013 2:47 PM
  • Hi Sp.User,

    If you do want to use C#, you can use the KeywordQuery class (http://msdn.microsoft.com/en-us/library/microsoft.office.server.search.query.keywordquery(v=office.14).aspx) to query SharePoint Search Index. You don't need to worry about ifilters in your code, as you're just querying SharePoints search index. As long as the ifilter is installed on the SharePoint server, and your PDF files have been index, then it will work fine.

    An example of using the KeywordQuery class (from a test webpart):

    using System;
    using System.ComponentModel;
    using System.Data;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.Office.Server.Search.Administration;
    using Microsoft.Office.Server.Search.Query;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    
    namespace SharePointTesting.GetSearchItem
    {
     [ToolboxItemAttribute(false)]
     public class GetSearchItem : WebPart
     {
      protected override void CreateChildControls()
      {
       Controls.Add(SearchKeyword);
       Controls.Add(RunSearch);
       Controls.Add(Results);
      }
    
      private TextBox SearchKeyword;
      private Button RunSearch;
      private Label Results;
    
      protected override void OnInit(EventArgs e)
      {
       base.OnInit(e);
       SearchKeyword = new TextBox();
       RunSearch = new Button();
       RunSearch.Text = "Search";
       RunSearch.Click += RunSearchOnClick;
       Results = new Label();
      }
    
      private void RunSearchOnClick(object sender, EventArgs eventArgs)
      {
       try
       {
        var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
        var keywordQuery = new KeywordQuery(ssaProxy);
        keywordQuery.RowLimit = 1;
        keywordQuery.SelectProperties.Clear();
        keywordQuery.SelectProperties.Add("Title");
        keywordQuery.SelectProperties.Add("Size");
        keywordQuery.SelectProperties.Add("Path");
        keywordQuery.ResultsProvider = SearchProvider.Default;
        keywordQuery.QueryText = String.Format("{0} AND Path:\"{1}\"", SearchKeyword.Text, "http://yourwebsite/PathToYourPdfDocumentsLibrary*");
        keywordQuery.ResultTypes |= ResultType.RelevantResults;
        keywordQuery.EnableStemming = true;
        ResultTableCollection searchResults;
        try
        {
         searchResults = keywordQuery.Execute();
        }
        catch (Exception)
        {
         Results.Text = String.Format("Your query is malformed. Please rephrase your query.");
         return;
        }
        if (searchResults.Exists(ResultType.RelevantResults))
        {
         var searchResult = searchResults[ResultType.RelevantResults];
         var result = new DataTable { TableName = "SearchResults" };
         result.Load(searchResult, LoadOption.OverwriteChanges);
         if (result.Rows.Count > 0)
         {
          DataRow dataRow = result.Rows[0];
          var urlToItem = dataRow["Path"] as String;
          var web = SPContext.Current.Web;
          var item = web.GetListItem(urlToItem);
          Results.Text = String.Format("Found the item: {0}", item[SPBuiltInFieldId.FileLeafRef]);
          return;
         }
         Results.Text = String.Format("No items found for search term: {0}", SearchKeyword.Text);
         
        }
       }
       catch (Exception e)
       {
        Results.Text = String.Format("Unhandled Exception running query. Error: {0}", e.Message);
       }
      }
     }
    }


    Regards, Matthew
    MCPD | MCITP
    My Blog
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.

    I just added a webpart to the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here: Upload and Crop User Profile Photos

    • Marked as answer by Qiao Wei Friday, May 24, 2013 9:45 AM
    Thursday, May 16, 2013 3:25 PM