1. 程式人生 > >elasticsearch高亮顯示

elasticsearch高亮顯示

高亮搜尋:

許多應用都傾向於在每個搜尋結果中 高亮 顯示搜尋的關鍵詞,比如字型的加粗,改變字型的顏色等.以便讓使用者知道為何該文件符合查詢條件。在 Elasticsearch 中檢索出高亮片段也很容易。

為了執行突出顯示,需要該欄位的實際內容。如果儲存了相關欄位(已 在對映中store設定true),則將使用_source該欄位,否則將載入實際欄位並從中提取相關欄位。

_all欄位無法從中提取_source,因此只有在對映為已store設定的情況下才能用於突出顯示true

在執行語句的前面,增加一個新的 highlight 引數:

GET /megacorp/employee/_search
{
    "query" : {
        "match_phrase" : {
            "about" : "rock climbing"
        }
    },
    "highlight": {
        "fields" : {
            "about" : {}
        }
    }
}

當執行該查詢時,返回結果與之前一樣,與此同時結果中還多了一個叫做 highlight 的部分。這個部分包含了 about 屬性匹配的文字片段,並以 HTML 標籤 <em></em>

 封裝:

{
   ...
   "hits": {
      "total":      1,
      "max_score":  0.23013961,
      "hits": [
         {
            ...
            "_score":         0.23013961,
            "_source": {
               "first_name":  "John",
               "last_name":   "Smith",
               "age":         25,
               "about":       "I love to go rock climbing",
               "interests": [ "sports", "music" ]
            },
            "highlight": {
               "about": [
                  "I love to go <em>rock</em> <em>climbing</em>" 
               ]
            }
         }
      ]
   }
}

下面看一下JAVA,API的實現,對title欄位返回的結果,高亮顯示搜尋關鍵字,也是非常的簡單.

package com.bonc.test;

import com.bonc.entity.ParamsEntity;
import net.sf.json.JSONObject;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * es的高亮顯示;
 */
public class Test {
    private SearchResponse response = null;
    public String query(TransportClient client, ParamsEntity p) {
        List list = new ArrayList();
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("").setTypes("");
        searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        searchRequestBuilder.setFrom(p.getPage()).setSize(p.getSize()).setExplain(true);
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").requireFieldMatch(true);
        highlightBuilder.preTags("<span style=\"color:red\">");
        highlightBuilder.postTags("</span>");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.queryStringQuery(p.getTitle()).field("title").defaultOperator(Operator.AND));
        try {
            response = searchRequestBuilder.execute().get();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("報錯了---------------------" + e.getMessage());
        }
        SearchHits hits = response.getHits();
        long totalHits = response.getHits().totalHits;
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSONObject.fromObject(sourceAsString);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            if (title != null) {
                Text[] fragments = title.fragments();
                String str = "";
                for (Text text : fragments) {
                    str += text;
                }
                jsonObject.put("title", str);
                list.add(jsonObject);
            }
        }
        Map map = new HashMap<String, Object>();
        map.put("total", totalHits);
        map.put("rows", list);
        return JSONObject.fromObject(map).toString();
    }
}

如果有寫的不對的地方,歡迎大家指正,如果有什麼疑問,可以加QQ群:340297350,謝謝