Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Goal

The aim of this article is to demonstrate how to index DateTime fields so that their type is properly parsed passed to the Hawksearch API.

...

  1. Navigate to Administration → Search indexes (your-site-domain/Sitefinity/Administration/Search)

  2. Open the index for editing

  3. Under Advanced → Additional fields for indexing add the fields e.g. Lastmodified, DateCreated

  4. Save the changes

...

Code Block
languagec#
using System;
using System.Collections.Generic;
using System.Linq;
using Hawksearch.Search;
using Telerik.Sitefinity.Configuration;
using Telerik.Sitefinity.Services.Search;

namespace SitefinityWebApp
{
    public class CustomSearchService : HawksearchService
    {
        public override void CreateIndex(string sitefinityIndexName, IEnumerable<IFieldDefinition> fieldDefinitions)
        {
            var definitionList = new List<IFieldDefinition>(fieldDefinitions);

            this.ModifyDatetimeFields(definitionList);

            base.CreateIndex(sitefinityIndexName, definitionList);
        }

        private void ModifyDatetimeFields(List<IFieldDefinition> definitionList)
        {
            var configManager = ConfigManager.GetManager();
            var section = configManager.GetSection<DatetimeFieldsConfig>();

            if (section != null)
            {
                var dateTimeFields = section.DatetimeFields.Keys;

                foreach (var field in dateTimeFields)
                {
                    var dateTimeField = definitionList.FirstOrDefault(f => f.Name == field);

                    if (dateTimeField != null)
                    {
                        definitionList.Remove(dateTimeField);

                        var dateTimeFieldDefinition = Telerik.Sitefinity.Abstractions.ObjectFactory.Resolve<IFieldDefinition>();
                        dateTimeFieldDefinition.Name = "Datetime"dateTimeField.Name;
                        dateTimeFieldDefinition.Type = typeof(DateTime);

                        definitionList.Add(dateTimeFieldDefinition);
                    }
                }
            }
        }
    }
}

...