Lucene.net入门学习系列(2)

      Lucene.net入门学习系列(1)-分词html

  Lucene.net入门学习系列(2)-建立索引学习

  Lucene.net入门学习系列(3)-全文检索优化

  

  在使用Lucene.net进行全文检索以前,须要写入索引,而后对索引进行检索。下面咱们来看看如何创建索引。spa

  具体步骤以下:.net

  1.使用FSDirectory类打开一个索引文件code

  2.使用IndexWriter类写来写索引htm

  3.关闭IndexWriter  对象

 1         /// <summary>
 2         /// 建立索引
 3         /// </summary>
 4         private void CreateIndex()
 5         {
 6             //索引的文件存放的路径
 7             string indexPath = @"\Lucene";
 8 
 9             //FSDirectory是用于对文件系统目录的操做的类
10             FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
11             //检查目录是否存在
12             bool isUpdate = IndexReader.IndexExists(directory);
13 
14             if (isUpdate)
15             {
16                 //目录存在则判断目录是否被锁定,被锁定就解锁
17                 if (IndexWriter.IsLocked(directory))
18                 {
19                     IndexWriter.Unlock(directory);
20                 }
21             }
22             //IndexWriter主要用于写索引
23             //方法签名:public IndexWriter(Directory d,Analyzer a,boolean create,IndexWriter.MaxFieldLength mfl)
24             //第一个参数是 (Directory d):索引的目录(前面的FSDirectory类的对象)
25             //第二个参数是 (Analyzer a):分析器(这里咱们用盘古分词的分析器)
26             //第三个参数是 (boolean create):是否建立目录
27             //第四个参数是 (IndexWriter.MaxFieldLength):最大长度
28             IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate,
29                 IndexWriter.MaxFieldLength.UNLIMITED);
30 
31             //BLL层的一个类,用于对表T_Article进行操做
32             //T_Article表中有三个字段: Id   Title  Message
33             T_ArticleBLL bll = new T_ArticleBLL();
34 
35             //遍历T_Article表中的内容
36             foreach (T_Articles art in bll.GetAll())
37             {
38                 writer.DeleteDocuments(new Term("id", art.ID.ToString()));
39 
40                 //Document文档对象
41                 Document document = new Document();
42 
43                 //将T_Articles表中的内容写入索引
44                 document.Add(new Field("id", art.ID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
45 
46                 document.Add(new Field("title", art.Title, Field.Store.YES, Field.Index.ANALYZED,
47                     Field.TermVector.WITH_POSITIONS_OFFSETS));
48 
49                 document.Add(new Field("msg", art.Message, Field.Store.YES, Field.Index.ANALYZED,
50                     Field.TermVector.WITH_POSITIONS_OFFSETS));
51                 writer.AddDocument(document);
52             }
53             //要记得关闭
54             writer.Close();
55             directory.Close();
56         }

 在上面的例子中,咱们使用FSDirectory类来对索引文件进行操做,要注意的是索引不光能够写到文件中,索引也能够写到内存(使用RAMDirectory类)中。blog

   索引建立好了以后,咱们还能够根据需求来对索引进行不一样的优化,以达到更好的检索效果。索引

相关文章
相关标签/搜索