Este tema describe cómo utilizar el método Bucket.SelectObject para consultar archivos CSV y JSON.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra la creación de una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para consultar objetos, debe contar con el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.Solo es posible consultar objetos en formatos CSV y JSON mediante SelectObject.
Código de ejemplo
Consultar un objeto CSV
A continuación se proporciona un ejemplo de código para consultar un archivo CSV.
package main
import (
"io"
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error getting credentials: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Specify the bucket name. For example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Error getting bucket: %v", err)
}
// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampledata.csv.
objectKey := "exampledir/exampledata.csv"
// Specify the full path of the local CSV file. For example, D:\\localpath\\exampledata.csv.
localCsvFile := "D:\\localpath\\exampledata.csv"
// Upload the local file to OSS.
if err := bucket.PutObjectFromFile(objectKey, localCsvFile); err != nil {
log.Fatalf("Error uploading file: %v", err)
}
// Use a SELECT statement to query data from the file.
selectRequest := oss.SelectRequest{
Expression: `select * from ossobject`,
}
// Execute the SELECT request.
body, err := bucket.SelectObject(objectKey, selectRequest)
if err != nil {
log.Fatalf("Error selecting object: %v", err)
}
defer body.Close()
// Read the content.
content, err := io.ReadAll(body)
if err != nil {
log.Fatalf("Error reading content: %v", err)
}
// Print the result.
log.Printf("Selected content: %s", string(content))
}
Consultar un objeto JSON
A continuación se proporciona un ejemplo de código para consultar un archivo JSON.
package main
import (
"io"
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error getting credentials: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Specify the bucket name. For example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Error getting bucket: %v", err)
}
// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampledata.json.
objectKey := "exampledir/exampledata.json"
// Specify the full path of the local JSON file. For example, D:\\localpath\\exampledata.json.
localJsonFile := "D:\\localpath\\exampledata.json"
// Upload the local file to OSS.
if err := bucket.PutObjectFromFile(objectKey, localJsonFile); err != nil {
log.Fatalf("Error uploading file: %v", err)
}
// Use a SELECT statement to query data from the file.
selectRequest := oss.SelectRequest{
Expression: `select * from ossobject`,
}
// Execute the SELECT request.
body, err := bucket.SelectObject(objectKey, selectRequest)
if err != nil {
log.Fatalf("Error selecting object: %v", err)
}
defer body.Close()
// Read the content.
content, err := io.ReadAll(body)
if err != nil {
log.Fatalf("Error reading content: %v", err)
}
// Print the result.
log.Printf("Selected content: %s", string(content))
}
Referencias
Para ver el código de ejemplo completo sobre la consulta de archivos, consulte el ejemplo en GitHub.
Para obtener más información sobre la operación de API para consultar archivos, consulte SelectObject.