Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,128 | Comments: 45,550

filter by tags archive

Raven Suggest: Review & Options

time to read 10 min | 1834 words

Phil Jones has posted some demo code for doing suggestions in RavenDB.

        public JsonResult CompanySuggestions(string term)
            var rq = RavenSession.Query<Company, Companies_QueryIndex>();

            var ravenResults = rq.Search(x => x.Name, string.Format("*{0}*", term), 
escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards,
options: SearchOptions.And) .Take(5) .ToList(); return Json(ravenResults.Select(x => new { id = x.Id, value = x.Name, description = string.Format("({0}, {1})", x.Category, x.Location) })); }


And the data looks like this:


The Companies_QueryIndex is a simple one, with the Name field marked as analyzed.

This code works, but it isn’t ideal. In fact, it contains an major problem. It uses string.Format("*{0}*", term), which is identical to doing a Foo LIKE ‘%’ + @term +’%’ in SQL. And bad for the same reason, it means that we can’t use the index efficiently, but have to scan the entire index.

The test app also populate the database with about 30,000 documents, enough to get a handle on how thins are going, even if this is a relatively small data set. Let us see how this actually behaves:



There are a few things to note here:

  • The query time is significant. – Leading wildcard queries tend to be expensive, they are essentially an O(N) query.
  • The results are… interesting. – In particular, look at the first few results, they are a match, but not what I would have expected.

A very simple change would be:



All I did was remove the leading wildcard, and suddenly the results look at a lot nicer, if only because they are closer to what I am actually searching on. By the way, note that in the last result, we are actually finding a company whose second name starts with Lua, it isn’t just a raw StartsWith, since we are actually working on individual tokens levels, not the entire name level. This is because we indexed the Name as analyzed.

Let us see how this plays out in the actual app, first, using *term*:


Now, using term*:


That is somewhat better, but the results are still poor in terms of search relevance. Let us try something a little bit different:

 var ravenResults = rq
    .Search(x => x.Name, term)
    .Search(x=>x.Name, term + "*", escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard
.Take(5) .ToList();

Here we force the search to search for the user’s actual term, as well as terms that starts with it. This means that any results that actually contains the name will stand up:


The most important thing about searching is to know that the problem is NOT that you can’t find enough information, it is that you find too much information that is not relevant.

But a better alternative all together might be using RavenDB suggest feature:

public JsonResult CompanySuggestions(string term)
    var rq = RavenSession.Query<Company, Companies_QueryIndex>()
        .Search(x => x.Name, term)

    var ravenResults = rq

    if(ravenResults.Count < 5)
        var suggestionQueryResult = rq.Suggest();

        ravenResults.AddRange(RavenSession.Query<Company, Companies_QueryIndex>()
                                  .Search(x => x.Name, string.Join(" ", suggestionQueryResult.Suggestions))
                                  .Take(5 - ravenResults.Count));

    return Json(ravenResults.Select(x => new
        id = x.Id,
        value = x.Name,
        description = string.Format("({0}, {1})", x.Category, x.Location)

Which result in:


What we are doing here is basically query the database for exact matches. Then, if we have no matches, we ask RavenDB to suggest additional words, and then query for those.

Here are the raw network traffic:

Query:  Name:<<lua>>
        Time: 1 ms
        Index: Companies/QueryIndex
        Results: 1 returned out of 1 total.

    Index: Companies/QueryIndex
    Term: lua
Time: 1 ms Query: Name:<<wlua luaz luka luau laua luoa lue luw lut lum luj lui lug luf lwa>> Time: 3 ms Index: Companies/QueryIndex Results: 4 returned out of 22 total.

As you can see, the speed difference between this and the first version is non trivial. More than that, note that it found companies with names such as “wlua”, which was also found in the first (*term*) version.

Just about any searching strategy would require that you take into account the dataset, the customer requirements, the user behavior and many more. But I would start with the suggestion option before I would go to anything as brute force as *term*.


Phil Jones

Hi Ayende,

Thanks for the helpful code samples.

I've posted a few blogs to go along with your one as well:

RavenSuggest: The Wrong Approach http://blog.orangelightning.co.uk/2012/07/ravensuggest-wrong-approach/

RavenSuggest: A Better Approach http://blog.orangelightning.co.uk/2012/07/ravensuggest-a-better-approach/

I have also put your suggested changes into the demo code and pushed it to GitHub.

I plan to experiment with the code more and see if I can make it even better!


Pure Krome

Love it Ayende!!!!!


Hi Ayende,

I'm struggling here to see how the final solution produces better results than the penultimate one??

The final solution produces "Lut Ezzkdaba Ltd" as its 2nd result, which looks like a worse match than "Luaeocrv B Ltd" and "Luaqesof S Ltd" (from the penultimate version) to me!

It actually looks to me like the final solution masks genuine results that are much more likely to be what the user is searching for!



Ayende Rahien

James_2JS, I had to google penultimate to figure out what it means.

And the answer to that is that it actually depends. In this case, we provide search with typo protection, so if you typed lua instead of lut, you get it. You can actually mix the two together easily enough, and get even better results.

The reason it depends is that it really matter what you are doing, what the source data is, etc. In this case, the data is actually randomly generated, so it isn't very meaningful.

Steve Py

James +1: I was left wondering why the last would be considered better... But if the results can be mixed efficiently without doubling up the query time then that's awesome.

Comment preview

Comments have been closed on this topic.


  1. The worker pattern - 18 hours from now

There are posts all the way to May 30, 2016


  1. The design of RavenDB 4.0 (14):
    26 May 2016 - The client side
  2. RavenDB 3.5 whirl wind tour (14):
    25 May 2016 - Got anything to declare, ya smuggler?
  3. Tasks for the new comer (2):
    15 Apr 2016 - Quartz.NET with RavenDB
  4. Code through the looking glass (5):
    18 Mar 2016 - And a linear search to rule them
  5. Find the bug (8):
    29 Feb 2016 - When you can't rely on your own identity
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats