Piyusha Jadhav
Piyusha Jadhav

Reputation: 141

Highlight search keyword in java

In my assignment I'm doing a search using solr.

  1. It works fine and returns result with highlighted keywords with fragment size 200 in header of result.
  2. When I click on the result, the header expands and shows whole result.

My problem is that I need to highlight keywords in opened results as well. How can I do that? Can I do it with solr or do I need to do it in java only?

Upvotes: 1

Views: 1246

Answers (2)

Lukas Gottschall
Lukas Gottschall

Reputation: 1

Case insensitive solution:

    String searchTerm="test", result="This is a TEST";
    Pattern pattern = Pattern.compile("(" + Pattern.quote(searchTerm.toLowerCase()) + ")",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    result = pattern.matcher(result).replaceAll("<strong>$1</strong>");

see https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html

Upvotes: 0

Matt
Matt

Reputation: 17639

The following two links should get you going:

Updated Answer:

One simple solution might be to iterate over the words of your search and replace them in the result before displaying it:

// warning: pseudcode ahead
List<String> newResults = new ArrayList<String>();
for(String result : search.getResults()) { // pseudocode, don't know the exact interface
  for(String word : searchQuery.split("\\s+")) {
    newResults.add(result.replaceAll(word, "<strong>" + word + "</strong>"));
  }
}

Upvotes: 1

Related Questions