查询 Azure CosmosDB for NoSQL 中的所有文档

问题描述 投票:0回答:1

我正在尝试使用 Golang 获取 Azure 中 NoSQL 的 CosmosDB 集合中的所有文档,但在尝试对数据库进行 HTTP GET 调用时得到 null 值。

当我尝试从文档传递特定值时,该值是 NewPartitionKeyFromString 方法中的分区键值。但我需要获取该容器中存在的所有记录,类似于其他关系数据库的 fetchAll 记录。

func GetAssets(w http.ResponseWriter, r *http.Request) {
    query := "SELECT * FROM c"
    containerClient, err := getContainerClient(database, container)
    if err != nil {
        http.Error(w, "Failed to get container client", http.StatusInternalServerError)
        return
    }

    queryOptions := &azcosmos.QueryOptions{}
    partitionKeyValue := azcosmos.NewPartitionKeyString("assetType")
    pager := containerClient.NewQueryItemsPager(query, partitionKeyValue, queryOptions)

    var assets []models.Asset
    for pager.More() {
        page, err := pager.NextPage(context.TODO())

        if err != nil {
            log.Printf("Failed to execute query: %v", err)
            http.Error(w, "Failed to execute query", http.StatusInternalServerError)
            return
        }

        // Check if items exist in the page
        if len(page.Items) == 0 {
            log.Println("No items found in this page.")
            continue // Skip to the next page if no items found
        }

        for _, item := range page.Items {
            var asset models.Asset // Declare asset as the defined struct
            if err := json.Unmarshal(item, &asset); err != nil {
                log.Printf("Failed to unmarshal item: %v", err)
                http.Error(w, "Failed to unmarshal item", http.StatusInternalServerError)
                return
            }
            assets = append(assets, asset)
        }
    }

    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(assets); err != nil {
        log.Printf("Failed to encode response: %v", err)
        http.Error(w, "Failed to encode response", http.StatusInternalServerError)
    }

}

请注意:我最近开始学习golang。欢迎任何类型的建议

azure go azure-cosmosdb azure-cosmosdb-sqlapi
1个回答
0
投票

根据评论,

 partitionKeyValue := azcosmos.NewPartitionKeyString("assetType")
应该是属性的值。

例如,如果您的文档如下所示:

{
  "id": "the id",
  "assetType": "car"
}

那么应该是

 partitionKeyValue := azcosmos.NewPartitionKeyString("car")

© www.soinside.com 2019 - 2024. All rights reserved.