2014-01-20 134 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