Having troubles in ordering search results using Lucene

178 views Asked by At

I am running search query as following to bring results from Dynamics CRM. Search is working fine but it is brining results based on relevance. We want to order them in descending order of 'createdon' field. As we are displaying only 10 results per page, so I can't sort the result returned by this query.

Is there any way to order based on a field?

public IEnumerable<SearchResult> Search(string term, int? pageNumber, int 
        pageSize, out int totalHits, IEnumerable<string> logicalName)
{
    var searchProvider = SearchManager.Provider;
    var query = new CrmEntityQuery(term, pageNumber.GetValueOrDefault(1), pageSize, logicalNames);

    return GetSearchResults(out totalHits, searchProvider, query);        
}

private IEnumerable<SearchResult> GetSearchResults(out int totalHits, 
                 SearchProvider searchProvider, CrmEntityQuery query)
{
    using (ICrmEntityIndexSearcher searcher = searchProvider.GetIndexSearcher())
    {                
        Portal.StoreRequestItem("SearchDeduplicateListForAuthorisation", new List<Guid>());
        var results = searcher.Search(query);
        totalHits = results.ApproximateTotalHits;

        return from x in results
             select new SearchResult(x);
    }
}
1

There are 1 answers

6
James Wood On

Not used Lucene myself, so cant comment on that.

However, if you were doing this in basic CRM. You would use a QueryExpression with an OrderExpression. Then when you page the results they are paged in order.

Here is an example of a QueryExpression, with an OrderExpression, and paging.

Page large result sets with QueryExpression

Presumably at some point the data is being pulled out of CRM, either within Lucene, or your own code, maybe in CrmEntityQuery? Then you can add the sort there.