How to use Sharepoint Server Search (KeywordQuery class) to search through a sharepoint list?

StackOverflow https://stackoverflow.com//questions/23062621

  •  26-12-2019
  •  | 
  •  

Question

We have a requirement where users are to be allowed to search a list called "Reports" from the front-end, and advanced search, such as author:"John Smith" or filetype:docx, is to be supported.

We decided that this can be achieved using Sharepoint Server Search API (using the Keyword Query Language). Also, since it is possible that all users don't have access to all items in the list, we decided to go with the approach to use a web method with elevated privileges to query the list.

This is my attempt so far...

public string GetSearchResults(string listname, string searchQuery)
{
    SPUser superUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
    using (SPSite site = new SPSite(SPContext.Current.Web.Url, superUser.UserToken))
    {
        KeywordQuery keywordQuery = new KeywordQuery(site);
        keywordQuery.QueryText = searchQuery;

        //where should listname be specified?

        SearchExecutor searchExecutor = new SearchExecutor(); 
        ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery); 
        var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults); 
        ResultTable resultTable = resultTables.FirstOrDefault(); 
        DataTable dataTable = resultTable.Table; 
    }

    //how to parse result to filter only items in given list?
}

...but what I don't understand is how to restrict search to only a given list or how to parse the search result to retrieve items of the list matching the search query.

I'm new to Sharepoint search, so any pointers would help.

Was it helpful?

Solution

This is possible either to give list path or list guid in query text

keywordQuery.QueryText = "Path:/Sales/Lists/Prospects/ (contentclass:STS_ListItem OR IsDocument:True) -ContentClass=urn:content-class:SPSPeople ";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top