全部產品
Search
文件中心

:巢狀型別查詢

更新時間:Sep 13, 2024

NestedQuery用於查詢巢狀型別欄位中子行的資料。巢狀型別不能直接查詢,需要通過NestedQuery封裝,NestedQuery中需要指定巢狀型別欄位的路徑和一個子查詢,其中子查詢可以是任意Query類型。

前提條件

參數

參數

說明

TableName

資料表名稱。

IndexName

多元索引名稱。

Path

路徑名,巢狀型別的列的樹狀路徑。例如news.title表示巢狀型別的news列中的title子列。

Query

巢狀型別的列中子列上的查詢,子列上的查詢可以是任意Query類型。

ScoreMode

當列存在多個值時基於哪個值計算分數。

InnerHits

巢狀型別欄位的子列的配置參數。包括如下配置項:

  • Sort:Nested子列返回時的定序。

  • Offset:當Nested列包含多個子行時,子行返回的起始位置。

  • Limit:當Nested列包含多個子行時,返回子行的數量。預設值為3。

  • Highlight:Nested子列高亮參數配置。具體參數配置說明請參見查詢高亮

樣本

單層級巢狀型別查詢樣本

以下樣本用於查詢col_nested.nested_1為tablestore的資料。其中col_nested為巢狀型別欄位,子行中包含nested_1和nested_2兩列。

func NestedQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.NestedQuery{ //設定查詢類型為NestedQuery。
        Path: "col_nested", //設定巢狀型別欄位的路徑。
        Query: &search.TermQuery{ //構造NestedQuery的子查詢。
            FieldName: "col_nested.nested_1", //設定欄位名,注意帶有Nested列的首碼。
            Term:      "tablestore",          //設定要查詢的值。
        },
        ScoreMode: search.ScoreMode_Avg,
    }
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    searchRequest.SetSearchQuery(searchQuery)
    //設定為返回所有列。
    searchRequest.SetColumnsToGet(&tablestore.ColumnsToGet{
        ReturnAll: true,
    })
    searchResponse, err := client.Search(searchRequest)
    if err != nil {
        fmt.Printf("%#v", err)
        return
    }
    fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) //查看返回結果是否完整。
    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))
    }
}

巢狀型別查詢使用查詢高亮樣本

以下樣本用於查詢表中col_nested巢狀型別欄位中nested_1子列的值能夠匹配tablestore的資料,並在返回結果中對關鍵詞進行高亮顯示。其中col_nested巢狀型別欄位的子行中包含nested_1和nested_2兩列。

func NestedQueryWithHighlight(client *tablestore.TableStoreClient, tableName string, indexName string) {
	searchRequest := &tablestore.SearchRequest{}
	searchRequest.SetTableName(tableName)
	searchRequest.SetIndexName(indexName)
	query := &search.NestedQuery{ //設定查詢類型為NestedQuery。
		Path: "col_nested", //設定巢狀型別欄位的路徑。
		Query: &search.TermQuery{ //構造NestedQuery的子查詢。
			FieldName: "col_nested.nested_1",       //設定欄位名,注意帶有Nested列的首碼。
			Term:      "tablestore", //設定要查詢的值。
		},
		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)
	//設定為返回所有列。
	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)
                // 列印高亮結果。
		printSearchHit(resp.SearchHits, " ")
	}
	fmt.Println("highlight query finished")
}


/**
 * 列印searchHit內容。
 * @param searchHits searchHits
 * @param padding Nested結構輸出時,增加首碼以列印層次資訊。
 */
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("")
	}
}

常見問題

相關文檔