Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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