public static Map<String, Object> search(String key,String index,String type,int start,int row){ //创建查询索引,要查询的索引库为index SearchRequestBuilder builder = getClient().prepareSearch(index); builder.setTypes(type); builder.setFrom(start); builder.setSize(row); //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序 builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); if(StringUtils.isNotBlank(key)){ // 设置查询关键词 builder.setQuery(QueryBuilders.multiMatchQuery(key, "title","describe")); } //设置是否按查询匹配度排序
builder.setExplain(true);
//设置高亮显示 HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false); highlightBuilder.preTags("<span style=\"color:red\">"); highlightBuilder.postTags("</span>"); builder.highlighter(highlightBuilder); //执行搜索,返回搜索响应信息 SearchResponse searchResponse = builder.get(); SearchHits searchHits = searchResponse.getHits(); //总命中数 long total = searchHits.getTotalHits(); Map<String, Object> map = new HashMap<String,Object>(); SearchHit[] hits = searchHits.getHits(); map.put("count", total); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (SearchHit hit : hits) { //highlightFields.size=0?? Map<String, HighlightField> highlightFields = hit.getHighlightFields(); //title高亮 HighlightField titleField = highlightFields.get("title"); Map<String, Object> source = hit.getSource(); if(titleField!=null){ Text[] fragments = titleField.fragments(); String name = ""; for (Text text : fragments) { name+=text; } source.put("title", name); } //describe高亮 HighlightField describeField = highlightFields.get("describe"); if(describeField!=null){ Text[] fragments = describeField.fragments(); String describe = ""; for (Text text : fragments) { describe+=text; } source.put("describe", describe); } list.add(source); } map.put("dataList", list); return map; }