Step1-CreateanewConsoleApplication
Thenextractthe
Lucene.Net.dllfromthe
Apache-Lucene.Net-2.9.2-incubating.bin.zipfileintoyour
libfolder.
You'llnoticelotsofotherbitsinthiszipfile.Especiallyofinteresttoyoulatermightbethestuffinthe
contribfolder.Imightgettothatinalatertutorial,butfornowletskeepitsimple.
Step2-AddaReferencetotheLucene.net.dll
Yourreferencesshouldlooklikethis
Step3-CreateaDocument
OkthenextstepistocreateasimpleDocumentwiththeappropriatefieldswhichyou'llwanttosearchon.Inourcasewe'regoingtocreate3cars.aFordFiesta,aFordFocusandaVauxhallAstra.
viewsource
print?
03 | using Lucene.Net.Analysis; |
04 | using Lucene.Net.Analysis.Standard; |
05 | using Lucene.Net.Documents; |
08 | using Directory=Lucene.Net.Store.Directory; |
09 | using Version=Lucene.Net.Util.Version; |
15 | static void
Main( string []args) |
17 | varfordFiesta= new
Document(); |
18 | fordFiesta.Add( new Field( "Id" , "1" , Field.Store.YES,Field.Index.NOT_ANALYZED)); |
19 | fordFiesta.Add( new Field( "Make" , "Ford" , Field.Store.YES,Field.Index.ANALYZED)); |
20 | fordFiesta.Add( new Field( "Model" , "Fiesta" , Field.Store.YES,Field.Index.ANALYZED)); |
22 | varfordFocus= new
Document(); |
23 | fordFocus.Add( new Field( "Id" , "2" , Field.Store.YES,Field.Index.NOT_ANALYZED)); |
24 | fordFocus.Add( new Field( "Make" , "Ford" , Field.Store.YES,Field.Index.ANALYZED)); |
25 | fordFocus.Add( new Field( "Model" , "Focus" , Field.Store.YES,Field.Index.ANALYZED)); |
27 | varvauxhallAstra= new
Document(); |
28 | vauxhallAstra.Add( new Field( "Id" , "3" , Field.Store.YES,Field.Index.NOT_ANALYZED)); |
29 | vauxhallAstra.Add( new Field( "Make" , "Vauxhall" , Field.Store.YES,Field.Index.ANALYZED)); |
30 | vauxhallAstra.Add( new Field( "Model" , "Astra" , Field.Store.YES,Field.Index.ANALYZED)); |
34 | Directorydirectory=FSDirectory.Open( new DirectoryInfo(Environment.CurrentDirectory+
"\\LuceneIndex" )); |
35 | Analyzeranalyzer= new
StandardAnalyzer(Version.LUCENE_29); |
38 | varwriter= new
IndexWriter(directory,analyzer, true ,IndexWriter.MaxFieldLength.LIMITED); |
39 | writer.AddDocument(fordFiesta); |
40 | writer.AddDocument(fordFocus); |
41 | writer.AddDocument(vauxhallAstra); |
InthecodeaboveyoucanseewefirstlycreateaseriesofDocumenttypes.ForeachdocumentwethendefineaseriesofFields.YoumightthinkthislookssimilartoSQLwhereyoucreatethetableschemaandeachDocument
islikearowinthetable!There'sanimportantdifferencehere,documentsdonothaveaschema.Ifwe'dwantedtoIcouldofgiventhe2ForddocumentsanextrafieldcalledSpecialFordFieldwhichwouldn'thaveexistedatallontheVauxhall
documents.
Step4-CreateaDirectory
Nowweneedtosortoutwherewe'regoingtostoreourindex:
viewsource
print?
1 | Directorydirectory=FSDirectory.Open( new DirectoryInfo(Environment.CurrentDirectory+
"\\LuceneIndex" )); |
TheabovecodecreatesaDirectory.thisistheplaceinwhichwestoreorwriteour
Indexto.InthiscaseweusetheFSDirectory.Open()
factorymethodtocreateanLuceneIndexontheFileSysteminafolder/directorycalledLuceneIndex.Wecouldofequallycreated
newRamDirectory()andjuststoredourindexinRAMforsuperhighperformancebutLuceneissofast,thatforthemostpartthisisunecessary.
Step5-TheAnalyzer
viewsource
print?
1 | Analyzeranalyzer= new StandardAnalyzer(Version.LUCENE_29); |
WenextcreateanewAnalyzerwhichessentiallyturnsourtextintoTokenswhicharestoredinour
Index.
Step6-WritingtheDocumentstotheIndex
FinallyweactuallyhavetowritetheDocumentstoour
Index
viewsource
print?
1 | varwriter= new IndexWriter(directory,analyzer,
true ,IndexWriter.MaxFieldLength.LIMITED); |
2 | writer.AddDocument(fordFiesta); |
3 | writer.AddDocument(fordFocus); |
4 | writer.AddDocument(vauxhallAstra); |
WedefineanIndexWritertellingittouseourDirectoryandAnalyzerdefinedabove.WethenaddallthedocumentstotheIndexWritercallthe
writer.Optimize()whichessentallydoesthesemi-equivilentofadefragontheindexandthenfinallywriter.Close().Atthispointwehaveaperfectlygoodindextosearch.
Step7-OpeningtheIndexforSearching
Oknowlet'sactuallysearchournewlycreatedindex.
viewsource
print?
1 | IndexReaderindexReader=IndexReader.Open(directory, true ); |
2 | SearcherindexSearch= new
IndexSearcher(indexReader); |
WefirstlyneedtoopenanIndexReaderherewe'repassingintheDirectorywecreatedaboveandwroteour
Documentsinto.AnIndexReadersimplyreadstheindexitdoesn'tdothemagicsearchpart.ForthatweneedaSearcherinourcasea
IndexSearcherwhichobviouslyneedstoreadourindexinternally.
Step8-CreatingourSearchQuery
Preparetosearchwithasimplesearchquery.Therealityisthatit'snotquiteassimpleastypinginaGooglequery,thoughit'snotfaroff.
viewsource
print?
1 | varqueryParser= new QueryParser(Version.LUCENE_29, "Make" ,analyzer); |
2 | varquery=queryParser.Parse( "Ford" ); |
Herewe'recreatingaQueryParserandspecifyingthatwewanttosearchthe
MakefieldofourIndex.ItistotallypossibletosearchmorethanonefieldbutforsimplicityI'mnotgoingtodothathere.WealsousethesameStandardAnalyzerweuseabovetoapplythesametokenizationtoourquery.
FinallyweparseourrawqueryFord.Sohopefullywe'llbeabletofindsomeFordcarsinourIndexspecificallyintheMakefield.
Step9-PerformingtheSearch
viewsource
print?
1 | Console.WriteLine( "Searchingfor:" +query.ToString()); |
2 | TopDocsresultDocs=indexSearch.Search(query,indexReader.MaxDoc()); |
4 | Console.WriteLine( "ResultsFound:" +resultDocs.totalHits); |
AboveweperformoursearchandreturntheTopDocsthatmatch.Hopefullythisshouldbe2resultsifyoursisanythinglikemine.Thereareindeed2
Fordsinourindex.
Step10-DisplayingourSearchResults
Lastpart.wejustquicklyloopthroughandprintoutthecarsthatmatch.
viewsource
print?
1 | varhits=resultDocs.scoreDocs;
|
4 | vardocumentFromSearcher=indexSearch.Doc(hit.doc); |
5 | Console.WriteLine(documentFromSearcher.Get( "Make" )+ ""
+documentFromSearcher.Get( "Model" )); |
That'sit,goodluck,hopeyoufindwhatyou'relookingfor.
FullDownloadoftheLucene.Nettutorial