Lucene.net站内搜索3—最简单搜索引擎代码

来源:互联网 发布:java环境一键安装包 编辑:程序博客网 时间:2024/05/16 09:13

Lucene.Net核心类简介

先运行写好的索引的代码,再向下讲解各个类的作用,不用背代码。

(*)Directory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirectory(文件中)、RAMDirectory (内存中)。使用的时候别和IO里的Directory弄混了。

创建FSDirectory的方法,FSDirectory directory =FSDirectory.Open(new DirectoryInfo(indexPath),new NativeFSLockFactory()), path索引的文件夹路径

IndexReader对索引进行读取的类,对IndexWriter进行写的类。

IndexReader的静态方法bool IndexExists(Directory directory)判断目录directory是否是一个索引目录。IndexWriter的bool IsLocked(Directory directory) 判断目录是否锁定,在对目录写之前会先把目录锁定。两个IndexWriter没法同时写一个索引文件。IndexWriter在进行写操作的时候会自动加锁,close的时候会自动解锁。IndexWriter.Unlock方法手动解锁(比如还没来得及close IndexWriter 程序就崩溃了,可能造成一直被锁定)。

创建索引

构造函数:IndexWriter(Directorydir, Analyzer a, bool create, MaxFieldLength mfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。

void AddDocument(Document doc),向索引中添加文档(Insert)。Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一条记录,Field相当于字段。

Field类的构造函数 Field(string name, string value, Field.Store store, Field.Indexindex, Field.TermVector termVector):name表示字段名; value表示字段值;

store表示是否存储value值,可选值Field.Store.YES存储,Field.Store.NO不存储,Field.Store.COMPRESS压缩存储;默认只保存分词以后的一堆词,而不保存分词之前的内容,搜索的时候无法根据分词后的东西还原原文,因此如果要显示原文(比如文章正文)则需要设置存储。

index表示如何创建索引,可选值Field.Index. NOT_ANALYZED,不创建索引,Field.Index. ANALYZED,创建索引;创建索引的字段才可以比较好的检索。是否碎尸万段!是否需要按照这个字段进行“全文检索”。

termVector表示如何保存索引词之间的距离。“北京欢迎你们大家”,索引中是如何保存“北京”和“大家”之间“隔多少单词”。方便只检索在一定距离之内的词。

为什么要把帖子的url做为一个Field,因为要在搜索展示的时候先帖子地址取出来构建超链接,所以Field.Store.YES;一般不需要对url进行检索,所以Field.Index.NOT_ANALYZED 。根据《红楼梦》构建的“词:页数”纸,在构建完成后就可以把原文《红楼梦》扔了

案例:对1000至1100号帖子进行索引。“只要能看懂例子和文档,稍作修改即可实现自己的需求”。除了基础知识外,第三方开发包只要“能看懂,改改即可”

引入命名空间:

using Lucene.Net.Store;using System.IO;using Lucene.Net.Index;using Lucene.Net.Analysis.PanGu;using Lucene.Net.Documents;using Lucene.Net.Search;

1、 对数据进行索引

            string indexPath = @"C:\1017index";//注意和磁盘上文件夹的大小写一致,否则会报错。            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());            bool isUpdate = IndexReader.IndexExists(directory);//判断索引库是否存在            if (isUpdate)            {                //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁                //Lucene.Net在写索引库之前会自动加锁,在close的时候会自动解锁                //不能多线程执行,只能处理意外被永远锁定的情况                if (IndexWriter.IsLocked(directory))                {                    IndexWriter.Unlock(directory);//un-否定。强制解锁                }            }            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);            for (int i = 1000; i < 1100; i++)            {                string txt = File.ReadAllText(@"D:\我的文档\快盘\传智资料\班级资料\2011-10-17就业班\文章\" + i + ".txt");                Document document = new Document();//一条Document相当于一条记录                document.Add(new Field("id", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));                //每个Document可以有自己的属性(字段),所有字段名都是自定义的,值都是string类型                //Field.Store.YES不仅要对文章进行分词记录,也要保存原文,就不用去数据库里查一次了                //需要进行全文检索的字段加 Field.Index. ANALYZED                document.Add(new Field("msg", txt, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));                //防止重复索引                writer.DeleteDocuments(new Term("id", i.ToString()));//防止存在的数据//delete from t where id=i                //如果不存在则删除0条                writer.AddDocument(document);//把文档写入索引库            }            writer.Close();            directory.Close();//不要忘了Close,否则索引结果搜不到

2、搜索的代码

            string indexPath = @"C:\1017index";            string kw = TextBox1.Text;            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());            IndexReader reader = IndexReader.Open(directory, true);            IndexSearcher searcher = new IndexSearcher(reader);            PhraseQuery query = new PhraseQuery();//查询条件            query.Add(new Term("msg", kw));//where contains("msg",kw)            //foreach (string word in kw.Split(' '))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”            //{            //    query.Add(new Term("msg", word));//contains("msg",word)            //}            query.SetSlop(100);//两个词的距离大于100(经验值)就不放入搜索结果,因为距离太远相关度就不高了            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);//盛放查询结果的容器            searcher.Search(query, null, collector);//使用query这个查询条件进行搜索,搜索结果放入collector            //collector.GetTotalHits()总的结果条数            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;//从查询结果中取出第m条到第n条的数据            List<SearchResult> list = new List<SearchResult>();            for (int i = 0; i < docs.Length; i++)//遍历查询结果            {                int docId = docs[i].doc;//拿到文档的id。因为Document可能非常占内存(DataSet和DataReader的区别)                //所以查询结果中只有id,具体内容需要二次查询                Document doc = searcher.Doc(docId);//根据id查询内容。放进去的是Document,查出来的还是Document                //Console.WriteLine(doc.Get("id"));                //Console.WriteLine(doc.Get("msg"));                SearchResult result = new SearchResult();                result.Id = Convert.ToInt32(doc.Get("id"));                result.Msg = doc.Get("msg");//只有 Field.Store.YES的字段才能用Get查出来                list.Add(result);            }            Repeater1.DataSource = list;            Repeater1.DataBind();

aspx代码:

    <form id="form1" runat="server">    <div>        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="创建索引" />        <br />        <br />        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="搜索" />        <br />        <ul>        <asp:Repeater ID="Repeater1" runat="server">            <ItemTemplate><li>Id:<%#Eval("Id") %><br /><%#Eval("Msg") %></li></ItemTemplate>        </asp:Repeater>        </ul>    </div>    </form>

1 0