Return to doc.sitecore.com

Valid for Sitecore 5.2, 5.3
Indexing a Database with Lucene.NET

Q:

How to index a database with Lucene.NET?

A:

Lucene.NET search for the website is implemented in SC Printers Demo site. Sitecore demo site can be found here:

http://sdn.sitecore.net/Resources/Shared%20Source/Demo%20Sites/Demonstration%20Site.html

The site contains the source codes including the search logic (see \SCPrintersDemoRoot\layouts\search.ascx.cs file).

There is no user interface for managing indexes. The API should be used for this purpose.

You can create your own index for any of the databases. See the example below:

 

1.  Add the new index in web.config for, say, Master database:

<indexes>
    ...
    
<index id="mastercustomindex" singleInstance="true" type="Sitecore.Data.Indexing.Index, Sitecore.Kernel">
      
<param desc="name">$(id)</param>
      
<templates hint="list:AddTemplate">
        
<template>document</template>            // Which Templates will be indexing
      
</templates>
      
<fields hint="raw:AddField">
        
<field>title</field>                                   // Which Fields will be indexing
        
<field storage="unstored">text</field>
      
</fields>
    
</index>
    ...
    
</indexes>
      
<database id="master" singleInstance="true" type="Sitecore.Data.Database, Sitecore.Kernel">
        
<param desc="name">$(id)</param>
          ...
        
<indexes hint="list:AddIndex">
          
<index path="indexes/index[@id='mastercustomindex']"/>
        
</indexes>
          ...

2.  Here is a sublayout sample code which uses mastercustomindex.

private void SearchButton_Click(object sender, System.EventArgs e)
  {
             ArrayList results
= new ArrayList();
             SearchResultsPanel.Controls.Clear();
            
string search = SearchTextBox.Text.Trim();
            
if (search != string.Empty)
             {
  
// Getting index from the web.config
   Index webIndex = Sitecore.Configuration.Factory.GetIndex("mastercustomindex");
  
// The search itself
   Hits hits = null;
   Database db
= Sitecore.Configuration.Factory.GetDatabase("master");
  
try
   {
       hits
= webIndex.Search search, db);
   }
  
catch (Exception ex)
   {
       Response.Write (
"The search failed with the following message: "+ ex.Message);
        
return;
   }
  
// Looping through the search results
   for (int i = 0; i < hits.Length(); i++)
   {
          Document document
= hits.Doc(i);
          
string itemID = document.Get("_docID");
          ItemPointer pointer
= ItemPointer.Parse(itemID);
          Item itm
= Factory.GetDatabase("master").Items[pointer.ItemID, pointer.Language, pointer.Version];
          Response.Write(
"<a href=\"" + itm.Paths.GetFriendlyUrl(true) + "\" target=\"_blank\" >" + itm.Name + "</a><br/>");
          Response.Write(
"<br/>");
   }
             }
  }

Related reading: