Document

Lucene.net 基本示例 《第一篇》

  Lucene.net是java平台搜索插件Lucene的移植版。它的主要用于开发搜索引擎,站内搜索等。

  开篇之前,写个最简单的DEMO,让自己先体验下Lucene.net的魅力,顺便搭建环境。

复制代码
        static void Main(string[] args)
        {
            //写入数据到索引
            Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
            Directory directory = new RAMDirectory();
            IndexWriter.MaxFieldLength maxFieldLength = new IndexWriter.MaxFieldLength(10000);

            using (IndexWriter writer = new IndexWriter(directory, analyzer, maxFieldLength))
            {
                Document document1 = new Document();
                document1.Add(new Field("Sentence", "刘备", Field.Store.YES, Field.Index.ANALYZED));
                writer.AddDocument(document1);

                Document document2 = new Document();
                document2.Add(new Field("Sentence", "张飞", Field.Store.YES, Field.Index.ANALYZED));
                writer.AddDocument(document2);

                Document document3 = new Document();
                document3.Add(new Field("Sentence", "关羽", Field.Store.YES, Field.Index.ANALYZED));
                writer.AddDocument(document3);

                writer.Optimize();
            }

            //查找
            using (IndexSearcher searcher = new IndexSearcher(directory))
            {
                Term t = new Term("Sentence", "飞");
                Query query = new TermQuery(t);
                TopDocs docs = searcher.Search(query, null, 1000);
                Console.WriteLine(docs.TotalHits);
                Console.WriteLine(docs.ScoreDocs[0].Doc);
                Document doc = searcher.Doc(docs.ScoreDocs[0].Doc);
                Console.WriteLine(doc.Get("Sentence"));
            }
            Console.ReadKey();
        }
复制代码

  以上示例输出如下:

  

posted @ 2016-05-05 14:58  从未被超越  阅读(415)  评论(0编辑  收藏  举报