一个Lucene例子

public void Test1()
        
{
            
//建立一个内存目录
            Lucene.Net.Store.RAMDirectory ramDir = new Lucene.Net.Store.RAMDirectory();

            
//建立一个索引书写器
            IndexWriter ramWriter = new IndexWriter(ramDir,new ChineseAnalyzer(), true);

            
//要索引的词/文件(把下面的每个字符串换成每个文件的内容即可)
            string[] words = {"中华人民共和国""人民共和国""人民","共和国"};  

            
//循环数组,创建文档,给文档添加字段,并把文档添加到索引书写器里
            Document doc = null;  
            
for (int i = 0; i < words.Length; i++)
            
{
                doc 
= new Document();
                doc.Add(Field.Text(
"contents", words[i]));
                ramWriter.AddDocument(doc);
            }


            
//索引优化
            ramWriter.Optimize();

            
//关闭索引读写器,一定要关哦,按理说应该把上面的代码用try括主,在finally里关闭索引书写器
            ramWriter.Close();

            
//构建一个索引搜索器
            IndexSearcher searcher = new IndexSearcher(ramDir);

            
//用QueryParser.Parse方法实例化一个查询
            Query query = QueryParser.Parse("人民""contents"new ChineseAnalyzer());

            
//获取搜索结果
            Hits hits = searcher.Search(query);

            
//判断是否有搜索到的结果,当然你也可以遍历结果集并输出
            
//if (hits.Length() != 0)
            
//    MessageBox.Show("有");
            
//else
            
//    MessageBox.Show("没有");
            for (int i = 0; i < hits.Length(); i++)
            
{
                Document _doc 
= hits.Doc(i);
                MessageBox.Show(_doc.Get(
"contents"));
            }

        }


posted @ 2011-03-04 17:30  Ken-Cai  阅读(207)  评论(0编辑  收藏  举报