JSON 查询

更新时间:
复制 MD 格式

使用 Tablestore Go SDK 查询多元索引中的 JSON Object 或 JSON Nested 字段。

前提条件

开始前,完成以下准备工作:

功能说明

JSON 字段支持 Object 和 Nested 两种索引方式。Object 不保留数组中各子对象的边界,多个查询条件可以由不同子对象分别满足;Nested 将数组中的每个对象作为独立子行查询,能够保证多个条件在同一数组元素内匹配。

JSON 索引类型

查询方式

JsonType_OBJECT

不保留数组子对象边界。使用子字段完整路径执行普通查询,例如 profile.city

JsonType_NESTED

保留同一子对象内各字段的对应关系。使用 NestedQuery 查询数组中的对象。

说明

JSON 字段的 SubFieldSchemas 不支持 Vector 类型子字段。

查询 Object 字段

tableName := "example_table"
indexName := "example_index"

query := &search.TermQuery{FieldName: "profile.city", Term: "hangzhou"}
searchQuery := search.NewSearchQuery().
    SetQuery(query).
    SetLimit(10).
    SetGetTotalCount(true)

response, err := client.Search(&tablestore.SearchRequest{
    TableName:   tableName,
    IndexName:   indexName,
    SearchQuery: searchQuery,
    ColumnsToGet: &tablestore.ColumnsToGet{
        ReturnAllFromIndex: true,
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(response.TotalCount)
fmt.Println(response.Rows)

查询 Nested 字段

tableName := "example_table"
indexName := "example_index"

query := &search.NestedQuery{Path: "orders", Query: &search.TermQuery{FieldName: "orders.product", Term: "book"}, ScoreMode: search.ScoreMode_None}
searchQuery := search.NewSearchQuery().
    SetQuery(query).
    SetLimit(10).
    SetGetTotalCount(true)

response, err := client.Search(&tablestore.SearchRequest{
    TableName:   tableName,
    IndexName:   indexName,
    SearchQuery: searchQuery,
    ColumnsToGet: &tablestore.ColumnsToGet{
        ReturnAllFromIndex: true,
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(response.TotalCount)
fmt.Println(response.Rows)

参数说明

Object 字段使用具体查询类型的参数;Nested 字段使用 search.NestedQuery。通用查询配置请参见精确查询,NestedQuery 参数请参见嵌套类型查询

Object 字段查询

名称

类型

说明

FieldName(必选)

string

JSON 子字段的完整路径,例如 profile.city

查询值(必选)

interface{}

具体名称和类型取决于使用的查询类型。

Nested 字段查询

名称

类型

说明

Path(必选)

string

JsonType_NESTED 字段路径。

Query(必选)

search.Query

对子字段执行的查询条件。

ScoreMode(可选)

search.ScoreMode

子查询评分合并方式。