因为lucene.net 2.9.2 改变比较大,有一些之前公布的方法、构造函数被遗弃了,所以需要采用新的方法来编写代码。下面是我调整过后的代码,以便以后查找方便。也可以与大家一起学习。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Analysis; using Lucene.Net.Analysis.PanGu; namespace MyLuceneDemo { public class MySearch { private const string INDEXDIRECTORY = @"D:/DOTNET/Lucene/MyLuceneDemo/MyLuceneDemo/Demo_Index"; public MySearch() { Index(); List<string> list = new List<string>() { "测试"}; foreach (var item in list) { Console.WriteLine("搜索词:" + item); Console.WriteLine("结果:"); Searcher(item); Console.WriteLine("-------------------------------"); } } /// <summary> /// 搜索 /// </summary> /// <param name="queryString">搜索输入</param> private void Searcher(string queryString) { Directory directory = FSDirectory.Open(new System.IO.FileInfo(INDEXDIRECTORY)); IndexReader reader = IndexReader.Open(directory, true); Analyzer analyzer = new PanGuAnalyzer(); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "content", analyzer); Query query = parser.Parse(queryString); TopScoreDocCollector collector = TopScoreDocCollector.create(searcher.MaxDoc(), false); searcher.Search(query, collector); ScoreDoc[] hits = collector.TopDocs().scoreDocs; for (int i = 0; i < collector.GetTotalHits(); i++) { Document doc = searcher.Doc(hits[i].doc); Console.WriteLine(doc.Get("content") + "_得分:" + hits[i].score.ToString("f2")); } } /// <summary> /// 索引数据 /// </summary> private void Index() { Directory directory = FSDirectory.Open(new System.IO.DirectoryInfo(INDEXDIRECTORY),new SimpleFSLockFactory()); Analyzer analyzer = new PanGuAnalyzer(); IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.LIMITED); AddDoc(writer, "测试标题一", "测试内容一", 1.0f); AddDoc(writer, "测试标题二", "测试内容二", 1.0f); AddDoc(writer, "测试标题三", "测试内容三", 1.0f); AddDoc(writer, "测试标题四", "测试内容四", 1.0f); writer.Optimize(); writer.Close(); } /// <summary> /// 为索引准备数据 /// </summary> /// <param name="writer">索引实例</param> /// <param name="title">需要索引的数据</param> /// <param name="content">需要索引的数据</param> /// <param name="boost">文档权重</param> private void AddDoc(IndexWriter writer, string title, string content, float boost) { Document doc = new Document(); doc.Add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED)); doc.SetBoost(boost); writer.AddDocument(doc); } } }