繁体   English   中英

Apache Lucene - 创建和存储索引?

[英]Apache Lucene - Creating and Storing an Index?

这篇文章如果是我上一个问题的后续内容: Apache Lucene - 优化搜索

我想从存储在我的数据库中的标题创建一个索引,将索引存储在我运行我的Web应用程序的服务器上,并将该索引提供给在Web应用程序上使用搜索功能的所有用户。

我会在添加,编辑或删除新标题时更新索引。

我找不到在Apache Lucene中做这个的教程,所以任何人都可以帮我用Java编写代码(使用Spring)。

从我的理解到您的问题,您需要执行以下操作:

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);

希望对你有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM