Todos os produtos
Search
Central de documentação

Tablestore:Consulta aninhada

Última atualização: Jul 03, 2026

Use uma consulta aninhada para consultar dados nos subcampos de campos Nested. Não é possível consultar campos Nested diretamente. Para consultar um campo Nested, especifique o caminho do campo e uma subconsulta em um objeto NestedQuery. A subconsulta pode ser de qualquer tipo.

Pré-requisitos

Parâmetros

Parâmetro

Descrição

TableName

Nome da tabela de dados.

IndexName

Nome do índice de pesquisa.

Path

Caminho do campo Nested. Esse campo usa uma estrutura de árvore. Por exemplo, news.title especifica o subcampo title no campo Nested chamado news.

Query

Consulta aplicada ao subcampo dentro do campo Nested. Pode ser de qualquer tipo.

ScoreMode

Valor usado para calcular a pontuação quando um campo contém vários valores.

InnerHits

Configurações dos subcampos no campo Nested.

  • Sort: regra de ordenação dos subcampos no campo Nested.

  • Offset: primeiro subcampo retornado quando o campo Nested tem vários subcampos.

  • Limit: número máximo de subcampos retornados quando o campo Nested tem vários subcampos. Valor padrão: 3.

  • highlight: define se o recurso de destaque deve ser ativado para os subcampos no campo Nested. Para mais informações, consulte Resumos e destaque.

Exemplos

Campos Nested de nível único

O código de exemplo a seguir mostra como consultar linhas nas quais o valor do campo col_nested.nested_1 é tablestore. Neste exemplo, o campo Nested chamado col_nested consiste nos seguintes subcampos: nested_1 e nested_2.

func NestedQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.NestedQuery{ // Set the query type to NestedQuery. 
        Path: "col_nested", // Specify the path of the Nested field. 
        Query: &search.TermQuery{ // Construct a subquery for the nested query. 
            FieldName: "col_nested.nested_1", // Specify the name of the field that you want to query. The field name must contain the col_nested prefix. 
            Term:      "tablestore",          // Specify the keyword that is used to match the value of the field. 
        },
        ScoreMode: search.ScoreMode_Avg,
    }
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    searchRequest.SetSearchQuery(searchQuery)
    // Specify that all fields are returned. 
    searchRequest.SetColumnsToGet(&tablestore.ColumnsToGet{
        ReturnAll: true,
    })
    searchResponse, err := client.Search(searchRequest)
    if err != nil {
        fmt.Printf("%#v", err)
        return
    }
    fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) // Check whether all rows that meet the query conditions are returned. 
    fmt.Println("RowCount: ", len(searchResponse.Rows))
    for _, row := range searchResponse.Rows {
        jsonBody, err := json.Marshal(row)
        if err != nil {
            panic(err)
        }
        fmt.Println("Row: ", string(jsonBody))
    }
}

Campos Nested com o recurso de destaque ativado

O código de exemplo a seguir demonstra como consultar linhas onde o valor do campo col_nested.nested_1 é tablestore e destacar as palavras-chave nos resultados da consulta. Neste exemplo, o campo Nested chamado col_nested consiste nos seguintes subcampos: nested_1 e nested_2.

func NestedQueryWithHighlight(client *tablestore.TableStoreClient, tableName string, indexName string) {
	searchRequest := &tablestore.SearchRequest{}
	searchRequest.SetTableName(tableName)
	searchRequest.SetIndexName(indexName)
	query := &search.NestedQuery{ // Set the query type to NestedQuery. 
		Path: "col_nested", // Specify the path of the Nested field. 
		Query: &search.TermQuery{ // Construct a subquery for the nested query. 
			FieldName: "col_nested.nested_1", // Specify the name of the field that you want to query. The field name must contain the col_nested prefix. 
			Term:      "tablestore",          // Specify the value that you want to match. 
		},
		ScoreMode: search.ScoreMode_Avg,
		InnerHits: &search.InnerHits{
			Offset: proto.Int32(0),
			Limit:  proto.Int32(3),
			Highlight: &search.Highlight{
				FieldHighlightParameters: map[string]*search.HighlightParameter{
					"col_nested.nested_1": {
						NumberOfFragments: proto.Int32(5),
						PreTag:            proto.String("<em>"),
						PostTag:           proto.String("</em>"),
					},
				},
			},
		},
	}
	searchQuery := search.NewSearchQuery()
	searchQuery.SetQuery(query)
	searchRequest.SetSearchQuery(searchQuery)
	// Specify that all fields 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 results. 
		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.NestedDocOffset != nil {
			fmt.Printf("%sOffset: %d\n", padding, *searchHit.NestedDocOffset)
		}

		if searchHit.Row != nil {
			fmt.Printf("%sRow: %v\n", padding, *searchHit.Row)
		}

		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)
			}
		}

		if searchHit.SearchInnerHits != nil && len(searchHit.SearchInnerHits) != 0 {
			fmt.Printf("%sInnerHits: \n", padding)
			for path, innerSearchHit := range searchHit.SearchInnerHits {
				fmt.Printf("%sPath: %s\n", padding+padding, path)
				fmt.Printf("%sSearchHit: \n", padding+padding)
				printSearchHit(innerSearchHit.SearchHits, padding+padding)
			}
		}

		fmt.Println("")
	}
}

Perguntas frequentes

Referências