Skip to content

Instantly share code, notes, and snippets.

@yrodiere
Created December 11, 2017 09:50
Show Gist options
  • Save yrodiere/b2f70e88f2f9700715867c4de25c1732 to your computer and use it in GitHub Desktop.
Save yrodiere/b2f70e88f2f9700715867c4de25c1732 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
public class Test {
@Test
public void test() throws Exception {
Query query = new TermQuery( new Term( "notAnalyzedField", "a-bbb-ccc" ) );
String highlighted = highlightText( query, new KeywordAnalyzer(), "notAnalyzedField", "a-bbb-ccc" );
Assert.assertEquals( "<span>a-bbb-ccc</span>", highlighted );
}
String highlightText(Query query, Analyzer analyzer, String fieldName, String text)
throws IOException, InvalidTokenOffsetsException {
QueryScorer queryScorer = new QueryScorer(query);
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span>", "</span>");
Highlighter highlighter = new Highlighter(formatter, queryScorer);
return highlighter.getBestFragment(analyzer, fieldName, text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment