利用lucene對檔案內容進行關鍵字檢索
一、概述
關於lucene的具體介紹,請自行百度。
二、例項講解
在具體實現之前,請根據自己的要求,建立對應的路徑及檔案。
例如,我這邊建立的路徑及檔案是:
D:/tools/LearningByMyself/lucene/source/demo1.txt
D:/tools/LearningByMyself/lucene/source/demo2.txt
D:/tools/LearningByMyself/lucene/index
第一步,建立索引,程式碼如下:
/** * @param sourceFile 需要新增到索引中的路徑 * @param indexFile 存放索引的路徑 * @throws Exception */ public static void textFileIndexer(String sourceFile,String indexFile) throws Exception{ File sourceDir = new File(sourceFile), indexDir = new File(indexFile); Directory dir = FSDirectory.open(indexDir); Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_36); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,luceneAnalyzer); iwc.setOpenMode(OpenMode.CREATE); IndexWriter indexWriter = new IndexWriter(dir,iwc); File[] textFiles = sourceDir.listFiles(); long startTime = new Date().getTime(); for(int i=0;i<textFiles.length;i++){ if(textFiles[i].isFile() && textFiles[i].getName().endsWith(".txt")){ System.out.println("File--->" + textFiles[i].getCanonicalPath() + " 正在被索引....."); String str_temp = fileReaderAll(textFiles[i].getCanonicalPath(),"UTF-8"); System.out.println("檔案內容:" + str_temp); Document document = new Document(); Field field_path = new Field("path",textFiles[i].getCanonicalPath(), Field.Store.YES,Field.Index.NO); Field field_body = new Field("body",str_temp,Field.Store.YES, Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS); document.add(field_path); document.add(field_body); indexWriter.addDocument(document); } } indexWriter.close(); long endTime = new Date().getTime(); System.out.println("一共花費了" + (endTime - startTime) + "毫秒將" + sourceDir.getPath() + "中的檔案增加到索引裡面去....."); }
第二步,在索引中檢索關鍵字private static String fileReaderAll(String filename,String charset) throws IOException{ BufferedReader buffer_read = new BufferedReader( new InputStreamReader(new FileInputStream(filename),charset)); String line = new String(); String temp = new String(); while((line = buffer_read.readLine()) != null){ temp += line ; } buffer_read.close(); return temp ; }
/** * @param indexFile 索引所在的路徑 * @param keyWords 需要檢索的關鍵字 * @throws IOException * @throws ParseException */ public static void queryKeyWords(String indexFile,String keyWords) throws IOException,ParseException{ IndexReader reader = IndexReader.open( FSDirectory.open(new File(indexFile))); IndexSearcher index_search = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); QueryParser query_parser = new QueryParser(Version.LUCENE_36,"body",analyzer); Query query = query_parser.parse(keyWords); if(index_search != null){ TopDocs result = index_search.search(query, 10); //返回最多為10條記錄 ScoreDoc[] hits = result.scoreDocs; if(hits.length > 0){ System.out.println("關鍵字:" + keyWords + ",在 " + indexFile + "中,一共檢索到" + hits.length + "個..."); } index_search.close(); } }
第三部,自己編寫一個測試類,測試一下上面的兩個方法,例如,我寫的測試類如下:
public class LuceneTest {
public static void main(String[] args) throws IOException,ParseException,Exception{
String sourcePath = "D:/tools/LearningByMyself/lucene/source" ;
String indexPath = "D:/tools/LearningByMyself/lucene/index" ;
String key_words = "伺服器" ;
LuceneIndex.textFileIndexer(sourcePath, indexPath);
LuceneIndex.queryKeyWords(indexPath, key_words);
}
}
第四步,在控制檯上檢視結果。例如,我這邊的測試結果如下:
File--->D:\tools\LearningByMyself\lucene\source\demo1.txt 正在被索引.....
檔案內容:為了保證機房的網路安全,IDC內所有伺服器不被允許從辦公網直接ssh登入,必須通過跳板機 進行間接登入。使用者通過跳板機執行的所有命令(包括通過跳板機登入的其他機器後的命令)都會被儲存並審計。
File--->D:\tools\LearningByMyself\lucene\source\demo2.txt 正在被索引.....
檔案內容:Relay是我們登入IDC伺服器的跳板機,在Relay上使用者只能執行ssh、passwd等簡單命令,Relay只做ssh跳板機兒不做日常工具機使用。
一共花費了235毫秒將D:\tools\LearningByMyself\lucene\source中的檔案增加到索引裡面去.....
關鍵字:伺服器,在 D:/tools/LearningByMyself/lucene/index中,一共檢索到2個.