Highlighting
是solr功能之一。您必须传递查询参数来实现突出显示,如下所示:-
hl
– 设置为 true,它可以在查询响应中生成突出显示的片段。
hl.fl
– 提及要突出显示的字段列表。 char * 将突出显示所有字段
hl.fragsize
– 由荧光笔创建的片段(又名片段)的大小(以字符为单位)。在原始荧光笔中,“0”表示应使用整个字段值,不分段。默认情况下片段大小为 100 个字符
通过添加以下代码进行检查。
params.setHighlight(true).setHighlightSnippets(1);
params.setParam("hl.fl", "*");
params.setParam("hl.fragsize", "0");
这是完整的代码供您尝试。
Note : 请忽略代码中的硬编码内容,
就像硬编码的 url "solrUrl = "http://localhost:8983/solr http://localhost:8983/solr”和字符串“返回“Success””。这些应该从属性文件和常量文件中读取。希望您也这样做。切勿在生产代码中使用 System out。
public String getResult() throws SolrServerException, IOException {
final SolrClient client = getSolrClient();
ModifiableSolrParams params = new ModifiableSolrParams ();
params.set ("q", "comment_t:pizza");
params.set ("fl", "id, comment_t");
params.set ("sort", "id asc");
params.set("hl", true);
params.set("hl.q", "pizza");
params.set("hl.simple.pre", "<strong>");
params.set("hl.simple.post", "</strong>");
params.set("hl.fl", "comment_t");
params.set("hl.fragsize", "100");
final QueryResponse response = client.query("demo", params);
response.getHighlighting();
final SolrDocumentList documents = response.getResults();
System.out.println("Found " + documents.getNumFound() + " documents");
for (SolrDocument document : documents) {
final String id = (String) document.getFirstValue("id");
final String name = (String) document.getFirstValue("comment_t");
System.out.println("id: " + id + "; comment_t: " + name);
if(response.getHighlighting() != null){
System.out.println("highlighted text :: " + response.getHighlighting());
}
}
return "Success";
}
private SolrClient getSolrClient() {
final String solrUrl = "http://localhost:8983/solr";
return new HttpSolrClient.Builder(solrUrl).withConnectionTimeout(10000).withSocketTimeout(60000).build();
}
请找到输出的屏幕截图: