C#Solr查询 - 如何仅获取未来日期?

时间:2017-12-14 14:59:09

标签: c# date solr filter

我有一个搜索方法,用于查询Solr的事件项。我需要将其修改为仅获取日期尚未过去的事件(即Where(x => x.EventDate.Date> = DateTime.Now.Date),但我不确定如何添加此项,因为我对Solr不太熟悉。这是我的搜索功能:

public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
  var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
                    {
                      new IsSearchablePredicateBuilder()
                    };

  if (contentTypeFilters.Any())
  {
    var contentTypePredicateBuilder = new ContentTypePredicateBuilder();

    contentTypePredicateBuilder.ContentTypes = contentTypeFilters;

    searchFilters.Add(contentTypePredicateBuilder);
  }

  if (otherFilters.Any())
  {
    var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);

    searchFilters.Add(tagFilterBuilder);
  }

  if (string.IsNullOrWhiteSpace(keywords))
  {
    keywords = "";
  }

  SearchRequest searchRequest = new SearchRequest();
  var queryParams = new Dictionary<string, string>() { };
  queryParams.Add("q", keywords);


  searchRequest.QueryParameters = queryParams;
  searchRequest.SortBy = "";
  searchRequest.SortOrder = "";

  SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
  queryArguments.FilterBuilders = searchFilters;

  queryArguments.Page = page;
  queryArguments.PerPage = perPage;
  queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
  queryArguments.SearchRequest = searchRequest;
  queryArguments.IndexName = _indexName;
  if (string.IsNullOrWhiteSpace(keywords))
  {
    queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
  }
  else
  {
    queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
  }

  queryArguments.SortBuilder = sortBuilder;

  try
  {
    var results = _searchManager.GetResults<SearchResultItem>(queryArguments);


    SearchQueryResults queryResults = new SearchQueryResults();
    queryResults.ResultItems = results.Results;
    queryResults.CurrentPage = page;

    queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());

    queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;


    return queryResults;
  }
  catch (Exception exc)
  {
    Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
    return null;
  }
}

以下是它的调用方式:

Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
    new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));

如何添加日期过滤,以便它只返回日期为未来的项目?

1 个答案:

答案 0 :(得分:0)

我会将过滤查询添加到过滤日期字段的现有列表中。在文档页面上,我能够找到有关fluent API的信息,这可能会对此有所帮助

Query.Field("date").From(DateTime.Now)

我不是C#开发人员,这段代码可能会有一些错误,但我认为主要想法是明确需要做什么。