Kentico: Example: Adding additional information to a document

In this article you’ll find:

Goal

The purpose of this article is to show you how to add additional information to a document. For the purpose of this tutorial, it will be assumed that you have inherited the Hawksearch.Kentico.Xperience.CMS.Services.Indexing.Indexer class and want to extend its behavior instead of writing your own Indexer from scratch.

Prerequisite

Steps to adding additional information to a document

  1. Override the GetDocuments method and write out your custom logic. For example the following snippet adds a custom field called “CustomEventItemFieldName” on all Documents which have a field with a name “ContentType” which has a value of “Event”.

    public override IEnumerable<SubmitDocument> GetDocuments(IEnumerable<FieldMappingInfo> fieldMappings, IEnumerable<string> identifiers = null) { var documents = base.GetDocuments(fieldMappings, identifiers); foreach (var document in documents) { if (document.Fields.Any(a => a.Name == "ContentType" && a.Values.Any(b => b == "Event"))) { document.Fields.Add(new SubmitField { Name = "CustomEventItemFieldName", Values = new List<string> { "CustomEventItemValue" } }); } } return documents; }

2. Override the CreateIndex method and make sure that the index has the field we just added to our documents.

public override string CreateIndex(IndexMappingInfo indexMapping, IEnumerable<FieldDefinition> fields) { var indexSuffix = indexMapping.IndexDisplayName.Replace(' ', '-').ToLower(); var indexFields = fields.ToList(); if (!indexFields.Any(a => a.Name == "CustomEventItemFieldName")) { indexFields.Add(new FieldDefinition { Name = "CustomEventItemFieldName", Type = "String", IncludeInResults = true }); } var createIndexResponseJson = this.Client.CreateIndex(indexFields, indexSuffix).Content.ReadAsStringAsync().Result; var createIndexResponse = JsonConvert.DeserializeObject<CreateIndexResponse>(createIndexResponseJson); return createIndexResponse.IndexName; }

3. That’s it. Our custom indexer will now add the custom field we created to every event item before sending it to Hawkseach.