Java Code Examples for org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder#field()

The following examples show how to use org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder#field() . 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: ESSearchTest.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Test
public void highLightResultSet() {
    HighLight highLight = new HighLight();
    HighlightBuilder hBuilder = new HighlightBuilder();
    hBuilder.preTags("<h2>");
    hBuilder.postTags("</h2>");
    hBuilder.field("productName");

    queryPair.setFieldNames(new String[] {"productName"});
    queryPair.setContent("*");
    queryCondition.setSearchType(SearchType.QUERY_THEN_FETCH);
    queryCondition
        .setQueryBuilder(QueryBuilders.wildcardQuery(queryPair.getFieldNames()[0], queryPair.getContent()));

    highLight.setBuilder(hBuilder);
    highLight.setField("productName");

    List<Map<String, Object>> sourceList =
        elasticsearchTemplate.highLightResultSet(esBasicInfo, queryCondition, highLight);

    assertThat(sourceList.size(), is(3));
    assertThat((String)sourceList.get(0).get("productName"), containsString("运"));
    assertThat((String)sourceList.get(1).get("productName"), containsString("android"));
    assertThat((String)sourceList.get(2).get("productName"), containsString("华"));
}
 
Example 2
Source File: ESSearchTest.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Test
public void highLightResultSet() {
    HighLight highLight = new HighLight();
    HighlightBuilder hBuilder = new HighlightBuilder();
    hBuilder.preTags("<h2>");
    hBuilder.postTags("</h2>");
    hBuilder.field("productName");

    queryPair.setFieldNames(new String[] {"productName"});
    queryPair.setContent("*");
    queryCondition.setSearchType(SearchType.QUERY_THEN_FETCH);
    queryCondition
        .setQueryBuilder(QueryBuilders.wildcardQuery(queryPair.getFieldNames()[0], queryPair.getContent()));

    highLight.setBuilder(hBuilder);
    highLight.setField("productName");

    List<Map<String, Object>> sourceList =
        elasticsearchTemplate.highLightResultSet(esBasicInfo, queryCondition, highLight);

    assertThat(sourceList.size(), is(3));
    assertThat((String)sourceList.get(0).get("productName"), containsString("运"));
    assertThat((String)sourceList.get(1).get("productName"), containsString("android"));
    assertThat((String)sourceList.get(2).get("productName"), containsString("华"));
}
 
Example 3
Source File: ElasticsearchHelperService.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 增加高亮词
 *
 * @param keywords
 * @param highlightBuilder
 */
private void AddHighLigh(JSONObject keywords, HighlightBuilder highlightBuilder) {
    if (keywords == null || keywords.size() <= 0) {
        return;
    }
    Iterator<Map.Entry<String, Object>> iterator = keywords.entrySet().iterator();
    if (iterator == null) {
        return;
    }
    while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        String key = next.getKey();
        Object value = next.getValue();
        if (value == null || value.toString().length() <= 0) {
            continue;
        }
        highlightBuilder.preTags("<span style=color:red>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.field(key);
    }
}
 
Example 4
Source File: ElasticsearchQuery.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Highlights the given field or all fields if null.
 */
@Override
public void highlight(IRI property) {
	String field = (property != null)
			? ElasticsearchIndex.toPropertyFieldName(SearchFields.getPropertyField(property))
			: ElasticsearchIndex.ALL_PROPERTY_FIELDS;
	HighlightBuilder hb = new HighlightBuilder();
	hb.field(field);
	hb.preTags(SearchFields.HIGHLIGHTER_PRE_TAG);
	hb.postTags(SearchFields.HIGHLIGHTER_POST_TAG);
	// Elastic Search doesn't really have the same support for fragments as Lucene.
	// So, we have to get back the whole highlighted value (comma-separated if it is a list)
	// and then post-process it into fragments ourselves.
	hb.numOfFragments(0);
	request.highlighter(hb);
}
 
Example 5
Source File: QueryAction.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
protected void updateRequestWithHighlight(Select select, SearchRequestBuilder request) {
    boolean foundAnyHighlights = false;
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    for (Hint hint : select.getHints()) {
        if (hint.getType() == HintType.HIGHLIGHT) {
            HighlightBuilder.Field highlightField = parseHighlightField(hint.getParams());
            if (highlightField != null) {
                foundAnyHighlights = true;
                highlightBuilder.field(highlightField);
            }
        }
    }
    if (foundAnyHighlights) {
        request.highlighter(highlightBuilder);
    }
}
 
Example 6
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 使用分词查询  排序 高亮
 * @param index          索引名称
 * @param type           类型名称,可传入多个type逗号分隔
 * @param query          查询条件
 * @param size           文档大小限制
 * @param fields         需要显示的字段,逗号分隔(缺省为全部字段)
 * @param sortField      排序字段
 * @param highlightField 高亮字段
 * @return 结果
 */
public static List<Map<String, Object>> searchListData(String index, String type, QueryBuilder query, Integer size, String fields, String sortField, String highlightField) {
    SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
    if (StringUtils.isNotEmpty(type)) {
        searchRequestBuilder.setTypes(type.split(","));
    }
    if (StringUtils.isNotEmpty(highlightField)) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // 设置高亮字段
        highlightBuilder.field(highlightField);
        searchRequestBuilder.highlighter(highlightBuilder);
    }
    searchRequestBuilder.setQuery(query);
    if (StringUtils.isNotEmpty(fields)) {
        searchRequestBuilder.setFetchSource(fields.split(","), null);
    }
    searchRequestBuilder.setFetchSource(true);
    if (StringUtils.isNotEmpty(sortField)) {
        searchRequestBuilder.addSort(sortField, SortOrder.ASC);
    }
    if (size != null && size > 0) {
        searchRequestBuilder.setSize(size);
    }//打印的内容 可以在 Elasticsearch head 和 Kibana  上执行查询
    log.info("\n{}", searchRequestBuilder);
    SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
    long totalHits = searchResponse.getHits().totalHits;
    long length = searchResponse.getHits().getHits().length;
    log.info("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length);
    if (searchResponse.status().getStatus() == 200) {
        // 解析对象
        return setSearchResponse(searchResponse, highlightField);
    }
    return null;
}
 
Example 7
Source File: SearchServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds the configured highlighting to the given builder
 * @param builder the search builder to update
 */
protected void updateHighlighting(SearchSourceBuilder builder) {
    HighlightBuilder highlight = SearchSourceBuilder.highlight();
    for (String field : highlightFields) {
        highlight.field(field, snippetSize, numberOfSnippets);
    }
    builder.highlighter(highlight);
}
 
Example 8
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);
}