Gavin
Gavin

Reputation: 5871

Lucene.Net - how to retrieve a single Document

In Lucene.Net how do I retrive a single Document based on a Field value? The Field value will always be unique to a single document in this case.

The Field I wish to use is "Id" from this is the structure of my document:

var doc = new Document();

// Add lucene fields mapped to DB fields
doc.Add(new Field("Id", searchResult.Id, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("Name", searchResult.Name, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Region", searchResult.Region, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Type", searchResult.Type, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("Permalink", searchResult.Permalink, Field.Store.YES, Field.Index.NOT_ANALYZED));

I can find lots of examples of searching Lucene for multiple results, but nothing for retrieving a single item. I'm sure it must be possible as I imagine it would be required for updating only a specific Document in Lucene.

I imagine the first step is to change the "Id" Field to ANALYZED rather than NOT_ANALYZED and rebuild the index.

I feel that there is probably a nice simple method I haven't stumbled across yet for retrieving a single Document rather than using a QueryParser?

Upvotes: 2

Views: 1805

Answers (2)

christofr
christofr

Reputation: 2700

Fetching a single document using Lucene.Net 3.0.3

        //Set up
        var directory = FSDirectory.Open(new DirectoryInfo("/path/to/your/index"));
        var reader = IndexReader.Open(directory, false);
        var searcher = new IndexSearcher(reader);

        //find your document location
        var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
        var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "_id", analyzer).Parse("_id:1");
        var result = searcher.Search(query, 1).ScoreDocs.FirstOrDefault();

        //Fetch a document by index number. This index number is stored as an integer in result.Doc
        Document d = searcher.Doc(result.Doc);

        //return
        return d;

Upvotes: 1

LuckyS
LuckyS

Reputation: 553

You can use query parser it's better approach in lucene to add document and I used this to create index in many projects,

doc.Add(new Field("Id", searchResult.Id,Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));    

Upvotes: 1

Related Questions