How to create and search a Lucene.Net index in 4 simple steps using C#, Step 3

Perform the search.

In this step we will use the query which was created using the query parser to perform the search on the index we created in step 1.

The Searcher class needs to be told where the index we want to search is. We will create a directory class to hold this information and then pass it to the searcher.

Lucene.Net.Store.Directory directory = 
  Lucene.Net.Store.FSDirectory.Open(new
    System.IO.DirectoryInfo(@"C:\xx\index"));

And then create the searcher class using the directory we just created and a Boolean, set to true, opening the index in read-only mode.

Lucene.Net.Search.Searcher searcher = 
  new Lucene.Net.Search.IndexSearcher
    (Lucene.Net.Index.IndexReader.Open(directory, true));

There are some implementations of a Lucene.Net search solution that need access to an Index reader. For example, if you wanted to access some of the Term Vector information, this would be available via the Index Reader class. However, we do not need an instance of the reader class and therefore pass it as a parameter to the IndexSearch class. Shown above.

There are a number of ways to store the results of the search. These are called collectors. Some common collector classes are listed in the below table.

Collector Class Description
TopDocsCollector Read a certain number of Top N document after a search
TopScoreDocCollector Sorted by highest scoring document
TopFieldCollector Sorted by field, score
TimeLimitingCollector Times out if time exceeds threshold
PositiveScoreOnlyCollector Returns documents with a score greater than 0

For this example, I will use the TopScoreDocCollector. I pass the create method of the TopScoreDocCollector class 2 parameters. An integer which defines the maximum number of documents I want and a Boolean which determines whether to score the docs in order.

TopScoreDocCollector collector = 
    TopScoreDocCollector.create(100, true);

I pass the collector and the query (created in Part 2) to the Search method of the Searcher class.

searcher.Search(query, collector);
ScoreDoc[] hits = collector.TopDocs().scoreDocs; 

Lastly, I capture the result in a ScoreDoc array, as shown above.




Leave a Comment

Your email address will not be published.