Monday, September 2, 2013

Appending query terms in SharePoint 2013/O365 without adding them to the search box

In SharePoint 2010 you can append query terms to a search query by either setting a property on the Core Results web part, or by using the a= query parameter.
image
Neither of these possibilities exist in SharePoint 2013 so you have to do a workaround. If you read my post Limiting search results by exact time in SharePoint 2013–and how to do FQL you might have picked up on how you can use the refiners to pass in arbitrary FQL. This means, the refiner parameter is not only useful for refinements, but you may use it to append parts to your query as well.
Using the REST API this is quite easy as you pass raw FQL into the query string. Using the search center page is not as easy. I have not yet figured out how to append a 100% arbitrary query which does not show, but you can easily append queries which targets managed properties which are marked as queryable.
Using the following JSON object will query for the term “test” as well as for “dlp” and “admin” in the Title field.
{"k":"test","r":[{"n":"title","t":["\"dlp\"", "\"admin\""],"o":"and","k":false,"m":null}]}
Encoded the URL looks something like this:
https://contoso.com/search/Pages/results.aspx#Default=%7B%22k%22%3A%22test%22%2C%22r%22%3A%5B%7B%22n%22%3A%22title%22%2C%22t%22%3A%5B%22%5C%22dlp%5C%22%22%2C%20%22%5C%22admin%5C%22%22%5D%2C%22o%22%3A%22and%22%2C%22k%22%3Afalse%2C%22m%22%3Anull%7D%5D%7D
or un-encoded which also seems to work most of the time
https://contoso.com/search/Pages/results.aspx#Default={"k":"test","r":[{"n":"title","t":["\"dlp\"", "\"admin\""],"o":"and","k":false,"m":null}]}
The research continues and I hope to find a way which can append any arbitrary query just like you can with the REST interface.
Tip: Click different refiners with multi value as well as change sorting to see how the JSON object is built up.