PS:
苦學一周全文檢索,由原來的搜索小白,到初次涉獵,感覺每門技術都博大精深,其中精髓亦是不可一日而語。那小博豬就簡單介紹一下這一周的學習歷程,僅供各位程序猿們參考,這其中不涉及任何私密話題,因此也不用打馬賽克了,都是網絡分享的開源資料,當然也不涉及任何利益關系。
如若轉載,還請注明出處——xingoo
講解之前,先來分享一些資料
首先呢,學習任何一門新的亦或是舊的開源技術,百度其中一二是最簡單的辦法,先了解其中的大概,思想等等。這里就貢獻一個講解很到位的ppt。已經被我轉成了PDF,便於搜藏。
其次,關於第一次編程初探,建議還是查看官方資料。百度到的資料,目前Lucene已經更新到4.9版本,這個版本需要1.7以上的JDK,所以如果還用1.6甚至是1.5的小盆友,請參考低版本,由於我用的1.6,因此在使用Lucene4.0。
這是Lucene4.0的官網文檔:http://lucene.apache.org/core/4_0_0/core/overview-summary.html
這里非常佩服Lucene的開元貢獻者,可以閱讀Lucene in Action,作者最初想要寫軟件賺錢,最后貢獻給了Apache,跑題了。
最后,提醒學習Lucene的小盆友們,這個開源軟件的版本更新不慢,版本之間的編程風格亦是不同,所以如果百度到的帖子,可能這段代碼,用了4.0或者3.6就會不好使。
比如,以前版本的申請IndexWriter時,是這樣的:
IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer, true );
但是4.0,我們需要配置一個conf,把配置內容放到這個對象中:
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); IndexWriter iwriter = new IndexWriter(directory, config);
所以,請一定要參考官方文檔的編程風格,進行代碼的書寫。
最后的最后,從官網上面下載下來的文件,已經上傳至百度網盤,歡迎下載。
這是其中最常用的五個文件:
第一個,也是最重要的,Lucene-core-4.0.0.jar,其中包括了常用的文檔,索引,搜索,存儲等相關核心代碼。
第二個,Lucene-analyzers-common-4.0.0.jar,這里面包含了各種語言的詞法分析器,用於對文件內容進行關鍵字切分,提取。
第三個,Lucene-highlighter-4.0.0.jar,這個jar包主要用於搜索出的內容高亮顯示。
第四個和第五個,Lucene-queryparser-4.0.0.jar,提供了搜索相關的代碼,用於各種搜索,比如模糊搜索,范圍搜索,等等。
廢話說到這里,下面我們簡單的講解一下什么是全文檢索。
比如,我們一個文件夾中,或者一個磁盤中有很多的文件,記事本、world、Excel、pdf,我們想根據其中的關鍵詞搜索包含的文件。例如,我們輸入Lucene,所有內容含有Lucene的文件就會被檢查出來。這就是所謂的全文檢索。
因此,很容易的我們想到,應該建立一個關鍵字與文件的相關映射,盜用ppt中的一張圖,很明白的解釋了這種映射如何實現。
在Lucene中,就是使用這種“倒排索引”的技術,來實現相關映射。
有了這種映射關系,我們就來看看Lucene的架構設計。
下面是Lucene的資料必出現的一張圖,但也是其精髓的概括。
我們可以看到,Lucene的使用主要體現在兩個步驟:
1 創建索引,通過IndexWriter對不同的文件進行索引的創建,並將其保存在索引相關文件存儲的位置中。
2 通過索引查尋關鍵字相關文檔。
下面針對官網上面給出的一個例子,進行分析:
1 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); 2 3 // Store the index in memory: 4 Directory directory = new RAMDirectory(); 5 // To store an index on disk, use this instead: 6 //Directory directory = FSDirectory.open("/tmp/testindex"); 7 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); 8 IndexWriter iwriter = new IndexWriter(directory, config); 9 Document doc = new Document(); 10 String text = "This is the text to be indexed."; 11 doc.add(new Field("fieldname", text, TextField.TYPE_STORED)); 12 iwriter.addDocument(doc); 13 iwriter.close(); 14 15 // Now search the index: 16 DirectoryReader ireader = DirectoryReader.open(directory); 17 IndexSearcher isearcher = new IndexSearcher(ireader); 18 // Parse a simple query that searches for "text": 19 QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer); 20 Query query = parser.parse("text"); 21 ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; 22 assertEquals(1, hits.length); 23 // Iterate through the results: 24 for (int i = 0; i < hits.length; i++) { 25 Document hitDoc = isearcher.doc(hits[i].doc); 26 assertEquals("This is the text to be indexed.", hitDoc.get("fieldname")); 27 } 28 ireader.close(); 29 directory.close();
索引的創建
首先,我們需要定義一個詞法分析器。
比如一句話,“我愛我們的中國!”,如何對他拆分,扣掉停頓詞“的”,提取關鍵字“我”“我們”“中國”等等。這就要借助的詞法分析器Analyzer來實現。這里面使用的是標准的詞法分析器,如果專門針對漢語,還可以搭配paoding,進行使用。
1 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
參數中的Version.LUCENE_CURRENT,代表使用當前的Lucene版本,本文環境中也可以寫成Version.LUCENE_40。
第二步,確定索引文件存儲的位置,Lucene提供給我們兩種方式:
1 本地文件存儲
Directory directory = FSDirectory.open("/tmp/testindex");
2 內存存儲
Directory directory = new RAMDirectory();
可以根據自己的需要進行設定。
第三步,創建IndexWriter,進行索引文件的寫入。
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); IndexWriter iwriter = new IndexWriter(directory, config);
這里的IndexWriterConfig,據官方文檔介紹,是對indexWriter的配置,其中包含了兩個參數,第一個是目前的版本,第二個是詞法分析器Analyzer。
第四步,內容提取,進行索引的存儲。
Document doc = new Document(); String text = "This is the text to be indexed."; doc.add(new Field("fieldname", text, TextField.TYPE_STORED)); iwriter.addDocument(doc); iwriter.close();
第一行,申請了一個document對象,這個類似於數據庫中的表中的一行。
第二行,是我們即將索引的字符串。
第三行,把字符串存儲起來(因為設置了TextField.TYPE_STORED,如果不想存儲,可以使用其他參數,詳情參考官方文檔),並存儲“表明”為"fieldname".
第四行,把doc對象加入到索引創建中。
第五行,關閉IndexWriter,提交創建內容。
這就是索引創建的過程。
關鍵字查詢:
第一步,打開存儲位置
DirectoryReader ireader = DirectoryReader.open(directory);
第二步,創建搜索器
IndexSearcher isearcher = new IndexSearcher(ireader);
第三步,類似SQL,進行關鍵字查詢
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer); Query query = parser.parse("text"); ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; assertEquals(1, hits.length); for (int i = 0; i < hits.length; i++) { Document hitDoc = isearcher.doc(hits[i].doc); assertEquals("This is the text to be indexed.",hitDoc.get("fieldname")); }
這里,我們創建了一個查詢器,並設置其詞法分析器,以及查詢的“表名“為”fieldname“。查詢結果會返回一個集合,類似SQL的ResultSet,我們可以提取其中存儲的內容。
關於各種不同的查詢方式,可以參考官方手冊,或者推薦的PPT
第四步,關閉查詢器等。
ireader.close();
directory.close();
最后,博豬自己寫了個簡單的例子,可以對一個文件夾內的內容進行索引的創建,並根據關鍵字篩選文件,並讀取其中的內容。
創建索引:
/** * 創建當前文件目錄的索引 * @param path 當前文件目錄 * @return 是否成功 */ public static boolean createIndex(String path){ Date date1 = new Date(); List<File> fileList = getFileList(path); for (File file : fileList) { content = ""; //獲取文件后綴 String type = file.getName().substring(file.getName().lastIndexOf(".")+1); if("txt".equalsIgnoreCase(type)){ content += txt2String(file); }else if("doc".equalsIgnoreCase(type)){ content += doc2String(file); }else if("xls".equalsIgnoreCase(type)){ content += xls2String(file); } System.out.println("name :"+file.getName()); System.out.println("path :"+file.getPath()); // System.out.println("content :"+content); System.out.println(); try{ analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); directory = FSDirectory.open(new File(INDEX_DIR)); File indexFile = new File(INDEX_DIR); if (!indexFile.exists()) { indexFile.mkdirs(); } IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); indexWriter = new IndexWriter(directory, config); Document document = new Document(); document.add(new TextField("filename", file.getName(), Store.YES)); document.add(new TextField("content", content, Store.YES)); document.add(new TextField("path", file.getPath(), Store.YES)); indexWriter.addDocument(document); indexWriter.commit(); closeWriter(); }catch(Exception e){ e.printStackTrace(); } content = ""; } Date date2 = new Date(); System.out.println("創建索引-----耗時:" + (date2.getTime() - date1.getTime()) + "ms\n"); return true; }
進行查詢:
/** * 查找索引,返回符合條件的文件 * @param text 查找的字符串 * @return 符合條件的文件List */ public static void searchIndex(String text){ Date date1 = new Date(); try{ directory = FSDirectory.open(new File(INDEX_DIR)); analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); DirectoryReader ireader = DirectoryReader.open(directory); IndexSearcher isearcher = new IndexSearcher(ireader); QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer); Query query = parser.parse(text); ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; for (int i = 0; i < hits.length; i++) { Document hitDoc = isearcher.doc(hits[i].doc); System.out.println("____________________________"); System.out.println(hitDoc.get("filename")); System.out.println(hitDoc.get("content")); System.out.println(hitDoc.get("path")); System.out.println("____________________________"); } ireader.close(); directory.close(); }catch(Exception e){ e.printStackTrace(); } Date date2 = new Date(); System.out.println("查看索引-----耗時:" + (date2.getTime() - date1.getTime()) + "ms\n"); }
全部代碼:

