Search Basics – Lucene.NET
March 14th, 2009 by TrilobyteIn this article I will show you how to implement a basic Lucene searcher which searches through the index created in the previous article. I assume you have read my previous article and that you have the index application up and running, if not: you can download the source code of our starting point here.
First reference some additional namespaces:
using Lucene.Net.QueryParsers; using Lucene.Net.Search;
Add the following code to Program.Main(), under the call to IndexBooks():
// search the created index Search(indexPath, "Sequel");
We pass the path to the index we want to search and the term we want to search on.
And here is the Search() function:
private static void Search(string indexPath, string term)
{
// create searcher
var searcher = new IndexSearcher(indexPath);
// create a query which searches through the title and description, the term can be in the title or the description
Query searchQuery = MultiFieldQueryParser.Parse(term, new[] {"title", "description"}, new[] {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD}, new StandardAnalyzer());
// perform the search
Hits hits = searcher.Search(searchQuery);
// loop through all the hits and show their title
for (int hitIndex = 0; hitIndex < hits.Length(); hitIndex++)
{
// get the corresponding document
Document hitDocument = hits.Doc(hitIndex);
// write its title to the console
Console.WriteLine(hitDocument.GetField("title").StringValue());
}
}
This function does the heavy lifting in our search implementation. First we open an index reader using the specified index path. Then we create a query which searches through the title or description field in the index using the specified term. With the call to searcer.Search() we actually perform the search. Next we loop through all the hits returned by the searcher and write their title to the console.
That is it for this article, you can download the full source code here, in the next article I will show you how you can implement alternatives.