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
Instância OTSClient inicializada. Para mais informações, consulte Inicializar uma instância OTSClient.
Tabela de dados criada e preenchida. Para mais informações, consulte Criar uma tabela de dados e Gravar dados.
Índice de pesquisa criado para a tabela de dados. Para mais informações, consulte Criar índices de pesquisa.
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.
|
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
-
Ao usar um índice de pesquisa para consultar dados, utilize os seguintes métodos: consulta de termo, consulta de termos, consulta match all, consulta match, consulta match phrase, consulta de prefixo, consulta de intervalo, consulta curinga, consulta geográfica, consulta booleana, consulta vetorial KNN, consulta aninhada e consulta exists. Use esses métodos fornecidos pelo índice de pesquisa para consultar dados de várias dimensões conforme suas necessidades de negócio.
Ordene ou pagine as linhas que atendem às condições de consulta usando os recursos de ordenação e paginação. Para mais informações, consulte Ordenação e paginação.
Use o recurso de colapso (distinto) para agrupar o conjunto de resultados com base em uma coluna específica. Assim, os dados do tipo especificado aparecem apenas uma vez nos resultados da consulta. Para mais informações, consulte Colapso (deduplicação).
Para analisar dados em uma tabela de dados, use o recurso de agregação da operação Search ou execute instruções SQL. Por exemplo, obtenha valores mínimos e máximos, soma e número total de linhas. Para mais informações, consulte Agregação e Consulta SQL.
Caso precise obter todas as linhas que atendem às condições de consulta sem ordená-las, chame as operações ParallelScan e ComputeSplits para usar o recurso de varredura paralela. Para mais informações, consulte Executar uma varredura paralela.