Skip to content

Instantly share code, notes, and snippets.

@richardszalay
Created August 12, 2019 01:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardszalay/fcd29492eacafd24595e57bb8b91a851 to your computer and use it in GitHub Desktop.
Save richardszalay/fcd29492eacafd24595e57bb8b91a851 to your computer and use it in GitHub Desktop.
Convert SXA search API URLs to raw queries
<#
Converts an SXA search results API URL into the raw query sent to the provider
Example:
ConvertFrom-SxaSearchUrl (Read-Host "URL (eg. http://localhost/sxa/search/results?q=...)") | Format-List
#>
function ConvertFrom-SxaSearchUrl
{
param(
[Uri]$uri
)
if (-not $uri)
{
return
}
$ErrorActionPreference = "Stop"
$qs = [System.Web.HttpUtility]::ParseQueryString($uri.Query.Substring(1))
if (-not $qs["site"]) {
$multisiteContext = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider.GetService([Sitecore.XA.Foundation.Multisite.IMultisiteContext])
$site = $multisiteContext.GetSettingsItem( (Get-Item $qs["itemid"]) ).Axes.GetChild("Site Grouping").Children[0].Fields["SiteName"].Value
} else {
$site = $qs["site"]
}
$searchService = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider.GetService([Sitecore.XA.Foundation.Search.Services.ISearchService])
$indexName = ""; $queryable = $searchService.GetQuery($qs["q"], $qs["s"], $null, $null, $site, $qs["itemid"], [ref]$indexName)
$getQuery = $queryable.GetType().GetMethod("GetQuery", [System.Reflection.BindingFlags]::NonPublic -bxor [System.Reflection.BindingFlags]::Instance)
$query = $getQuery.Invoke($queryable, @($queryable.Expression))
$getQueryIndex = $queryable.GetType().GetMethod("get_Index", [System.Reflection.BindingFlags]::NonPublic -bxor [System.Reflection.BindingFlags]::Instance)
$queryIndex = $getQueryIndex.Invoke($queryable, @())
$optimizeQuery = ($queryIndex.GetType().GetMethods([System.Reflection.BindingFlags]::NonPublic -bxor [System.Reflection.BindingFlags]::Instance) | ? Name -eq "OptimizeQueryExpression")
if ($optimizeQuery -ne $null)
{
$index = [Sitecore.ContentSearch.ContentSearchManager]::GetIndex($indexName)
$optimizedQuery = $optimizeQuery.Invoke($queryIndex, @($query, $index))[0] + '&$count=true'
}
else
{
$optimizedQuery = [string]$query
}
[psobject]@{
Query = $optimizedQuery;
Index = $indexName;
Site = $site
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment