Giedrius
Giedrius

Reputation: 8550

Index not working with Raven DB, how to debug it?

I have an index:

public class FreeSearchIndex : 
    AbstractIndexCreationTask<Post, FreeSearchIndex.Result>
{
    public FreeSearchIndex()
    {
        Map = posts => from post in posts
                       select new
                          {
                              Query = post.Tags.Concat(new[]
                                       {
                                           post.Title,
                                           post.Body
                                       }),
                              DatePosted = post.Date
                          };

        Index(x => x.Query, FieldIndexing.Analyzed);            
    }

    public class Result
    {
        public object[] Query { get; set; }
        public DateTime DatePosted { get; set; }
    }
}

and have method:

public List<Post> Filter(string freeSearch)
{
    IQueryable<Post> posts;
    var posts = documentSession
            .Query<FreeSearchIndex.Result, FreeSearchIndex>()
            .Where(x => x.Query == (object)freeSearch)
            .OrderByDescending(x => x.DatePosted)
            .As<Post>();                                 

    return posts.ToList();
}

and have unit test:

[SetUp]
public void Setup()
{
    store = new EmbeddableDocumentStore
                {
                    RunInMemory = true
                };

    store.Initialize();

    session = store.OpenSession();

    IndexCreation.CreateIndexes(typeof(FreeSearchIndex).Assembly, store);
}

[Test]
public void GivenFreeSearchPhrase_Filter_ShouldOutputFilteredPostsByGivenPhrase()
{            
    session.Store(new Post { Body = "universal answer to everything is 42" });
    session.SaveChanges();

    var posts = Filter("everything");

    Assert.AreEqual(1, posts.Count);            
}

And it fails, because query returns 0 posts. How do I troubleshoot this? Should I check generated query, is it possible to check how it indexed fields in store (which is in memory)?

Upvotes: 2

Views: 381

Answers (1)

oleksii
oleksii

Reputation: 35935

I suspect the indexer just didn't have time to process new data. You may get this test passing from time to time depending on the machine load, CPU and memory performance. To the best of my knowledge you would need to use some sort of WaitForStale solution in the unit tests.

I got this from a RavenOverflow application on github

public abstract class RavenDbFactBase : IDisposable
{        
    public class NoStaleQueriesListener : IDocumentQueryListener
    {
        public void BeforeQueryExecuted(IDocumentQueryCustomization c)
        {
            c.WaitForNonStaleResults();
        }        
    }        
}

In production though, you do not use it and just bring stale data fast.

Upvotes: 4

Related Questions