Java Code Examples for org.elasticsearch.search.SearchHit#getHighlightFields()

The following examples show how to use org.elasticsearch.search.SearchHit#getHighlightFields() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XiaoEUKResultMapper.java    From youkefu with Apache License 2.0 7 votes vote down vote up
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null){
			PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
		}
		PropertyUtils.setProperty(t, "id" , hit.getId());
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
Example 2
Source File: UKResultMapper.java    From youkefu with Apache License 2.0 6 votes vote down vote up
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null){
			PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
		}
		PropertyUtils.setProperty(t, "id" , hit.getId());
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
Example 3
Source File: EKMResultMapper.java    From youkefu with Apache License 2.0 6 votes vote down vote up
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null && contentHightlightField.fragments()!=null && contentHightlightField.fragments().length >0 && !StringUtils.isBlank(contentHightlightField.fragments()[0].string())){
			PropertyUtils.setProperty(t, "summary" , contentHightlightField.fragments()[0].string());
		}
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
Example 4
Source File: HighlightResultMapper.java    From code with Apache License 2.0 6 votes vote down vote up
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> clazz, Pageable pageable) {
    SearchHits hits = searchResponse.getHits();
    List<T> result = new ArrayList<>((int) hits.getTotalHits());
    for (SearchHit searchHit : hits) {
        // 高亮 K,V
        Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
        // 使用反射比较通用一些,也可以直接 new 对象,把值set进去
        try {
            T document = objectMapper.readValue(searchHit.getSourceAsString(), clazz);
            for (Map.Entry<String, HighlightField> entry : highlightFields.entrySet()) {
                Field field = clazz.getField(entry.getKey());
                field.setAccessible(true);
                field.set(document, entry.getValue().fragments()[0].toString());
            }
            result.add(document);
        } catch (IllegalAccessException | IOException | NoSuchFieldException e) {
            e.printStackTrace();
        }

    }
    return new AggregatedPageImpl<>(result, pageable, hits.getTotalHits());
}
 
Example 5
Source File: PostServiceImpl.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Page<Post> findPostsByEs(Map<String, Object> criteria, Page<Post> page) {

    //search request
    SearchRequest searchRequest = new SearchRequest("blog");

    //search builder
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    BoolQueryBuilder booleanQueryBuilder = QueryBuilders.boolQuery();
    for (String key : criteria.keySet()) {
        booleanQueryBuilder.must(QueryBuilders.matchQuery(key, criteria.get(key)));
    }

    sourceBuilder.query(booleanQueryBuilder);
    sourceBuilder.from(Integer.parseInt(String.valueOf((page.getCurrent() - 1) * page.getSize())));
    sourceBuilder.size(Integer.parseInt(String.valueOf(page.getSize())));
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

    //sort
    sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));

    //highlight
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("postTitle");
    highlightTitle.preTags("<span class=\"highlight\">");
    highlightTitle.postTags("</span>");
    highlightBuilder.field(highlightTitle);
    sourceBuilder.highlighter(highlightBuilder);

    // add builder into request
    searchRequest.indices("blog");
    searchRequest.source(sourceBuilder);

    //response
    SearchResponse searchResponse = null;
    List<Post> postList = new ArrayList<>();
    try {
        searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //search hits
        SearchHits hits = searchResponse.getHits();
        long totalHits = hits.getTotalHits();

        SearchHit[] searchHits = hits.getHits();
        page.setTotal((int) totalHits);
        for (SearchHit hit : searchHits) {
            String str = hit.getSourceAsString();
            Post esPost = JSONObject.parseObject(str, Post.class);
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("postTitle");
            if (highlight != null) {
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                esPost.setPostTitle(fragmentString);
            }
            postList.add(esPost);
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("ES未开启: {}", e);
    }
    return page.setRecords(postList);
}
 
