Organizing Solr’s schema.xml for Sitecore using PowerShell

When setting up your Solr cores for the first time for a new project, several steps have to be done to prepare your schema.xml (or managed-schema). One of them is moving all <field> and <dynamicField> nodes under a new <fields> node and moving all <fieldType> nodes under a new <types> node. This process is very annoying and tedious.

To help you through this, I’ve creating a very simple PowerShell script that automates this process. All you have to do is run the below PowerShell script, pass it the ‘Path’ parameter (that points to the original schema.xml or managed-schema’) and it’ll create a new updated one for you that ends with a ‘*.edited’. Rename it and place it appropriately according to your setup.

param([String]$Path)
[xml]$doc = Get-Content -Path $Path
$new = $doc.Clone();
$existingTypes = $new.SelectSingleNode("//types");
$existingFields = $new.SelectSingleNode("//fields");
if(!$existingTypes){
'---------CREATING <TYPES>' 
   $fields = $new.DocumentElement.AppendChild($new.CreateNode("element", "fields",""));
}
else{
   $fields = $existingFields;
}
if(!$existingFields){ 
'---------CREATING <FIELDS>' 
   $types = $new.DocumentElement.AppendChild($new.CreateNode("element", "types",""));
}
else{
   $types = $existingTypes;
}
'---------Moving fields'
$moveFields = $new.SelectNodes('//field|//dynamicField');
for($i = 0; $i -lt $moveFields.count; $i++){ 
   $fields.AppendChild($moveFields[$i]);
}
'---------Moving types'
$moveTypes = $new.SelectNodes('//fieldType');
for($i = 0; $i -lt $moveTypes.count; $i++){ 
   $types.AppendChild($moveTypes[$i]);
}

$new.Save($Path + ".edited");

Copy the above into a new *.ps1 file (or download it from here) and run it as the below:

.\MoveIntoFieldsAndTypes.ps1 -Path 'c:/Documents/schema.xml'

You will then find a new schema.xml.edited next to the original file.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s