November 24, 2017 Greg

Clear SOLR core with PowerShell

Using PowerShell with SOLR

There are multiple examples on the web on how to interact with SOLR using curl. I thought I would share here a simple example of how to send requests to SOLR using PowerShell web request.

It is not complicated but very sensible on how the parameters are set to have a successful PowerShell interaction with SOLR.
In the example bellow you can clear all the documents in a SOLR core using PowerShell. The same code can be re-used to perform all sort of actions against SOLR with PowerShell.

function Get-SolrCredentials {
    [Parameter(Mandatory=$False)][string]$SolrUsername = "",
    [Parameter(Mandatory=$False)][string]$SolrPassword = ""

  if($SolrUsername -eq "" -or $SolrPassword -eq "") {		
    $solrPsCred = Get-Credential
  else {
    $securedPassword = ConvertTo-SecureString $SolrPassword -AsPlainText -Force;
    $solrPsCred = New-Object -Type System.Management.Automation.PSCredential -ArgumentList $SolrUsername, $securedPassword;
  return $solrPsCred;

function Clear-SolrDocuments {
    [Parameter(Mandatory=$False)][System.Management.Automation.PSCredential]$credentials = $null

  if($credentials -eq $null) {
    $credentials = Get-SolrCredentials

  $url = $baseUrl + "/solr/" + $coreName + "/update?boost=1.0&commitWithin=1&overwrite=true&wt=json"

  try {
    Write-Host "Deleting all documents of core $coreName" -ForegroundColor Green
    $webRequest = Invoke-WebRequest -URI $url -Credential $credentials -Headers @{"Content-type"="text/xml";} -Body "<delete><query>*:*</query></delete>" -Method POST		
    $webRequest | Out-String |% {Write-Host $_}

    if ($webRequest.StatusCode -ne 200) {
      Write-Host "[ERROR] Solr did not respond with status code HTTP 200." -ForegroundColor Red
  catch {
    Write-Host "[ERROR] Exception occured while sending request to solr." -ForegroundColor Red

Write-Host "Setting credentials"
$cred = Get-SolrCredentials -SolrUsername "MyLogin" -SolrPassword "MyPassword";

Write-Host "Clearing core"
Clear-SolrDocuments -baseUrl "http://MySolrBaseUrl" -coreName "MyCore" -credentials $cred
Tagged: ,


We invite you to contact us for more information
about our services.