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

The following examples show how to use org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder#preTags() . 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: SearchService.java    From jakduk-api with MIT License 6 votes vote down vote up
private SearchRequestBuilder getCommentSearchRequestBuilder(String query, Integer from, Integer size, String preTags,
															String postTags) {

	HighlightBuilder highlightBuilder = new HighlightBuilder()
			.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
			.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
			.field("content", Constants.SEARCH_FRAGMENT_SIZE, 1);

	SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
			.setIndices(elasticsearchProperties.getIndexBoard())
			.setTypes(Constants.ES_TYPE_COMMENT)
			.setFetchSource(null, new String[]{"content"})
			.setQuery(
					QueryBuilders.boolQuery()
							.must(QueryBuilders.matchQuery("content", query))
							.must(JoinQueryBuilders
                                       .hasParentQuery(Constants.ES_TYPE_ARTICLE, QueryBuilders.matchAllQuery(), false)
                                       .innerHit(new InnerHitBuilder())
							)
			)
			.setFrom(from)
			.setSize(size);

	if (StringUtils.isNotBlank(preTags))
		highlightBuilder.preTags(preTags);

	if (StringUtils.isNotBlank(postTags))
		highlightBuilder.postTags(postTags);

	searchRequestBuilder.highlighter(highlightBuilder);
	log.debug("getBoardCommentSearchRequestBuilder Query:\n{}", searchRequestBuilder);

	return searchRequestBuilder;
}
 
Example 6
Source File: SearchService.java    From jakduk-api with MIT License 5 votes vote down vote up
private SearchRequestBuilder getArticleSearchRequestBuilder(String query, Integer from, Integer size, String preTags,
															String postTags) {

	HighlightBuilder highlightBuilder = new HighlightBuilder()
			.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
			.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
			.field("subject", Constants.SEARCH_FRAGMENT_SIZE, 0)
			.field("content", Constants.SEARCH_FRAGMENT_SIZE, 1);

	SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
			.setIndices(elasticsearchProperties.getIndexBoard())
			.setTypes(Constants.ES_TYPE_ARTICLE)
			.setFetchSource(null, new String[]{"subject", "content"})
			.setQuery(
					QueryBuilders.boolQuery()
							.should(QueryBuilders.multiMatchQuery(query, "subject", "content").field("subject", 1.5f))
			)
			.setFrom(from)
			.setSize(size);

	if (StringUtils.isNotBlank(preTags))
		highlightBuilder.preTags(preTags);

	if (StringUtils.isNotBlank(postTags))
		highlightBuilder.postTags(postTags);

	searchRequestBuilder.highlighter(highlightBuilder);
	log.debug("getArticleSearchRequestBuilder Query:\n{}", searchRequestBuilder);

	return searchRequestBuilder;
}
 
Example 7
Source File: SearchService.java    From jakduk-api with MIT License 5 votes vote down vote up
private SearchRequestBuilder getGallerySearchRequestBuilder(String query, Integer from, Integer size, String preTags,
															String postTags) {

	HighlightBuilder highlightBuilder = new HighlightBuilder()
			.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
			.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
			.field("name", Constants.SEARCH_FRAGMENT_SIZE, 0);

	SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
			.setIndices(elasticsearchProperties.getIndexGallery())
			.setTypes(Constants.ES_TYPE_GALLERY)
			.setFetchSource(null, new String[]{"name"})
			.setQuery(QueryBuilders.matchQuery("name", query))
			.setFrom(from)
			.setSize(size);

	if (StringUtils.isNotBlank(preTags))
		highlightBuilder.preTags(preTags);

	if (StringUtils.isNotBlank(postTags))
		highlightBuilder.postTags(postTags);

	searchRequestBuilder.highlighter(highlightBuilder);
	log.debug("getGallerySearchRequestBuilder Query:\n{}", searchRequestBuilder);

	return searchRequestBuilder;
}
 
Example 8
Source File: IndexSearchDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a {@link HighlightBuilder} based on (pre/post)tags and fields fetched from the DB config which is added to the main {@link SearchRequestBuilder}
 *
 * @param preTag The specified pre-tag to be used for highlighting
 * @param postTag The specified post-tag to be used for highlighting
 * @param match the set of match fields that are to be searched upon in the index search
 *
 * @return A configured {@link HighlightBuilder} object
 */
private HighlightBuilder buildHighlightQuery(String preTag, String postTag, Set<String> match)
{
    HighlightBuilder highlightBuilder = new HighlightBuilder();

    // Field matching is not needed since we are matching on multiple 'type' fields like stemmed and ngrams and enabling highlighting on all those fields
    // will yield duplicates
    highlightBuilder.requireFieldMatch(false);

    // Set the configured value for pre-tags for highlighting
    highlightBuilder.preTags(preTag);

    // Set the configured value for post-tags for highlighting
    highlightBuilder.postTags(postTag);

    // Get highlight fields value from configuration
    String highlightFieldsValue;

    // If the match column is included
    if (match != null && match.contains(MATCH_COLUMN))
    {
        highlightFieldsValue = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_COLUMN_MATCH_HIGHLIGHT_FIELDS);
    }
    else
    {
        highlightFieldsValue = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_HIGHLIGHT_FIELDS);
    }

    try
    {
        @SuppressWarnings("unchecked")
        IndexSearchHighlightFields highlightFieldsConfig = jsonHelper.unmarshallJsonToObject(IndexSearchHighlightFields.class, highlightFieldsValue);

        highlightFieldsConfig.getHighlightFields().forEach(highlightFieldConfig ->
        {

            // set the field name to the configured value
            HighlightBuilder.Field highlightField = new HighlightBuilder.Field(highlightFieldConfig.getFieldName());

            // set matched_fields to the configured list of fields, this accounts for 'multifields' that analyze the same string in different ways
            if (CollectionUtils.isNotEmpty(highlightFieldConfig.getMatchedFields()))
            {
                highlightField.matchedFields(highlightFieldConfig.getMatchedFields().toArray(new String[0]));
            }

            // set fragment size to the configured value
            if (highlightFieldConfig.getFragmentSize() != null)
            {
                highlightField.fragmentSize(highlightFieldConfig.getFragmentSize());
            }

            // set the number of desired fragments to the configured value
            if (highlightFieldConfig.getNumOfFragments() != null)
            {
                highlightField.numOfFragments(highlightFieldConfig.getNumOfFragments());
            }

            highlightBuilder.field(highlightField);
        });

    }
    catch (IOException e)
    {
        LOGGER.warn("Could not parse the configured value for highlight fields: {}", highlightFieldsValue, e);
    }

    return highlightBuilder;
}