public List<LuceneSearchResult> search(String keyword, boolean highlight, int size) throws IOException, ParseException { IndexReader reader = luceneIndex.reader(); try { IndexSearcher searcher = new IndexSearcher(reader); Analyzer analyzer = new IKAnalyzer(); MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_4_9, fields, analyzer, boosts); // 将关键字包装成Query对象 Query query = parser.parse(keyword); TopDocs results = searcher.search(query, size); FragListBuilder fragListBuilder = new SimpleFragListBuilder(); FragmentsBuilder fragmentsBuilder = new ScoreOrderFragmentsBuilder( BaseFragmentsBuilder.COLORED_PRE_TAGS, BaseFragmentsBuilder.COLORED_POST_TAGS); FastVectorHighlighter fvh = new FastVectorHighlighter(true, true, fragListBuilder, fragmentsBuilder); FieldQuery fq = fvh.getFieldQuery(query); // System.out.println("命中--》" + results.totalHits); List<LuceneSearchResult> searchResults = new ArrayList<LuceneSearchResult>(); for (ScoreDoc sd : results.scoreDocs) { // 当查询不到高亮信息时,返回内容为Null // String highContent = fvh.getBestFragment(fq, reader, sd.doc, "content", 100); // System.out.println("highContent-->" + highContent); String highTitle = null; if (highlight) { fvh.getBestFragment(fq, reader, sd.doc, "title", 100); if (highTitle == null) { Document doc = searcher.doc(sd.doc); /** 如果高亮内容为null,那么表示标题没有需要高亮的内容,那么赋值为原有标题 */ highTitle = doc.get("title"); } } else { highTitle = searcher.doc(sd.doc).get("title"); } String id = searcher.doc(sd.doc).get("id"); searchResults.add(new LuceneSearchResult(id, highTitle)); } return searchResults; } finally { reader.close(); } }
public void close() throws IOException { if (luceneIndex != null) luceneIndex.close(); }