1.去 http://lucenenet.apache.org/ 下载lunece.net 文件
2.在项目添加引用Lucene.Net.dll
class Program
{
static void Main(string[] args)
{
//索引
Directory direcotry = FSDirectory.GetDirectory("LuceneIndex");
Analyzer analyzer = new StandardAnalyzer();
IndexWriter writer = new IndexWriter(direcotry,analyzer);
IndexReader red = IndexReader.Open(direcotry);
int totDocs = red.MaxDoc();
red.Close();
//添加文档到索引
string text = string.Empty;
Console.WriteLine("输入文本你想要添加到索引:");
Console.Write(">");
int txts = totDocs;
int j = 0;
while((text=Console.ReadLine())!=string.Empty)
{
AddTextToIndex(txts++,text,writer);
j++;
Console.Write(">");
}
writer.Optimize();
writer.Flush();
writer.Close();
Console.WriteLine(j + " lines added, " + txts + " documents total");
//搜索
IndexSearcher searcher = new IndexSearcher(direcotry);
QueryParser parser = new QueryParser("postBody", analyzer);
Console.WriteLine("输入搜索的文本:");
Console.Write(">");
while ((text = Console.ReadLine()) != String.Empty)
{
Search(text, searcher, parser);
Console.Write(">");
}
//关闭资源
searcher.Close();
direcotry.Close();
}
//搜索
private static void Search(string text,IndexSearcher searcher,QueryParser parser)
{ //条件
Query query = parser.Parse(text);
//搜索
Hits hits = searcher.Search(query);
//显示结果
Console.WriteLine("搜索 '" + text + "'");
int results = hits.Length();
Console.WriteLine("发现 {0} 结果", results);
for (int i = 0; i < results; i++)
{
Document doc = hits.Doc(i);
float score = hits.Score(i);
Console.WriteLine("--结果 num {0}, 耗时 {1}", i + 1, score);
Console.WriteLine("--ID: {0}", doc.Get("id"));
Console.WriteLine("--Text found: {0}" + Environment.NewLine, doc.Get("postBody"));
}
}
//添加文档到索引中
private static void AddTextToIndex(int txts,string text,IndexWriter writer)
{
Document doc = new Document();
doc.Add(new Field("id",text.ToString(),Field.Store.YES,Field.Index.UN_TOKENIZED));
doc.Add(new Field("postBody",text,Field.Store.YES,Field.Index.TOKENIZED));
writer.AddDocument(doc);
}
}
标签:检索,Console,text,writer,Lucene,WriteLine,doc,new,net
From: https://www.cnblogs.com/guangzhiruijie/p/18502811