SharePoint Search *Quirks: Query Variables

In several forums, emails, and discussions, I keep seeing this recurring question, "How can I limit results to a specific library [in this site collection]?" Turns out, this was more difficult than I originally thought …until I found mention of the escape character "\" (essentially as a side note in an example) in this invaluable resource:

Query variables in SharePoint Server 2013

First, a brief disclaimer

  • I'm sure there are plenty of ways to accomplish task with some options better than others. This post isn't at all intended to imply that this is the best way or even the recommended way… only simply that this was the way I happened to attack it
  • Please share your ideas, experience and lessons learned in the comments J

And now, a few examples…

  • To scope to this site collection:

{searchTerms} SPSiteURL: {SiteCollection.Url}

    • By using the {SiteCollection.Url} variable, you could define, say a [result source, query rule, result type or whatever] at an SSA level and it would be applicable to the Site Collection from which the query is made
    • In other words, say I have two site collections https://foo/sites/abc and https://foo/sites/xyz, and wanted to create a rule (or whatever) at the SSA level. For this example, hard coding the URL path would mean I have to create two rules (or whatever) …one for each site collection, which clearly doesn't scale for large environments.
      • Instead, I can create just one rule and use the variable instead that would be correct and in the proper context for all site collections

 

  • To limit to the "Shared Documents" library in this site collection:

{searchTerms} Path:"{\SiteCollection.Url}/Shared Documents/*"

    • In this example, I needed to also use:
      • The escape character "\" to append the library path to the site collection path (e.g. to specify something more specific than the site collection path)
      • Side Note:
        • Another use for the escape character "\" is described in the Query variables TechNet, too
      • "Quotes" around the path value to handle the [space] (e.g. between Shared and Documents)
      • And the wildcard * character at the end to force treating this as a wildcard instead of an explicit path ending with "[ …whatever path… ]/Shared Documents/"

 

  • Similarly, if you wanted to exclude some path, you could append the minus "-" character in front of the Path managed variable, such as:

{searchTerms} -Path:"{\SiteCollection.Url}/the keep-me-secret library/*"

 

I hope this helps…

Comments

  • Anonymous
    August 04, 2014
    Thanks for this useful hint, Brian!

  • Anonymous
    January 08, 2015
    that helped! I didn't know about the escape character to be used that precedes the SiteCollection.URL property. Thank you Brian

  • Anonymous
    December 18, 2017
    Nice :)