solr 关键词高亮

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/gs_albb/article/details/83120006

solr在通过用户输入文字进行搜索后,搜索返回的结果文档一般都要对输入关键词进行高亮,方便用户定位搜索目标在文档中的位置。solr、elasticsearch都提供了关键词高亮显示的API和SDK。本文将简要说明下solr中如何对搜索结果进行关键词高亮显示。


高亮API

官方文档中定义了搜索结果高亮的url参数名称,主要的如下:

字段 默认值 说明
hl false 是否开启高亮显示
hl.fl (df=) 要高亮的字段
hl.q (q=) 要高亮的文字内容
hl.tag.pre <em> 要高亮的内容html标签前缀
hl.tag.post </em> 要高亮的内容html标签后缀

测试示例:

http://localhost:8983/solr/gettingstarted/select?hl=on&q=apple&wt=json&hl.fl=manu&fl=id,name,manu,cat


高亮SDK

示例代码:

    // springboot + solr 测试结果高亮
    @Test
    public void testHighLight() throws IOException, SolrServerException {
        SolrQuery solrQuery = new SolrQuery();
        //查询字段
        solrQuery.setQuery("item_title:大衣马夹");
        //solrQuery.setQuery("title:大衣马夹");
        solrQuery.set("q.op","AND");
        solrQuery.setHighlight(true);
        //要高亮的字段
        //注意,要高亮的字段类型最好与查询的字段类型一致
        //例如:这里item_title和item_title1字段类型都是text_ik类型
        solrQuery.addHighlightField("item_title1");
        QueryResponse response = client.query("item_v2", solrQuery);
        System.out.println(response);
    }

猜你喜欢

转载自blog.csdn.net/gs_albb/article/details/83120006