azuregoazure-cosmosdbazure-cosmosdb-sqlapi

Query all documents in Azure CosmosDB for NoSQL


I am trying to get all documents in a collection in CosmosDB for NoSQL in Azure using Golang but I get null value when trying to do a HTTP GET call to the database.

When I try to pass a specific value from the document which is the partitionkey value in the NewPartitionKeyFromString method. But I need to fetch all the records present in that container similar to fetchAll records for other relational databases.

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)
    }

}

Please Note: I have recently started learning golang. Any type of suggestions are welcomed


Solution

  • Based on the comments, partitionKeyValue := azcosmos.NewPartitionKeyString("assetType") should be the value of the property.

    For example, if your documents look like:

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

    Then it should be partitionKeyValue := azcosmos.NewPartitionKeyString("car")

    The Go SDK does not support cross-partition queries at this time, so you can only query within a logical partition value. You cannot get all the documents for all the partitions.