讓我們使用Lucene框架做實際程式設計。在開始使用Lucene框架編寫第一個例子之前,必須確保已經安裝Lucene的環境正常。也假設有一點點的工作和Eclipse IDE的知識。
因此,開始寫一個簡單的搜尋應用程式將列印找到搜尋結果數量。我們也看到在這個過程中建立的索引列表。
第一步是使用Eclipse IDE建立一個簡單的Java專案。按照選項 File -> New -> Project 最後選擇 Java Project 從嚮導列表向導。現在,專案命名為 LuceneFirstApplication 使用嚮導視窗,如下所示:
一旦專案成功建立,將有以下內容在 Project Explorer:
作為第二步,我們新增Lucene核心框架庫在專案中。要做到這一點,右鍵單擊專案名稱LuceneFirstApplication然後按照上下文選單中提供以下選項:Build Path -> Configure Build Path,顯示了Java構建路徑如下視窗:
現在,使用新增在庫索引標籤中提供外部JAR按鈕,新增Lucene安裝目錄下的核心JAR:
lucene-core-3.6.2
現在,讓我們 LuceneFirstApplication 專案下建立實際的原始檔。首先,我們需要建立一個名為 com.yiibai.lucene 包。要做到這一點,右鍵單擊 src 在包資源管理部分,並按照選項:New -> Package.
下一步,我們將建立 LuceneTester.java 和 其他Java類在 com.yiibai.lucene 包下。
LuceneConstants.java
這個類是用來提供跨範例應用程式中使用的各種常數。
package com.yiibai.lucene; public class LuceneConstants { public static final String CONTENTS="contents"; public static final String FILE_NAME="filename"; public static final String FILE_PATH="filepath"; public static final int MAX_SEARCH = 10; }
TextFileFilter.java
此類用於為 .txt 檔案過濾器
package com.yiibai.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } }
Indexer.java
這個類是用於索引的原始資料,這樣我們就可以使用Lucene庫,使其可搜尋。
package com.yiibai.lucene; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Indexer { private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException{ //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } public void close() throws CorruptIndexException, IOException{ writer.close(); } private Document getDocument(File file) throws IOException{ Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } private void indexFile(File file) throws IOException{ System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } public int createIndex(String dataDirPath, FileFilter filter) throws IOException{ //get all files in the data directory File[] files = new File(dataDirPath).listFiles(); for (File file : files) { if(!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead() && filter.accept(file) ){ indexFile(file); } } return writer.numDocs(); } }
Searcher.java
這個類是用來搜尋索引所建立的索引搜尋請求的內容。
package com.yiibai.lucene; import java.io.File; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Searcher { IndexSearcher indexSearcher; QueryParser queryParser; Query query; public Searcher(String indexDirectoryPath) throws IOException{ Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); indexSearcher = new IndexSearcher(indexDirectory); queryParser = new QueryParser(Version.LUCENE_36, LuceneConstants.CONTENTS, new StandardAnalyzer(Version.LUCENE_36)); } public TopDocs search( String searchQuery) throws IOException, ParseException{ query = queryParser.parse(searchQuery); return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException{ return indexSearcher.doc(scoreDoc.doc); } public void close() throws IOException{ indexSearcher.close(); } }
LuceneTester.java
這個類是用來測試 Lucene 庫的索引和搜尋功能。
package com.yiibai.lucene; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; public class LuceneTester { String indexDir = "E:\Lucene\Index"; String dataDir = "E:\Lucene\Data"; Indexer indexer; Searcher searcher; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.createIndex(); tester.search("Mohan"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void createIndex() throws IOException{ indexer = new Indexer(indexDir); int numIndexed; long startTime = System.currentTimeMillis(); numIndexed = indexer.createIndex(dataDir, new TextFileFilter()); long endTime = System.currentTimeMillis(); indexer.close(); System.out.println(numIndexed+" File indexed, time taken: " +(endTime-startTime)+" ms"); } private void search(String searchQuery) throws IOException, ParseException{ searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); TopDocs hits = searcher.search(searchQuery); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime)); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.println("File: " + doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } }
把 record1.txt 任命為 record10.txt 包含簡單的名稱以及學生的其他資料資訊,並把它們放在目錄:E:LuceneData 並測試資料。索引目錄路徑應建立在 E:LuceneIndex。執行此程式後,就可以看到該檔案夾中建立的索引檔案的列表。
一旦完成建立源和原始資料,資料目錄和索引目錄,下一步是編譯和執行程式。要做到這一點,請LuceneTester.Java檔案的活動索引標籤中使用EclipseIDE可無論是執行選項,或使用Ctrl+ F11來編譯和執行應用程式LuceneTester。如果一切正常您的應用程式,這將列印在 Eclipse IDE 控制台以下訊息:
Indexing E:LuceneDataecord1.txt Indexing E:LuceneDataecord10.txt Indexing E:LuceneDataecord2.txt Indexing E:LuceneDataecord3.txt Indexing E:LuceneDataecord4.txt Indexing E:LuceneDataecord5.txt Indexing E:LuceneDataecord6.txt Indexing E:LuceneDataecord7.txt Indexing E:LuceneDataecord8.txt Indexing E:LuceneDataecord9.txt 10 File indexed, time taken: 109 ms 1 documents found. Time :0 File: E:LuceneDataecord4.txt
一旦已經成功地執行程式,將有以下的索引目錄中的內容: