Tuesday, November 21, 2017

Computed Index Field

In an include config:

  <sitecore>
        <contentSearch>
            <indexConfigurations>
                <defaultSolrIndexConfiguration>
                    <documentOptions>
                        <fields hint="raw:AddComputedIndexField">
                            <add fieldName="event_type_name" returnType="string">Car.Common.Website.Indexing.EventTypeComputedField, Car.Common.Website</add>
                            <add fieldName="keyword" returnType="string">Car.Common.Website.Indexing.KeywordComputedField, Car.Common.Website</add>
                            <add fieldName="category_name" returnType="string">Car.Common.Website.Indexing.CategoryComputedField, Car.Common.Website</add>
                        </fields>
                    </documentOptions>
                </defaultSolrIndexConfiguration>
            </indexConfigurations>
        </contentSearch>
</sitecore>

CODE:

using Car.Org.Website;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.ComputedFields;
using Sitecore.Data;
using Sitecore.Data.Items;
using System;

namespace Car.Org.Website.CustomSearchFields
{
    public class DatedInComputedField : IComputedIndexField
    {
        public string FieldName { get; set; }

        public string ReturnType { get; set; }

        public object ComputeFieldValue(IIndexable indexable)
        {
            Item i = indexable as SitecoreIndexableItem; 

            if (string.Compare(i.Database.Name, "core", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return null;
            }

            var getSearchDateFiltersItem = i.Database.GetItem(Constants.ItemIds.SearchDateFiltersFolder);

            if (getSearchDateFiltersItem != null && getSearchDateFiltersItem.HasChildren)
            {
                var dateItems = getSearchDateFiltersItem.GetChildren();

                foreach (Item dateRangeItem in dateItems)
                {
                    var days = dateRangeItem[new ID(Constants.FiledIDs.DateRangeField)];
                    var startDate = DateTime.Now.AddDays(int.Parse(days));  
                 
                    if(i.Statistics.Updated.Date > DateTime.Now.Date || (i.Statistics.Updated.Date <= DateTime.Now.Date && i.Statistics.Updated.Date > startDate.Date))
                    {
                        return dateRangeItem.ID.ToString();
                    }

                }
            }

            return null;
        }
    }
}

No comments:

Post a Comment