1 package test; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileReader; 7 import java.util.ArrayList; 8 import java.util.Date; 9 import java.util.List; 10 11 import jxl.Cell; 12 import jxl.Sheet; 13 import jxl.Workbook; 14 15 import org.apache.lucene.analysis.Analyzer; 16 import org.apache.lucene.analysis.standard.StandardAnalyzer; 17 import org.apache.lucene.document.Document; 18 import org.apache.lucene.document.LongField; 19 import org.apache.lucene.document.TextField; 20 import org.apache.lucene.document.Field.Store; 21 import org.apache.lucene.index.DirectoryReader; 22 import org.apache.lucene.index.IndexWriter; 23 import org.apache.lucene.index.IndexWriterConfig; 24 import org.apache.lucene.queryparser.classic.QueryParser; 25 import org.apache.lucene.search.IndexSearcher; 26 import org.apache.lucene.search.Query; 27 import org.apache.lucene.search.ScoreDoc; 28 import org.apache.lucene.store.Directory; 29 import org.apache.lucene.store.FSDirectory; 30 import org.apache.lucene.util.Version; 31 import org.apache.poi.hwpf.HWPFDocument; 32 import org.apache.poi.hwpf.usermodel.Range; 33 34 /** 35 * @author xinghl 36 * 37 */ 38 public class IndexManager{ 39 private static IndexManager indexManager; 40 private static String content=""; 41 42 private static String INDEX_DIR = "D:\\luceneIndex"; 43 private static String DATA_DIR = "D:\\luceneData"; 44 private static Analyzer analyzer = null; 45 private static Directory directory = null; 46 private static IndexWriter indexWriter = null; 47 48 /** 49 * 創建索引管理器 50 * @return 返回索引管理器對象 51 */ 52 public IndexManager getManager(){ 53 if(indexManager == null){ 54 this.indexManager = new IndexManager(); 55 } 56 return indexManager; 57 } 58 /** 59 * 創建當前文件目錄的索引 60 * @param path 當前文件目錄 61 * @return 是否成功 62 */ 63 public static boolean createIndex(String path){ 64 Date date1 = new Date(); 65 List<File> fileList = getFileList(path); 66 for (File file : fileList) { 67 content = ""; 68 //獲取文件后綴 69 String type = file.getName().substring(file.getName().lastIndexOf(".")+1); 70 if("txt".equalsIgnoreCase(type)){ 71 72 content += txt2String(file); 73 74 }else if("doc".equalsIgnoreCase(type)){ 75 76 content += doc2String(file); 77 78 }else if("xls".equalsIgnoreCase(type)){ 79 80 content += xls2String(file); 81 82 } 83 84 System.out.println("name :"+file.getName()); 85 System.out.println("path :"+file.getPath()); 86 // System.out.println("content :"+content); 87 System.out.println(); 88 89 90 try{ 91 analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); 92 directory = FSDirectory.open(new File(INDEX_DIR)); 93 94 File indexFile = new File(INDEX_DIR); 95 if (!indexFile.exists()) { 96 indexFile.mkdirs(); 97 } 98 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); 99 indexWriter = new IndexWriter(directory, config); 100 101 Document document = new Document(); 102 document.add(new TextField("filename", file.getName(), Store.YES)); 103 document.add(new TextField("content", content, Store.YES)); 104 document.add(new TextField("path", file.getPath(), Store.YES)); 105 indexWriter.addDocument(document); 106 indexWriter.commit(); 107 closeWriter(); 108 109 110 }catch(Exception e){ 111 e.printStackTrace(); 112 } 113 content = ""; 114 } 115 Date date2 = new Date(); 116 System.out.println("創建索引-----耗時:" + (date2.getTime() - date1.getTime()) + "ms\n"); 117 return true; 118 } 119 120 /** 121 * 讀取txt文件的內容 122 * @param file 想要讀取的文件對象 123 * @return 返回文件內容 124 */ 125 public static String txt2String(File file){ 126 String result = ""; 127 try{ 128 BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件 129 String s = null; 130 while((s = br.readLine())!=null){//使用readLine方法,一次讀一行 131 result = result + "\n" +s; 132 } 133 br.close(); 134 }catch(Exception e){ 135 e.printStackTrace(); 136 } 137 return result; 138 } 139 140 /** 141 * 讀取doc文件內容 142 * @param file 想要讀取的文件對象 143 * @return 返回文件內容 144 */ 145 public static String doc2String(File file){ 146 String result = ""; 147 try{ 148 FileInputStream fis = new FileInputStream(file); 149 HWPFDocument doc = new HWPFDocument(fis); 150 Range rang = doc.getRange(); 151 result += rang.text(); 152 fis.close(); 153 }catch(Exception e){ 154 e.printStackTrace(); 155 } 156 return result; 157 } 158 159 /** 160 * 讀取xls文件內容 161 * @param file 想要讀取的文件對象 162 * @return 返回文件內容 163 */ 164 public static String xls2String(File file){ 165 String result = ""; 166 try{ 167 FileInputStream fis = new FileInputStream(file); 168 StringBuilder sb = new StringBuilder(); 169 jxl.Workbook rwb = Workbook.getWorkbook(fis); 170 Sheet[] sheet = rwb.getSheets(); 171 for (int i = 0; i < sheet.length; i++) { 172 Sheet rs = rwb.getSheet(i); 173 for (int j = 0; j < rs.getRows(); j++) { 174 Cell[] cells = rs.getRow(j); 175 for(int k=0;k<cells.length;k++) 176 sb.append(cells[k].getContents()); 177 } 178 } 179 fis.close(); 180 result += sb.toString(); 181 }catch(Exception e){ 182 e.printStackTrace(); 183 } 184 return result; 185 } 186 /** 187 * 查找索引,返回符合條件的文件 188 * @param text 查找的字符串 189 * @return 符合條件的文件List 190 */ 191 public static void searchIndex(String text){ 192 Date date1 = new Date(); 193 try{ 194 directory = FSDirectory.open(new File(INDEX_DIR)); 195 analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); 196 DirectoryReader ireader = DirectoryReader.open(directory); 197 IndexSearcher isearcher = new IndexSearcher(ireader); 198 199 QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer); 200 Query query = parser.parse(text); 201 202 ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; 203 204 for (int i = 0; i < hits.length; i++) { 205 Document hitDoc = isearcher.doc(hits[i].doc); 206 System.out.println("____________________________"); 207 System.out.println(hitDoc.get("filename")); 208 System.out.println(hitDoc.get("content")); 209 System.out.println(hitDoc.get("path")); 210 System.out.println("____________________________"); 211 } 212 ireader.close(); 213 directory.close(); 214 }catch(Exception e){ 215 e.printStackTrace(); 216 } 217 Date date2 = new Date(); 218 System.out.println("查看索引-----耗時:" + (date2.getTime() - date1.getTime()) + "ms\n"); 219 } 220 /** 221 * 過濾目錄下的文件 222 * @param dirPath 想要獲取文件的目錄 223 * @return 返回文件list 224 */ 225 public static List<File> getFileList(String dirPath) { 226 File[] files = new File(dirPath).listFiles(); 227 List<File> fileList = new ArrayList<File>(); 228 for (File file : files) { 229 if (isTxtFile(file.getName())) { 230 fileList.add(file); 231 } 232 } 233 return fileList; 234 } 235 /** 236 * 判斷是否為目標文件,目前支持txt xls doc格式 237 * @param fileName 文件名稱 238 * @return 如果是文件類型滿足過濾條件,返回true;否則返回false 239 */ 240 public static boolean isTxtFile(String fileName) { 241 if (fileName.lastIndexOf(".txt") > 0) { 242 return true; 243 }else if (fileName.lastIndexOf(".xls") > 0) { 244 return true; 245 }else if (fileName.lastIndexOf(".doc") > 0) { 246 return true; 247 } 248 return false; 249 } 250 251 public static void closeWriter() throws Exception { 252 if (indexWriter != null) { 253 indexWriter.close(); 254 } 255 } 256 /** 257 * 刪除文件目錄下的所有文件 258 * @param file 要刪除的文件目錄 259 * @return 如果成功,返回true. 260 */ 261 public static boolean deleteDir(File file){ 262 if(file.isDirectory()){ 263 File[] files = file.listFiles(); 264 for(int i=0; i<files.length; i++){ 265 deleteDir(files[i]); 266 } 267 } 268 file.delete(); 269 return true; 270 } 271 public static void main(String[] args){ 272 File fileIndex = new File(INDEX_DIR); 273 if(deleteDir(fileIndex)){ 274 fileIndex.mkdir(); 275 }else{ 276 fileIndex.mkdir(); 277 } 278 279 createIndex(DATA_DIR); 280 searchIndex("man"); 281 } 282 }
運行結果:
所有包含man關鍵字的文件,都被篩選出來了。
參考資料
JAVA讀取文本大全:http://blog.csdn.net/csh624366188/article/details/6785817
Lucene官方文檔:http://lucene.apache.org/core/4_0_0/core/overview-summary.html