Question

The Lucene.Net.Linq project seems pretty powerful and while querying seems pretty simple, I'm not quite sure how to add/update documents. Can an example or two be provided?

Was it helpful?

Solution

There are some full examples in the test project at https://github.com/themotleyfool/Lucene.Net.Linq/tree/master/source/Lucene.Net.Linq.Tests/Samples.

Once you've configured your mappings and initialized your provider, you make updates by opening a session:

var directory = new RAMDirectory();

var provider = new LuceneDataProvider(directory, Version.LUCENE_30);

using (var session = provider.OpenSession<Article>())
{
    session.Add(new Article {Author = "John Doe", BodyText = "some body text", PublishDate = DateTimeOffset.UtcNow});
}

You can also update existing documents. Simply retrieve the item from the session, and the session will detect if a modification was made:

using (var session = provider.OpenSession<Article>())
{
    var item = session.Query().Single(i => i.Id == someId);
    item.Name = "updated";
}

Or you can delete documents:

using (var session = provider.OpenSession<Article>())
{
    var item = session.Query().Single(i => i.Id == someId);
    session.Delete(item);
}

When the session is disposed, all pending changes in the session are written to the index and then committed. This is done within a synchronization context to ensure all changes in the session are committed and seen atomically when queries are being executed on other threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top