Example 6
Source File: SearchServiceImpl.java    From emotional_analysis with Apache License 2.0 4 votes vote down vote up
@Override
public PageBean<Map<String,Object>> getSearchResult(int page, int rows,String content) throws Exception {

	PageBean<Map<String, Object>> searchListPageBean = new PageBean<Map<String, Object>>();
	BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
	boolBuilder.must(QueryBuilders.matchQuery("content", content));
	PageHelper.startPage(page, rows);
	SearchRequestBuilder searchRequestBuilder = ESClientUtils.getClient().prepareSearch("hotcomments")
			.setTypes("logs").setSearchType(SearchType.DFS_QUERY_THEN_FETCH) 
			.setQuery(boolBuilder).setFrom(page).setSize(3);
	long totalHits = ESClientUtils.getClient().prepareSearch("hotcomments").setTypes("logs")
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(boolBuilder).get().getHits().getTotalHits();
	searchRequestBuilder.setHighlighterPostTags("</span>");
	searchRequestBuilder.setHighlighterPreTags("<span style=\"color:red\">");
	searchRequestBuilder.addHighlightedField("content");
	// 执行结果
	SearchResponse response = searchRequestBuilder.get();
	// 接受结果
	List<Map<String, Object>> result = new ArrayList<>();
	// 遍历结果
	for (SearchHit hit : response.getHits()) {
		Map<String, Object> source = hit.getSource();
		String songName = null;
		String songUrl = null;
		Set<Entry<String, Object>> entrySet = source.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			if (entry.getKey().equals("songId")) {
				Integer songId = (Integer) entry.getValue();
				songName = SearchUtils.getSongNameById(songId);
				songUrl = SearchUtils.getSongUrlById(songId);
			}
		}
		source.put("songName", songName);
		source.put("songUrl", songUrl);
		// 处理高亮片段
		Map<String, HighlightField> highlightFields = hit.getHighlightFields();
		HighlightField nameField = highlightFields.get("content");
		if (nameField != null) {
			Text[] fragments = nameField.fragments();
			String nameTmp = "";
			for (Text text : fragments) {
				nameTmp += text;
			}
			// 将高亮片段组装到结果中去
			source.put("content", nameTmp);
		}
		result.add(source);
	}
	long totalPage = (totalHits + 3 - 1) / 3;
	if(page > totalPage){
		page = 1;
	}
	searchListPageBean.setPage(page);
	searchListPageBean.setTotalPage(totalPage);
	searchListPageBean.setList(result);
	return searchListPageBean;
}
 
Example 7
Source File: ESClientTest.java    From emotional_analysis with Apache License 2.0 4 votes vote down vote up
@Test
  public void test5(){
      BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();  
      //使用should实现或者查询  
      boolBuilder.should(QueryBuilders.matchQuery("content","爱我"));  
      //c查询  
      SearchRequestBuilder searchRequestBuilder = this.client.prepareSearch("hotcomments")  
              .setTypes("logs")  
              .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序  
              .setQuery(boolBuilder)  
              .setSize(10);  
 
      //设置高亮显示  
      searchRequestBuilder.setHighlighterPostTags("</span>");
      searchRequestBuilder.setHighlighterPreTags("<span style=\"color:red\">");
      searchRequestBuilder.addHighlightedField("content"); 
      //执行结果  
      SearchResponse response = searchRequestBuilder.get();  
      //接受结果  
      List<Map<String,Object>> result = new ArrayList<>();  
      //遍历结果  
      for(SearchHit hit:response.getHits()){  
          Map<String, Object> source = hit.getSource();  
          //处理高亮片段  
          Map<String, HighlightField> highlightFields = hit.getHighlightFields();  
          HighlightField nameField = highlightFields.get("content");  
          if(nameField!=null){  
              Text[] fragments = nameField.fragments();  
              String nameTmp ="";  
              for(Text text:fragments){  
                  nameTmp+=text;  
              }  
              //将高亮片段组装到结果中去  
              source.put("content",nameTmp);
          }  
          result.add(source);  
      }  
      for (Map<String, Object> map : result) {
	Set<Entry<String, Object>> entrySet = map.entrySet();
	for (Entry<String, Object> entry : entrySet) {
		System.out.println(entry.getKey()+":::"+entry.getValue());
	}
}
  }