您的位置:首页 > 其它

lucene.net简单tutorial

2013-05-29 23:23 246 查看

Step1-CreateanewConsoleApplication

ThenextracttheLucene.Net.dllfromtheApache-Lucene.Net-2.9.2-incubating.bin.zipfileintoyourlibfolder.

You'llnoticelotsofotherbitsinthiszipfile.Especiallyofinteresttoyoulatermightbethestuffinthecontribfolder.Imightgettothatinalatertutorial,butfornowletskeepitsimple.

Step2-AddaReferencetotheLucene.net.dll

Yourreferencesshouldlooklikethis



Step3-CreateaDocument

OkthenextstepistocreateasimpleDocumentwiththeappropriatefieldswhichyou'llwanttosearchon.Inourcasewe'regoingtocreate3cars.aFordFiesta,aFordFocusandaVauxhallAstra.

viewsource

print?

01
using
System;
02
using
System.IO;
03
using
Lucene.Net.Analysis;
04
using
Lucene.Net.Analysis.Standard;
05
using
Lucene.Net.Documents;
06
using
Lucene.Net.Index;
07
using
Lucene.Net.Store;
08
using
Directory=Lucene.Net.Store.Directory;
09
using
Version=Lucene.Net.Util.Version;
10
11
namespace

LuceneNet.App
12
{
13
class
Program
14
{

15
static
void

Main(
string
[]args)
16
{
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));
21
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));
26
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));
31
32
33
34
Directorydirectory=FSDirectory.Open(
new
DirectoryInfo(Environment.CurrentDirectory+
"\\LuceneIndex"
));
35
Analyzeranalyzer=
new

StandardAnalyzer(Version.LUCENE_29);
36
37
38
varwriter=
new

IndexWriter(directory,analyzer,
true
,IndexWriter.MaxFieldLength.LIMITED);
39
writer.AddDocument(fordFiesta);
40
writer.AddDocument(fordFocus);
41
writer.AddDocument(vauxhallAstra);
42
43
writer.Optimize();
44
writer.Close();
45
46
47
48
}
49
}

50
}
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);
5
6
writer.Optimize();
7
writer.Close();
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
Make
fieldofourIndex.ItistotallypossibletosearchmorethanonefieldbutforsimplicityI'mnotgoingtodothathere.WealsousethesameStandardAnalyzerweuseabovetoapplythesametokenizationtoourquery.

FinallyweparseourrawqueryFord.Sohopefullywe'llbeabletofindsomeFordcarsinourIndexspecificallyintheMakefield.

Step9-PerformingtheSearch

viewsource

print?

1
Console.WriteLine(
"Searchingfor:"
+query.ToString());
2
TopDocsresultDocs=indexSearch.Search(query,indexReader.MaxDoc());
3
4
Console.WriteLine(
"ResultsFound:"
+resultDocs.totalHits);
AboveweperformoursearchandreturntheTopDocsthatmatch.Hopefullythisshouldbe2resultsifyoursisanythinglikemine.Thereareindeed2
Fordsinourindex.

Step10-DisplayingourSearchResults

Lastpart.wejustquicklyloopthroughandprintoutthecarsthatmatch.

viewsource

print?

1
varhits=resultDocs.scoreDocs;

2
foreach
(varhit
in
hits)

3
{
4
vardocumentFromSearcher=indexSearch.Doc(hit.doc);
5
Console.WriteLine(documentFromSearcher.Get(
"Make"
)+
""

+documentFromSearcher.Get(
"Model"
));
6
}
7
8
indexSearch.Close();
9
directory.Close();
That'sit,goodluck,hopeyoufindwhatyou'relookingfor.

FullDownloadoftheLucene.Nettutorial
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: