lucene 3.0 学习笔记(1)— 建立索引(转)

正在学习lucene,下载的新版本是3.0的,这里把学习中整理的笔记,放在blog中做为备份。 



使用lucene做为搜索引擎,主要做的2件事就是:1、建立索引;2、利用索引查询。 

即lucene先将要搜索的内容,转化成一个个单词,然后对单词及其与内容的关系建索引;查询是根据你输入的内容,在索引中找到符合条件单词,并进而找到对应的内容。 

这里先从创建索引开始,下面是一段代码示例: 

Java代码 
  1. /** 
  2.  * Copyright (c) 2010 TeleNav, Inc 
  3.  * All rights reserved 
  4.  *  
  5.  * Created on Sep 25, 2010 
  6.  * Filename is CreateIndex.java 
  7.  * Packagename:example 
  8.  */  
  9. package example;  
  10.   
  11. import java.io.File;  
  12. import java.io.FileReader;  
  13. import java.util.Date;  
  14.   
  15. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  16. import org.apache.lucene.document.DateTools;  
  17. import org.apache.lucene.document.Document;  
  18. import org.apache.lucene.document.Field;  
  19. import org.apache.lucene.index.IndexWriter;  
  20. import org.apache.lucene.store.FSDirectory;  
  21. import org.apache.lucene.util.Version;  
  22.   
  23. /** 
  24.  * @author lgli 
  25.  * 
  26.  * Created on  Sep 25, 2010 
  27.  */  
  28. public class CreateIndex  
  29. {  
  30.     //索引文件存放目录  
  31.     final File INDEX_DIR = new File("index");  
  32.     //测试数据目录  
  33.     final File docDir = new File("E:\\workspace_eclipse\\DOCTEST\\txt\\");  
  34.       
  35.     public boolean createIndex()  
  36.     {  
  37.         if (!docDir.exists() || !docDir.canRead())  
  38.         {  
  39.             System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path");  
  40.             return false;  
  41.         }  
  42.   
  43.         Date start = new Date();  
  44.         try  
  45.         {  
  46.             IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_DIR),   
  47.                 new StandardAnalyzer(Version.LUCENE_30),   
  48.                     true//true为覆盖原index;false为追加  
  49.                     IndexWriter.MaxFieldLength.LIMITED);  
  50.             System.out.println("Indexing to directory '" + INDEX_DIR + "'...");  
  51.             indexDocs(writer, docDir);  //创建Document,加入IndexWriter中  
  52.             System.out.println("Optimizing...");  
  53.             writer.optimize();          //优化索引  
  54.             writer.close();  
  55.   
  56.             Date end = new Date();  
  57.             System.out.println(end.getTime() - start.getTime() + " total milliseconds");  
  58.   
  59.         }  
  60.         catch (Exception e)  
  61.         {  
  62.             System.out.println(e.getMessage());  
  63.             return false;  
  64.         }  
  65.         return true;  
  66.     }  
  67.     //向IndexWriter中添加Document  
  68.     private void indexDocs(IndexWriter writer, File file) throws Exception  
  69.     {  
  70.         if (file.canRead())  
  71.         {  
  72.             if (file.isDirectory())  
  73.             {  
  74.                 //递归遍历目录下所有文件  
  75.                 String[] files = file.list();  
  76.                 if (files != null)  
  77.                 {  
  78.                     for (int i = 0; i < files.length; i++)  
  79.                     {  
  80.                         indexDocs(writer, new File(file, files[i]));  
  81.                     }  
  82.                 }  
  83.             }  
  84.             else  
  85.             {  
  86.                 //添加Document  
  87.                 System.out.println("indexing: " + file);  
  88.                 writer.addDocument(getDocument(file));  
  89.             }  
  90.         }  
  91.     }  
  92.     public Document getDocument(File f) throws java.io.FileNotFoundException  
  93.     {  
  94.         //创建Document  
  95.         Document doc = new Document();  
  96.         doc.add(new Field("path", f.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));  
  97.         doc.add(new Field("modified", DateTools.timeToString(f.lastModified(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED));  
  98.         doc.add(new Field("contents"new FileReader(f)));  
  99.         return doc;  
  100.     }  
  101. }  

创建索引的主要步骤: 

1、先指定要搜索的文件(docDir 目录下放了一些文本文件做为测试数据)和存放索引文件的目录(INDEX_DIR ) 

2、创建IndexWriter-需要提供索引目录、使用的Analyzer等。Analyzer用于解析文本内容,拆分成单词,这里我使用的是lucene自带的分词器。 

3、递归遍历所有文件,生成Document,每一个文件对于一个Document。 

4、将Document逐个加入索引 

5、关闭IndexWriter,保存索引信息 



说明: 

1、索引文件可存放在目录或内存中,分别使用FSDirectory和RAMDirectory 

2、每个Document类似与索引中的一行记录,具体的字段由Field标识,我这里加入了3个Field,分别是路径、修改时间和内容。 

3、Field中的枚举字段 

     Field.Store.YES表示此字段内容需要在索引中保存 

     Field.Index.NOT_ANALYZED表示此字段内容不需要做分词 

     new Field("contents", new FileReader(f))表示此字段内容从reader中取,做分词但不保存 





几个基本对象间的关系如下图: 

 

最后,上面这段代码的输出结果如下: 
Indexing to directory 'index'... 
indexing: E:\workspace_eclipse\DOCTEST\txt\DeleteFiles.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\FileDocument.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\Entities.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\HTMLParser.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\HTMLParser.jj 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\HTMLParserConstants.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\HTMLParserTokenManager.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\ParseException.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\ParserThread.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\SimpleCharStream.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\Tags.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\Test.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\Token.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\html\TokenMgrError.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\HTMLDocument.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\IndexFiles.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\IndexHTML.java 
indexing: E:\workspace_eclipse\DOCTEST\txt\SearchFiles.java 
Optimizing... 
734 total milliseconds

猜你喜欢

转载自liuxinglanyue.iteye.com/blog/813286