Lucene.Net简单例子-01

前面已经简单介绍了Lucene.Net,下面来看一个实际的例子

1.1 引用必要的bll文件.这里不再介绍(Lucene.Net  PanGu  PanGu.HightLight  PanGu.Lucene.Analyzer) 

1.2 添加字典Dict,并设置到bin/debug目录下

1.3 创建Windows窗体应用程序

  1.3.1 添加按钮"创建索引库"

  1.3.2 添加按钮"搜索"  

using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BFFJ.LuceneNetDemo
{
    public partial class SearchTest : Form
    {
        public SearchTest()
        {
            InitializeComponent();
        }

        private void btnCreateIndex_Click(object sender, EventArgs e)
        {
            //01创建分词后的内容放目录
            string indexPath = @"E:LuceneNet测试文件索引文件";
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());//指定索引文件(打开索引目录) FS指的是就是FileSystem
            //判断目录是否存在(还可读取数据)
            bool isUpdate = IndexReader.IndexExists(directory);
            if (isUpdate)
            {
                //判断目录是否加锁
                if (IndexWriter.IsLocked(directory))
                {
                    IndexWriter.Unlock(directory);
                }
            }
            //向索引库中写数据                                 盘古分词                                     加锁                                                                
            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
            for (int i = 1; i <= 10; i++)
            {
                string txt = File.ReadAllText(@"E:LuceneNet测试文件测试文档" + i + ".txt", System.Text.Encoding.Default);
                //表示一篇文档。
                Document document = new Document();
                //Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("number")取出值来.Field.Index. NOT_ANALYZED:不进行分词保存
                document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

                //Field.Index. ANALYZED:进行分词保存:也就是要进行全文的字段要设置分词 保存(因为要进行模糊查询)

                //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不仅保存分词还保存分词的距离。
                document.Add(new Field("body", txt, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
                writer.AddDocument(document);

            }
            writer.Close();//会自动解锁。
            directory.Close();//不要忘了Close,否则索引结果搜不到
            MessageBox.Show("索引库创建成功");

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //定位到索引目录
            string indexPath = @"E:LuceneNet测试文件索引文件";
            string kw = "对象";//对用户输入的搜索条件进行拆分。
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader reader = IndexReader.Open(directory, true);
            IndexSearcher searcher = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery query = new PhraseQuery();
            //foreach (string word in kw.Split(' '))//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
            //{
            //    query.Add(new Term("body", word));
            //}
            //query.Add(new Term("body","语言"));--可以添加查询条件,两者是add关系.顺序没有关系.
            // query.Add(new Term("body", "大学生"));
            query.Add(new Term("body", kw));//body中含有kw的文章
            query.SetSlop(100);//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
            searcher.Search(query, null, collector);//根据query查询条件进行查询,查询结果放入collector容器
            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;//得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
            //可以用来实现分页功能
            this.listBox1.Items.Clear();
            for (int i = 0; i < docs.Length; i=i+2)
            {
                //
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                int docId = docs[i].doc;//得到查询结果文档的id(Lucene内部分配的id)
                Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
                this.listBox1.Items.Add(doc.Get("number") + "
");// 取出放进字段的值
                this.listBox1.Items.Add(doc.Get("body") + "
");
                this.listBox1.Items.Add("-----------------------
");
            }

        }
    }
}
View Code

1.4 运行结果

 1.5 此时有一个问题 如果将搜索条件改为"面向对象"则没有结果.其原因是:字典中没有"面向对象"这个词语.所以我们可以添加

但是,这样存在一个问题.每次都要修改数据字典.如果数据多的话,工作量会很大

原文地址:https://www.cnblogs.com/YK2012/p/6678074.html