Query Sitecore Lucene-index with ContentSearch-API on DateTime-range

耗尽温柔 提交于 2019-12-05 19:26:01

Try the following :

private void GetItems(int month, int year)
        {
            DateTime startDate = new DateTime(year,month,1);
            DateTime endDate = new DateTime(year,month, DateTime.DaysInMonth(year, month));
            using ( IProviderSearchContext context = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
            {
                List<EventSearchResultItem> allEvents = context.GetQueryable<EventSearchResultItem>(new CultureExecutionContext(Sitecore.Context.Language.CultureInfo))
                .Where(s =>
                       s.TemplateId == this.EventTemplateID &&
                       ((s.BeginDate >= startDate) || (s.EndDate <= endDate))
                           )
               .ToList();
            }
        }

Edit: Just to explain why you approach didn't work, when lucene index any date field, it gets indexed as number, the format will be 'yyyyMMdd', for example 18 Feb 2014 is indexed as 20140218, so as you can see it get stored as a whole number, and the year,month and day are in the same field, so you can't compare with year only or month only etc.

Now in Sitecore linq, if you want to query against a date field, you MUST compare with a 'DateTime' type, Sitecore knows that DateTime object must be converted to 'yyyyMMdd' format before passing this to Lucene.

You could try to remove the underscores from the field definition in the index configuration and in the EventSearchResult item. I've seen issues with this before.

<field luceneName="begindate" storageType="yes" indexType="tokenized" format="yyyyMMdd">Begin Date</field>
<field luceneName="enddate" storageType="yes" indexType="tokenized" format="yyyyMMdd">End Date</field>

[TypeConverter(typeof(IndexFieldDateTimeValueConverter))]
    [IndexField("begindate")]
    public DateTime BeginDate { get; set; }

    [TypeConverter(typeof(IndexFieldDateTimeValueConverter))]
    [IndexField("enddate")]
    public DateTime EndDate { get; set; }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!