Summaries and highlighting

更新时间:
复制 MD 格式

When you query data, you can set highlighting parameters to return text snippets that contain the search query and highlight the query. The summary and highlighting feature is supported only for Text type fields.

Prerequisites

Notes

  • When you use the summary and highlighting feature with a MatchQuery or MatchPhraseQuery, the matched terms may be highlighted by multiple pre-tags and post-tags.

  • If the tokenizer type for the Text field is maximum semantic tokenization, the summary and highlighting feature is not supported when you use a MatchPhraseQuery to query data.

  • Fragment splitting may divide a matched term in the text. In this case, the term may not be highlighted.

Parameters

Parameter

Description

HighlightEncoder

The encoding method for the original content of the highlighted fragment. Valid values are:

  • PLAIN (default): The original text is displayed without encoding.

  • HTML: The original content of the highlighted fragment is HTML-escaped. Escaping includes converting < to &lt;, > to &gt;, " to &quot;, ' to &#x27;, and / to &#x2F;. The HTML format is recommended for web display.

FieldHighlightParams

Field highlighting parameters. You can set these parameters only for fields that are part of a keyword query in SearchQuery.

HighlightParameter

NumberOfFragments

The maximum number of highlighted fragments to return. Set this to 1.

FragmentSize

The length of each fragment. The default value is 100.

Important

The actual length of the returned fragment is not strictly equal to this value.

PreTag

The prefix tag for highlighting search queries, such as <em> or <b>. The default value is <em>. You can customize the prefix tag as needed. The supported character set for preTag includes < > " ' /, a-z, A-Z, and 0-9.

PostTag

The postfix tag for highlighting search queries, such as </em> or </b>. The default value is </em>. You can customize the postfix tag as needed. The supported character set for postTag includes < > " ' /, a-z, A-Z, and 0-9.

HighlightFragmentOrder

The sorting rule for fragments when a highlighted field returns multiple fragments.

  • TEXT_SEQUENCE (default): The order in which the fragments appear in the text.

  • SCORE: Sorts the fragments based on the score of the hit search query.

Example

The following example shows how to use MatchQuery to find data where the Col_Text column matches hangzhou shanghai and how to highlight the search query in the results. The Col_Text column is a 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"   // Set the column to match.
    query.Text = "hangzhou shanghai"     // Set the value 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(""),
                PostTag:           proto.String(""),
            },
        },
    }
    searchQuery.SetHighlight(highlight)
    searchQuery.SetGetTotalCount(true)
    searchQuery.SetOffset(0) // Set offset to 0.
    searchQuery.SetLimit(20) // Set limit to 20 to return a maximum of 20 rows.
    searchRequest.SetSearchQuery(searchQuery)
    // Set to return all columns from the search index.
    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)
        // Print the query and highlight results. Set padding to empty when you query non-nested fields.
        printSearchHit(resp.SearchHits, " ")
    }
    fmt.Println("highlight query finished")
}

/**
 * Prints the content of searchHit.
 * @param searchHits The search hits.
 * @param padding When printing a nested structure, add a prefix to show the hierarchy.
 */
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