Thursday, June 30, 2022

How to implement search in Sitecore website using Solr index?

1. Read language from context and parse the date 

string _language = Context.Language.Name;

            if (_language.ToLower() == "en")

            {

                CultureInfo jaJP = new CultureInfo("ar-QA");

                DateTime dtiDate = new DateTime();

                if (DateTime.TryParseExact(Date.ToString(), "dd/MM/yyyy", jaJP, DateTimeStyles.None, out dtiDate))

                {

                    Date = dtiDate.ToLocalTime();

                }

            }

            ItemManagement itemManagement = new ItemManagement(new SitecoreService(Sitecore.Context.Database));

            Item ItemPeriod = itemManagement.SitecoreService.GetItem<Item>(new Guid(Constants.AppSearchPeriodInfo));


2. Get database from context

            var _db = Context.Database;


3. Get index

            var _index = Sitecore.ContentSearch.ContentSearchManager.GetIndex(string.Format("sitecore_{0}_index", _db.Name.ToLower()));

            var _result = new List<SearchResultItem>();

            DateTime _dateTo = string.IsNullOrEmpty(Date.ToString()) ?

                DateTime.Now.ToUniversalTime().ToLocalTime() : DateTime.Parse(Date.ToString()).AddHours(23).AddMinutes(59).AddSeconds(59).ToUniversalTime().ToLocalTime();

            DateTime _dateFrom = string.IsNullOrEmpty(Date.ToString()) ?

                DateTime.Now.ToUniversalTime().ToLocalTime() : DateTime.Parse(Date.ToString()).ToUniversalTime().ToLocalTime();


4. Specify the template Id for which you want to make a search

            ID _templateId = Constants.PageTemplateID;

            var PgeSize = int.Parse(Sitecore.Configuration.Settings.GetSetting("PgeSize"));

            using (IProviderSearchContext context = _index.CreateSearchContext())

            {

                _result = context.GetQueryable<SearchResultItem>()

                   .Where(x => x.TemplateId == _templateId

                   && x.Language == _language)

                      .Where(x => ((DateTime)x[(ObjectIndexerKey)"date_tdt"]).Between(_dateFrom, _dateTo, Inclusion.Both))

                      .OrderByDescending(x => x["date_tdt"]).Skip((PageNo - 1) * PgeSize).Take(PgeSize).ToList();

            }

            return NewsBullitenArticlesData(_result);


5.  Iterate result received from Sitecore search API

ItemManagement itemManagement = new ItemManagement(new SitecoreService(Sitecore.Context.Database));


            List<Article > articalList= new List<Article >();

 foreach (var article in result)

            {

Article articleModel  = new Article ();

                        Item ItemNews = itemManagement.SitecoreService.GetItem<Item>(new Guid(article.ItemId.ToString()));


                        if (ItemNews != null && ItemNews.Fields.Count > 8)

                        {

                            DateTime dtiDate = new DateTime();

                            if (DateTime.TryParseExact(GetSiteCoreValue(ItemNews.Fields["Date"]), "yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out dtiDate))

                            {

                                articleModel  .Date = BlogsReFormatDateTimeToTimeAgo(dtiDate);

                            }

                            articleModel  .Date = oNewsBulliten.Date.Contains("00:") ? oNewsBulliten.Date.Replace("00:", "12:") : oNewsBulliten.Date;

                            articleModel  .ItemId = ItemNews.ID.ToString();

                            articleModel  .Title = GetSiteCoreValue(ItemNews.Fields["Main Title"]);

                            articleModel  .Description = GetSiteCoreValue(ItemNews.Fields["Body"]);

                            articleModel .Image= GetSiteCoreValue(ItemNews.Fields["Image"]);

                            var options = LinkManager.GetDefaultUrlOptions();

                            string link = LinkManager.GetItemUrl(ItemNews, options);

                            if (!string.IsNullOrEmpty(link))

                            {

                                articleModel  .URL = Sitecore.Configuration.Settings.GetSetting("QNADomain") + link;

                            }

                            articalList.Add(articleModel);

                        }

}

6. Final object-articalList for view integration

No comments:

Post a Comment

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally whi...