How to specify a ranking for NHibernate search results, based on location of search term in results?
I have a paged list of search results. A user can search for 'derp' and anything with that sequence of characters anywhere in the name is returned.
I've been asked to change this so that 开发者_如何学编程this set of results will initially be ranked by relevance. So if normally the list would be returned as
a derp abc // everything is alphabetical
a derp xyz
b derp abc
derp abc
derp def
herp derp a
herp derp b
now the list needs to be sorted as
derp abc // these guys are given prominence
derp def
a derp abc // the rest of results alphabetical as normal
a derp xyz
b derp abc
herp derp a
herp derp b
keeping in mind that this list has to be paged (i.e. I can't just take the search result and manually remove occurrences of 'derp' from the middle and move them to the front), Is there any way with NHibernate that I can specify a required ranking?
Or do I have to do 2 queries, first searching for anything that starts with 'derp' and the second that contains 'derp' but doesn't start with it?
OrderBy can use Projections, so this will work just fine:
var list = session.QueryOver<Store>()
.Where(s => s.Name.IsLike("My", MatchMode.Anywhere))
.OrderBy(NHibernate.Criterion.Projections.Conditional(
NHibernate.Criterion.Restrictions.Like(
NHibernate.Criterion.Projections.Property<Store>(s => s.Name), "My",
MatchMode.Start),
NHibernate.Criterion.Projections.Constant(0),
NHibernate.Criterion.Projections.Constant(1))).Asc
.ThenBy(s => s.Name).Asc
.List();
What we are doing here is using a Projection that basically translates to the following SQL:
ORDER BY (case when this_.Name like 'My%' then 0 else 1 end)
精彩评论