本文主要为您介绍如何使用TermQuery及TermsQuery接口进行精确查询。

TermQuery

TermQuery采用完整精确匹配的方式查询表中的数据,但是对于分词字符串类型,只要分词后有词条可以精确匹配即可。比如某个分词字符串类型的字段,值为“tablestore is cool”,假设分词后为“tablestore”、“is”、“cool”三个词条,则查询“tablestore”、“is”、“cool”时都满足查询条件。

/**
 * 查询表中Col_Keyword这一列精确匹配"hangzhou"的数据。
 */
func TermQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.TermQuery{} // 设置查询类型为TermQuery
    query.FieldName = "Col_Keyword" // 设置要匹配的字段
    query.Term = "hangzhou" // 设置要匹配的值
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    searchQuery.SetGetTotalCount(true)
    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("TotalCount: ", searchResponse.TotalCount) // 匹配的总行数
    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))
    }
}

TermsQuery

多字段精确查询。类似于TermQuery,TermsQuery支持设置多个Term,查询匹配这些Term的数据。

/**
 * 查询表中Col_Keyword这一列精确匹配"hangzhou"或"tablestore"的数据。
 */
func TermsQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.TermsQuery{}   // 设置查询类型为TermQuery
    query.FieldName = "Col_Keyword" // 设置要匹配的字段
    terms := make([]interface{}, 0)
    terms = append(terms, "hangzhou")
    terms = append(terms, "tablestore")
    query.Terms = terms // 设置要匹配的值
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    searchQuery.SetLimit(100)
    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))
    }
}