Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add documents in Lucene.Net.Linq?

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?

like image 475
Jesse C. Slicer Avatar asked Mar 21 '23 13:03

Jesse C. Slicer


1 Answers

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.

like image 83
Chris Eldredge Avatar answered Apr 20 '23 23:04

Chris Eldredge