You can perform a nested query to query the data in the subfields of Nested fields. Nested fields cannot be directly queried. To query a Nested field, you must specify the path of the Nested field and a subquery in a NestedQuery object. The subquery can be any type of query.
Prerequisites
An OTSClient instance is initialized. For more information, see Initialize an OTSClient instance.
A data table is created and data is written to the data table. For more information, see Create a data table and Write data.
A search index is created for the data table. For more information, see Create search indexes.
Parameters
Parameter | Description |
TableName | The name of the data table. |
IndexName | The name of the search index. |
Path | The path of the Nested field. The Nested field uses a tree structure. For example, news.title specifies the title subfield in the Nested field named news. |
Query | The query on the subfield in the Nested field. The query can be of any type. |
ScoreMode | The value that is used to calculate the score when a field contains multiple values. |
InnerHits | The settings of the subfields in the Nested field.
|
Examples
Single-level Nested fields
The following sample code provides an example on how to query the rows in which the value of the col_nested.nested_1 field is tablestore. In this example, the Nested field named col_nested consists of the following subfields: nested_1 and 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))
}
}
Nested fields for which the highlight feature is enabled
The following sample code provides an example on how to query the rows in which the value of the col_nested.nested_1 field is tablestore and highlight the keywords in the query results. In this example, the Nested field named col_nested consists of the following subfields: nested_1 and 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("")
}
}
FAQ
References
When you use a search index to query data, you can use the following query methods: term query, terms query, match all query, match query, match phrase query, prefix query, range query, wildcard query, geo query, Boolean query, KNN vector query, nested query, and exists query. You can use the query methods provided by the search index to query data from multiple dimensions based on your business requirements.
You can sort or paginate rows that meet the query conditions by using the sorting and paging features. For more information, see Sorting and paging.
You can use the collapse (distinct) feature to collapse the result set based on a specific column. This way, data of the specified type appears only once in the query results. For more information, see Collapse (distinct).
If you want to analyze data in a data table, you can use the aggregation feature of the Search operation or execute SQL statements. For example, you can obtain the minimum and maximum values, sum, and total number of rows. For more information, see Aggregation and SQL query.
If you want to obtain all rows that meet the query conditions without the need to sort the rows, you can call the ParallelScan and ComputeSplits operations to use the parallel scan feature. For more information, see Perform a parallel scan.