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号帖子进行索引。“只要能看懂例子和文档,稍作修改即可实现自己的需求”。除了基础知识外,第三方开发包只要“能看懂,改改即可”

引入命名空间:

  1. using Lucene.Net.Store;  
  2. using System.IO;  
  3. using Lucene.Net.Index;  
  4. using Lucene.Net.Analysis.PanGu;  
  5. using Lucene.Net.Documents;  
  6. using Lucene.Net.Search;  

1 对数据进行索引

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

2、搜索的代码

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

aspx代码:

  1. <form id="form1" runat="server">
  2. <div>
  3. <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="创建索引" />
  4. <br />
  5. <br />
  6. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  7. <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="搜索" />
  8. <br />
  9. <ul>
  10. <asp:Repeater ID="Repeater1" runat="server">
  11. <ItemTemplate><li>Id:<%#Eval("Id") %><br /><%#Eval("Msg") %></li></ItemTemplate>
  12. </asp:Repeater>
  13. </ul>
  14. </div>
  15. </form>
  16. 本文摘自51CTO;

最新文章

  1. 并查集 + 线段树 LA 4730 Kingdom
  2. [Wordpress]wp_dropdown_categories() 添加自定义的attribute(属性)
  3. as 中的反射
  4. RemixOS Player 让用户在 Windows 上运行 Android App
  5. 概率dp-九度-1546-迷宫问题
  6. Jqgrid的用法总结与分页功能的拓展
  7. C++中头文件(.h)和源文件(.cpp)都应该写些什么
  8. 三白话经典算法系列 Shell排序实现
  9. 6.1 MSI/MSI-X Capability结构
  10. ubuntu---网络管理
  11. shell脚本_查找无效网址
  12. 使用数组制作简易的用户管理系统【java】
  13. jQuery中live函数的替代-【jQuery】
  14. LCT总结——应用篇(附题单)(LCT)
  15. CSRF攻击和防护
  16. 如何使用JBDC修改数据
  17. 对于最近一星期jsp培训有感
  18. windows安装mysql方法 mysql5.7以后的安装方法
  19. java 优秀文章集锦
  20. [leetcode]Path Sum--巧用递归

热门文章

  1. Linux 常用命令(三)
  2. Meteor Shower POJ - 3669 (bfs+优先队列)
  3. 搜索引擎elasticsearch常用指令演示
  4. poj 1862 2*根号(n1*n2)问题 贪心算法
  5. App架构经验总结
  6. CSS 工程化 小结
  7. multiprocessing join与lock区别
  8. bzoj3172 luogu3966 [TJOI2013]单词
  9. Leetcode24---&gt;Swap Nodes in Pairs(交换单链表中相邻的两个节点)
  10. PostgreSQL 全文索引