Find the differences: The optimization that changed behavior

time to read 2 min | 254 words

I was thinking about ways of optimizing NHibernate Search’ behavior, and I run into a bug in my proposed solution. It is an interesting one, so I thought that would be make a good post.

Right now NHibernate Search behavior is similar to this:

public IList<T> Search<T>(string query)
{
var results = new List<T>();
foreach(var idAndClass in DoLuceneSearch(query))
{
var result = (T)session.Get(idAndClass.ClassName, idAndClass.Id);
if(result != null)
results.Add(result);
}
return results;
}

This isn’t the actual code, but it shows how NHibernate works. It also shows the problem that I thought about fixing. The way it is implemented now, NHibernate Search will create a SELECT N+1 query.

Now, the optimization is simply:

public IList<T> Search<T>(string query)
{
return session
.CreateCriteria<T>()
.Add(Restrictions.In("id", DoLuceneSearch(query).Select(x=>x.Id)))
.List();
}

There are at least two major differences between the behavior of the two versions, can you find them?