Created
October 18, 2019 16:14
-
-
Save tackme31/41814f94762cc8a92f0b913b36293c8e to your computer and use it in GitHub Desktop.
A sample code for adding a custom field to a Solr index dynamically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomDocumentBuilder : SolrDocumentBuilder | |
{ | |
public CustomDocumentBuilder(IIndexable indexable, IProviderUpdateContext context) : base(indexable, context) | |
{ | |
} | |
protected override IEnumerable<IIndexableDataField> GetFieldsByItemList(IIndexable indexable) | |
{ | |
var fields = base.GetFieldsByItemList(indexable); | |
// Create a custom field | |
// This field is added as "custom_field_t" in a index | |
// See '/App_Config/Sitecore/ContentSearch/Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config' | |
var field = new CustomField | |
{ | |
Name = "Custom Field", | |
TypeKey = "single-line text", | |
FieldType = typeof(TextField), | |
Value = "This value is added by the CustomDocumentBuilder", | |
Id = Sitecore.Data.ID.NewID | |
}; | |
return fields.Append(field); | |
} | |
} | |
public class CustomField : IIndexableDataField | |
{ | |
public string Name { get; set; } | |
public string TypeKey { get; set; } | |
public Type FieldType { get; set; } | |
public object Value { get; set; } | |
public object Id { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/"> | |
<sitecore role:require="Standalone or ContentManagement or ContentDelivery" search:require="solr"> | |
<contentSearch> | |
<indexConfigurations> | |
<defaultSolrIndexConfiguration type="Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration, Sitecore.ContentSearch.SolrProvider"> | |
<!-- Replace the SolrDocumentBuilder to the CustomDocumentBuilder --> | |
<documentBuilderType>NamespaceTo.CustomDocumentBuilder, YourAssembly</documentBuilderType> | |
</defaultSolrIndexConfiguration> | |
</indexConfigurations> | |
</contentSearch> | |
</sitecore> | |
</configuration> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment