嗨,我是java开发人员,正在学习Lucene。我有一个用来索引pdf(lucene_in_action_2nd_edition.pdf)文件的java类和一个用来从索引中搜索一些文本的search类。IndexSearcher提供了Document,它表明字符串是否存在于索引(lucene_in_action_2nd_edition.pdf)中。
但是现在I want to get searched data or metadata. i.e. I want to know that at which page string is matched, or few text around matched string, etc...如何做到这一点呢?
下面是我的LuceneSearcher.java类:
public static void main(String[] args) throws Exception {
File indexDir = new File("D:\\index");
String querystr = "Advantages of FastVectorHighlighter";
Query q = new QueryParser(Version.LUCENE_40, "contents",
new StandardAnalyzer(Version.LUCENE_40)).parse(querystr);
int hitsPerPage = 100;
IndexReader reader = DirectoryReader.open(FSDirectory.open(indexDir));
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(
hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
System.out.println("Found " + hits.length + " hits.");
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + "... " + d.get("filename"));
System.out.println("=====================================================");
System.out.println(d.get("contents"));
}
// reader can only be closed when there
// is no need to access the documents any more.
reader.close();
}这里d.get("contents")给出了索引时存储的.pdf文件的全文(generated by Tika)。
我想要一些关于搜索文本的信息,这样我就可以在我的网页上显示这些信息,或者正确地突出显示搜索的文本(如google搜索输出)。如何做到这一点呢?我们需要写一些逻辑吗?还是Lucene在内部写?
任何类型的帮助都将不胜感激。提前谢谢。
发布于 2013-12-11 00:55:53
org.apache.lucene.search.highlight包提供了此功能。
例如:
SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
String text = doc.get("contents");
String bestFrag = highlighter.getBestFragment(analyzer, "contents", text);
//output, however you like.您还可以从荧光笔中获得最佳片段的列表,而不只是单个片段,如果您愿意,请参阅Highlighter API
https://stackoverflow.com/questions/20496789
复制相似问题