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 of the field. You can enable the highlight feature only for fields that contain keywords specified in SearchQuery objects.

HighlightParameter

NumberOfFragments

The maximum number of highlighted text fragments that you want to return. We recommend that you set this parameter to 1.

FragmentSize

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

Important

The actual length of the returned text fragment may be different 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 an 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 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 that you want 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.

func MatchQuerywithHighlight(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.MatchQuery{} // Set the query type to MatchQuery. 
    query.FieldName = "Col_Text"  // Specify the field that you want to match. 
    query.Text = "hangzhou shanghai"  // Specify the keyword that you want to match. 
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    highlight := &search.Highlight{
        FieldHighlightParameters: map[string]*search.HighlightParameter{
            "Col_Text": {
                NumberOfFragments: proto.Int32(5),
                PreTag:            proto.String("<b>"),
                PostTag:           proto.String("</b>"),
            },
        },
    }
    searchQuery.SetHighlight(highlight)
    searchQuery.SetGetTotalCount(true)
    searchQuery.SetOffset(0) // Set the Offset parameter to 0. 
    searchQuery.SetLimit(20) // Set the Limit parameter to 20, which specifies that up to 20 rows can be returned. 
    searchRequest.SetSearchQuery(searchQuery)
    // Specify that all fields in the search index are returned. 
    searchRequest.SetColumnsToGet(&tablestore.ColumnsToGet{
        ReturnAllFromIndex: true,
    })

    if resp, err := client.Search(searchRequest); err != nil {
        fmt.Println("Highlighting query failed with err: ", err)
    } else {
        fmt.Println("RequestId: " + resp.RequestId)
        // Display the highlighted query results. When you query a non-Nested field, you can set the padding parameter to null. 
        printSearchHit(resp.SearchHits, " ")
    }
    fmt.Println("highlight query finished")
}

/**
 * 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. 
 */
func printSearchHit(searchHits []*tablestore.SearchHit, padding string) {
    for _, searchHit := range searchHits {
        if searchHit.Score != nil {
            fmt.Printf("%sScore: %f\n", padding, *searchHit.Score)
        }

        if searchHit.Row != nil {
            jsonBody, err := json.Marshal(*searchHit.Row)
            if err != nil {
                panic(err)
            }
            fmt.Println("Row: ", string(jsonBody))
        }

        if searchHit.HighlightResultItem != nil && len(searchHit.HighlightResultItem.HighlightFields) != 0 {
            fmt.Printf("%sHighlight: \n", padding)
            for colName, highlightResult := range searchHit.HighlightResultItem.HighlightFields {
                fmt.Printf("%sColumnName: %s, Highlight_Fragments: %v\n", padding+padding, colName, highlightResult.Fragments)
            }
        }

        fmt.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.