Tuesday, October 23, 2007

Tutorial: implementing lucene.NET search

The following code implements a lucene.NET search routine, ready to run: C# Code
/// <summary> /// Searches for a specified string using the built-in lucene.net engine /// </summary> /// <param name="searchString">the string to search for</param> /// <param name="indexName">the name of the index</param> /// <param name="databaseName">the database to perform the search within</param> /// <returns>System.Collections.Generic.List<Sitecore.Data.Items.Item></returns> public List<Item> Search(string searchString, string indexName, string databaseName) { // initially set up the returning results list List<Item> results = new List<Item>(); // make sure string is not empty prior to starting the search if (searchString != string.Empty) { // get the specified index Index searchIndex = Sitecore.Configuration.Factory.GetIndex(indexName); // allocate a collection of hits.. Hits hits = null; // get the database to perform the search in.. Database db = Sitecore.Configuration.Factory.GetDatabase(databaseName); try { // run the search.. hits = searchIndex.Search(searchString, db); } catch (Exception ex) { // log error message to the sitecore log file.. Sitecore.Diagnostics.Log.Error("Custom Search failed with the following message: " + ex.Message, this); // .. and return null.. return null; } // iterate thru the hits we got from the search for (int i = 0; i < hits.Length(); i++) { // get a document referrer.. Document document = hits.Doc(i); // .. so we can get the id.. string itemID = document.Get("_docID"); // .. so we can get a pointer to the item in itself.. ItemPointer pointer = ItemPointer.Parse(itemID); // .. so we can get the actual item.. Item itm = Sitecore.Configuration.Factory.GetDatabase(databaseName).Items[pointer.ItemID, pointer.Language, pointer.Version]; // .. so we finally can add the item to the returning list if (itm != null) { results.Add(itm); } }
Usage example searching for "sample" in the system index in the master database:
System.Collections.Generic.List<Sitecore.Data.Items.Item> searchresults = Search("sample", "system", "master");
Extended usage example To use it on a site you could for example create a sublayout with a simple textbox and button, then hook it up to the routine and you'd be set to go.. something like: (this example assumes the existance of the SearchButton and SearchTextBox)
protected void SearchButton_Click(object sender, EventArgs e) { // get search, usually directly from a textbox string search = SearchTextBox.Text.Trim(); // try to get search results from a specified index List<Item> searchresults = Search(search, "system", "master"); // validate existing result prior to moving on if (searchresults!=null && searchresults.Count>0) { // step thru the items we've found in the search foreach (Item itm in searchresults) { // output the search results.. Response.Write(itm.Name + ": " + itm.Paths.GetFriendlyUrl(true)); } } }
Other information Add a reference to:
the Lucene.NET dll
add using declarations:
using Lucene.Net; using Lucene.Net.Search; using Lucene.Net.Documents;
Regards, P.

4 comments:

Anonymous said...

Nice one,

Could you please package this one and put it on the snippets section on sdn?

Alternatively send it to me, - and I can do it.

Unknown said...

This is great! Thanks Peter! We need more examples on how to work with Lucene.

Anonymous said...

Good one.
But i need with sorting options so that i used Search Lucene Index in C# it was so helpful thanks anyway

Corey said...

If you are looking for another Lucene.NET example, I use Lucene.NET in my open source bug tracking application, BugTracker.NET.

I created a little Lucene.NET, ASP.NET tutorial here