@Override public String highlight(String locale, boolean useStopWords, String query, String content, String pre, String post, int preview) { Analyzer analyzer = termAnalyzers.findAnalyzer(locale, useStopWords); QueryParser parser = new QueryParser(defaultField, analyzer); String summary = null; try { SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(pre, post); Highlighter hg = new Highlighter(formatter, new QueryTermScorer(parser.parse(query))); hg.setMaxDocCharsToAnalyze(preview); hg.setTextFragmenter(new SimpleFragmenter(100)); TokenStream tokens = TokenSources.getTokenStream(defaultField, content, analyzer); summary = hg.getBestFragments(tokens, content, 4, " ... "); } catch (InvalidTokenOffsetsException | IOException | ParseException ex) { LOG.error("Failed to highlight", ex); } return StringUtils.isBlank(summary) ? null : summary; }
/** * Return a {@link org.apache.lucene.search.highlight.Scorer} suitable for this Query and field. * * @param query * The current query * @param fieldName * The name of the field * @param request * The SolrQueryRequest */ private Scorer getQueryScorer(Query query, String requestFieldname, String schemaFieldName, SolrQueryRequest request) { boolean reqFieldMatch = request.getParams().getFieldBool(requestFieldname, HighlightParams.FIELD_MATCH, false); if (reqFieldMatch) { return new QueryTermScorer(query, request.getSearcher().getIndexReader(), schemaFieldName); } else { return new QueryTermScorer(query); } }