天天看點

Elasticsearch關鍵詞高亮檢索案例分享

1.準備工作

參考文檔《

內建Elasticsearch Restful API案例

》導入和配置es用戶端

2.建立索引表和初始化資料

通過元件

DocumentCRUD 來建立索引表和初始化資料, 元件實作本文不做重點介紹:

/**
 * 建立索引表,并導入高亮檢索功能需要的測試資料
 */
public void initIndiceAndData(){
   DocumentCRUD documentCRUD = new DocumentCRUD();
   documentCRUD.testCreateIndice();
   documentCRUD.testBulkAddDocuments();
}      

3.高亮檢索功能實作

3.1 定義高亮檢索dsl

在檔案

esmapper/demo.xml

中增加testHighlightSearch配置:

<!--
        一個簡單的檢索dsl,中有四個變量
        name 全文檢索字段
        startTime
        endTime
        通過map傳遞變量參數值

        變量文法參考文檔:https://my.oschina.net/bboss/blog/1556866
    -->
    <property name="testHighlightSearch">
        <![CDATA[{
            "query": {
                "bool": {
                    "filter": [
                        {   ## 時間範圍檢索,傳回對應時間範圍内的記錄,接受long型的值
                            "range": {
                                "agentStarttime": {
                                    "gte": #[startTime],##統計開始時間
                                    "lt": #[endTime]  ##統計截止時間
                                }
                            }
                        }
                    ],
                    "must": [
                        #*
                        {
                            "query_string": {
                                "query": #[condition],
                                "analyze_wildcard": true
                            }
                        }
                        *#
                        {
                        ## 全文檢索參考文檔  https://www.elastic.co/guide/en/elasticsearch/reference/6.2/full-text-queries.html
                            "match_phrase" : {
                                "name" : {
                                    "query" : #[condition]
                                }
                            }
                        }
                    ]
                }
            },
            ## 最多傳回1000條記錄
            "size":1000,
            ## 高亮檢索定義,參考文檔:https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-highlighting.html
            "highlight": {
                "pre_tags": [
                    "<mark>"
                ],
                "post_tags": [
                    "</mark>"
                ],
                "fields": {
                    "*": {}
                },
                "fragment_size": 2147483647
            }
        }]]>
    </property>      

3.2 編寫高亮檢索代碼

建立檢索類-org.bboss.elasticsearchtest.HighlightSearch

在其中定義以下方法

public void highlightSearch() throws ParseException {
		//建立加載配置檔案的用戶端工具,用來檢索文檔,單執行個體多線程安全
		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil(mappath);
		//設定查詢條件,通過map傳遞變量參數值,key對于dsl中的變量名稱
		//dsl中有三個變量
		//        condition
		//        startTime
		//        endTime
		Map<String,Object> params = new HashMap<String,Object>();

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//設定時間範圍,時間參數接受long值
		params.put("startTime",dateFormat.parse("2017-09-02 00:00:00"));
		params.put("endTime",new Date());
		params.put("condition","喜歡唱歌");//全文檢索條件,比對上的記錄的字段值對應的比對内容都會被高亮顯示
		//執行查詢,demo為索引表,_search為檢索操作action
		ESDatas<Demo> esDatas =  //ESDatas包含目前檢索的記錄集合,最多1000條記錄,由dsl中的size屬性指定
				clientUtil.searchList("demo/_search",//demo為索引表,_search為檢索操作action
						"testHighlightSearch",//esmapper/demo.xml中定義的dsl語句
						params,//變量參數
						Demo.class);//傳回的文檔封裝對象類型
		//擷取總記錄數
		long totalSize = esDatas.getTotalSize();
		System.out.println(totalSize);
		//擷取結果對象清單,最多傳回1000條記錄
		List<Demo> demos = esDatas.getDatas();
		for(int i = 0; demos != null && i < demos.size(); i ++){//周遊檢索結果清單
			Demo demo = demos.get(i);
			//記錄中比對上檢索條件的所有字段的高亮内容
			Map<String,List<Object>> highLights = demo.getHighlight();
			Iterator<Map.Entry<String, List<Object>>> entries = highLights.entrySet().iterator();
			while(entries.hasNext()){
				Map.Entry<String, List<Object>> entry = entries.next();
				String fieldName = entry.getKey();
				System.out.print(fieldName+":");
				List<Object> fieldHighLightSegments = entry.getValue();
				for (Object highLightSegment:fieldHighLightSegments){
					/**
					 * 在dsl中通過<mark></mark>來辨別需要高亮顯示的内容,然後傳到web ui前端的時候,通過為mark元素添加css樣式來設定高亮的顔色背景樣式
					 * 例如:
					 * <style type="text/css">
					 *     .mark,mark{background-color:#f39c12;padding:.2em}
					 * </style>
					 */
					System.out.println(highLightSegment);
				}
			}
		}
	}      

4.運作檢索功能

定義junit測試用例:

import org.junit.Test;

import java.text.ParseException;

public class HighlightSearchTest {

	@Test
	public void testHighlightSearch() throws ParseException {
		HighlightSearch highlightSearch = new HighlightSearch();
		highlightSearch.initIndiceAndData();
		highlightSearch.highlightSearch();
	}
	@Test
	public void testHighlightSearchOther() throws ParseException {
		HighlightSearch highlightSearch = new HighlightSearch();
		highlightSearch.initIndiceAndData();
		highlightSearch.highlightSearchOther();
	}
}      

在idea或者eclipse中運作測試用例即可,輸出檢索到的高亮内容資訊如下:

name:劉德華<mark>喜</mark><mark>歡</mark><mark>唱</mark><mark>歌</mark>454
name:劉德華<mark>喜</mark><mark>歡</mark><mark>唱</mark><mark>歌</mark>488
name:劉德華<mark>喜</mark><mark>歡</mark><mark>唱</mark><mark>歌</mark>508
name:劉德華<mark>喜</mark><mark>歡</mark><mark>唱</mark><mark>歌</mark>518      

5.完整的demo執行個體工程

https://github.com/bbossgroups/eshelloword-booter https://gitee.com/bbossgroups/eshelloword-booter

6.參考文檔

https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-highlighting.html https://my.oschina.net/bboss/blog/1801273

5 開發交流

elasticsearch技術交流群:166471282

elasticsearch微信公衆号:bbossgroups

Elasticsearch關鍵詞高亮檢索案例分享