2014-01-20 140 views
1

這個職位,如果後續從我剛纔的問題: Apache Lucene - Optimizing SearchingApache Lucene - 創建和存儲索引?

我想創建存儲在我的數據庫標題索引,存儲在服務器上的指數從我運行我的Web應用程序,並有該索引適用於在Web應用程序上使用搜索功能的所有用戶。

我將在新標題添加,編輯或刪除時更新索引。

我找不到在Apache Lucene中這樣做的教程,所以任何人都可以幫助我用Java編寫這個代碼(使用Spring)。

+0

你正在使用哪種lucene版本? – Salah

+0

Apache Lucene 4.6.0 – COBOL

回答

1

從我的理解你的問題,你需要做到以下幾點:

1)索引你的數據(在你的情況職稱) 首先你需要實現創建索引您數據的代碼,檢查這個代碼示例。

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); 

// Store the index in memory: 
//Directory directory = new RAMDirectory(); 

Store an index on disk 
Directory directory = FSDirectory.open(indexfilesDirPathOnYourServer); 
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer); 
IndexWriter iwriter = new IndexWriter(directory, config); 
Document doc = new Document(); 
String title = getTitle(); 
doc.add(new Field("fieldname", text, TextField.TYPE_STORED)); 
iwriter.addDocument(doc); 
iwriter.close(); 

這裏你需要遍歷你所有的數據。

2)搜索索引數據。 您可以通過使用此代碼搜索你的數據:

DirectoryReader ireader = DirectoryReader.open(indexfilesDirPathOnYourServer); 
IndexSearcher isearcher = new IndexSearcher(ireader); 
// Parse a simple query that searches for "text": 
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);//note here we used the same analyzer object 
Query query = parser.parse("test");//test is am example for a search query 
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; 
// Iterate through the results: 
for (int i = 0; i < hits.length; i++) { 
    Document hitDoc = isearcher.doc(hits[i].doc); 
    System.out.println(hitDoc.get("fieldname")); 
} 
ireader.close(); 
directory.close(); 

注:在這裏,你不必來從你的數據庫中的所有數據,你可以直接從指數得到它。您也不必在每次用戶搜索或獲取數據時重新創建整個索引,您可以隨時添加/更新或逐個刪除標題(已更新或刪除的標題不是全部索引標題)。

更新索引的使用:

Term keyTerm = new Term(KEY_FIELD, KEY_VALUE); 
iwriter.updateDocument(keyTerm, updatedFields); 

刪除索引的使用:

Term keyTerm = new Term(KEY_FIELD, KEY_VALUE); 
iwriter.deleteDocuments(keyTerm); 

希望能夠幫助您。

+0

這對我有很大的幫助。我設法讓我的搜索有效地工作。非常感謝。 – COBOL