All Products
Search
Document Center

Tablestore:Highlight the query results

Last Updated:Oct 17, 2024

When you initiate a query request, you can enable the highlight feature. In this case, the keywords in the results that meet the query conditions are highlighted. Only Text fields support the highlight feature.

Prerequisites

Usage notes

  • If you enable the highlight feature in a match query or match phrase query, the query strings in the query results may be highlighted by using multiple opening tags (preTag) and closing tags (postTag).

  • If the tokenization method of a Text field is maximum semantic unit-based tokenization (MaxWord), the highlight feature is not supported when you perform a match phrase query on the Text field.

  • If you want to return multiple fragments, the query strings in the fragments may be split. In this case, the query strings may not be highlighted.

Parameters

Parameter

Description

highlightEncoder

The encoding method of the highlighted text fragments. Valid values:

  • PLAIN (default): displays the highlighted text fragments without the need for encoding.

  • HTML: performs HTML encoding on the highlighted text fragments. After HTML encoding is complete, < is converted into &lt;, > into &gt;, " into &quot;, ' into &#x27;, and / into &#x2F;. If you want to display web pages, we recommend that you use the HTML format.

fieldHighlightParams

The highlight settings for the field. You can enable the highlight feature only for fields that contain the keywords specified in SearchQuery objects.

HighlightParameter

numberOfFragments

The maximum number of highlighted text fragments to return. We recommend that you set the value to 1.

fragmentSize

The length of each text fragment to return. Default value: 100.

Important

The actual length of the returned text fragment may differ from the value of this parameter.

preTag

The opening tag used to highlight the query keywords. Examples: <em> and <b>. Default value: <em>. You can specify a custom opening tag based on your business requirements. The preTag parameter supports the following character sets: < > " ' /, a-z, A-Z, and 0-9.

postTag

The closing tag used to highlight the query keywords. Examples: </em> and </b>. Default value: <em>. You can specify a custom closing tag based on your business requirements. The postTag parameter supports the following character sets: < > " ' /, a-z, A-Z, and 0-9.

highlightFragmentOrder

The sorting rule of the highlighted text fragments to return.

  • TEXT_SEQUENCE (default): The highlighted text fragments are sorted based on the order of their appearance in the original text.

  • SCORE: The highlighted text fragments are sorted based on the score of the hit keywords.

Example

The following sample code provides an example on how to use the MatchQuery feature to query data that matches hangzhou shanghai from the Col_Text field and highlight the keywords in the query results. In this example, the Col_Text field is of the Text type.

/**
 * Enable the highlight feature for keywords in the MatchQuery object. 
 */
public static void matchQueryWithHighlighting(SyncClient client) {
    SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .returnAllColumnsFromIndex(true)
            .searchQuery(SearchQuery.newBuilder()
                    .limit(5)
                    .query(QueryBuilders.bool()
                            .should(QueryBuilders.match("Col_Text", "hangzhou shanghai")))
                    .highlight(Highlight.newBuilder()
                            .addFieldHighlightParam("Col_Text", HighlightParameter.newBuilder()
                                    .highlightFragmentOrder(HighlightFragmentOrder.TEXT_SEQUENCE)
                                    .preTag("<b>")
                                    .postTag("</b>")
                                    .build())
                            .build())
                    .build())
            .build();
    SearchResponse resp = client.search(searchRequest);

    // Display the highlighted query results. When you query a non-Nested field, set the prefix parameter to null. 
    printSearchHit(resp.getSearchHits(), "");
}

/**
 * Display the content that meets the query conditions. 
 * @param searchHits searchHits
 * If the output uses the @param prefix Nested structure, add the prefix to display the hierarchy information. 
 */
private static void printSearchHit(List<SearchHit> searchHits, String prefix) {
    for (SearchHit searchHit : searchHits) {
        if (searchHit.getScore() != null) {
            System.out.printf("%s Score: %s\n", prefix, searchHit.getScore());
        }

        if (searchHit.getOffset() != null) {
            System.out.printf("%s Offset: %s\n", prefix, searchHit.getOffset());
        }

        if (searchHit.getRow() != null) {
            System.out.printf("%s Row: %s\n", prefix, searchHit.getRow().toString());
        }

        // Display the highlighted fragments for each field. 
        if (searchHit.getHighlightResultItem() != null) {
            System.out.printf("%s Highlight: \n", prefix);
            StringBuilder strBuilder = new StringBuilder();
            for (Map.Entry<String, HighlightField> entry : searchHit.getHighlightResultItem().getHighlightFields().entrySet()) {
                strBuilder.append(entry.getKey()).append(":").append("[");
                strBuilder.append(StringUtils.join(",", entry.getValue().getFragments())).append("]\n");
            }
            System.out.printf("%s   %s", prefix, strBuilder);
        }

        System.out.println();
    }
}

References

  • For information about the highlight feature, see Highlight keywords.

  • For information about how to use the highlight feature when you query Nested fields, see Nested query.