Todos los productos
Search
Centro de documentos

Object Storage Service:Query objects

Última actualización: Sep 22, 2026

La API SelectObject le permite ejecutar instrucciones SQL en objetos y recuperar los resultados.

Contexto

Hadoop 3.0 admite la ejecución de servicios como Spark, Hive y Presto en E-MapReduce (EMR) para procesar datos almacenados en Object Storage Service (OSS). Otros servicios de Alibaba Cloud, como MaxCompute y Data Lake Analytics (DLA), también permiten procesar datos directamente desde OSS.

Tradicionalmente, las plataformas de big data usan la API GetObject para descargar objetos completos desde OSS antes de filtrarlos y analizarlos.

La API SelectObject resuelve este problema al delegar la lógica de consulta, como proyecciones y filtros, a la capa de OSS. Así se recupera únicamente el subconjunto de datos necesario, lo que reduce la transferencia de información, disminuye los costos y ahorra CPU y memoria en el cliente. Esta eficiencia hace que el análisis de datos en OSS resulte mucho más atractivo.

Facturación

Cuando utiliza la API SelectObject para consultar datos, se le cobra según la cantidad real de datos analizados del objeto de origen. Para obtener más información, consulte Data processing fees.

Formatos de objeto compatibles

La API SelectObject admite formatos de objeto y sintaxis SQL específicos.

  • Objetos CSV que cumplen con RFC 4180. Esto incluye objetos similares a CSV, como TSV. Es posible especificar delimitadores de fila, delimitadores de columna y caracteres de comillas personalizados.

  • Objetos JSON codificados en UTF-8. Se admiten dos formatos: DOCUMENT y LINES.

    • DOCUMENT: todo el objeto constituye un único objeto JSON válido.

    • LINES: el objeto consta de varias líneas, donde cada una es un objeto JSON independiente. Las líneas se separan mediante un carácter de nueva línea, como \n o \r\n. No es necesario especificar el delimitador; sin embargo, el objeto completo no representa un objeto JSON válido.

  • Objetos en las clases de almacenamiento Standard e Infrequent Access. Los objetos de las clases Archive, Cold Archive o Deep Cold Archive deben restaurarse antes de consultarlos.

  • Objetos cifrados mediante cifrado del lado del servidor con claves administradas por OSS o con una CMK administrada por KMS.

Sintaxis SQL compatible

  • Cláusulas SQL: SELECT, FROM, WHERE

  • Tipos de datos: string, int (64 bits), double (64 bits), decimal (128 bits), timestamp y bool

  • Operadores: lógicos (AND, OR, NOT), aritméticos (+, -, *, /, %), de comparación (>, =, <, >=, <=, !=) y de cadena (LIKE, ||)

    Importante

    El operador LIKE realiza coincidencias de patrones con distinción entre mayúsculas y minúsculas.

Tipos de datos compatibles

De forma predeterminada, todos los datos de un objeto CSV se tratan como cadenas. Utilice la función CAST para realizar conversiones de tipo explícitas.

A continuación se muestra cómo usar una consulta SQL para convertir los valores de las columnas _1 y _2 a enteros:Select * from OSSOBject where cast (_1 as int) > cast(_2 as int)

La API SelectObject también admite la conversión implícita de tipos en una cláusula WHERE. Por ejemplo, en la siguiente instrucción, los valores de la primera y segunda columna se convierten implícitamente a enteros:

Select _1 from ossobject where _1 + _2 > 100

En los objetos JSON, si no utiliza la función CAST, el tipo de dato se determina según el contenido del objeto. Los tipos de datos JSON integrados estándar incluyen null, bool, int64, double y string.

Ejemplos de SQL

Esta sección proporciona ejemplos de SQL para objetos CSV y JSON.

  • CSV

    Caso de uso

    Instrucción SQL

    Devuelve las primeras 10 filas de datos.

    select * from ossobject limit 10

    Devuelve los enteros de la primera y tercera columna cuando el valor de la primera columna es mayor que el de la tercera.

    select _1, _3 from ossobject where cast(_1 as int) > cast(_3 as int)

    Devuelve el recuento de registros de la primera columna que comienzan con 'Chen'. (Nota: el carácter chino después de 'like' debe estar codificado en UTF-8).

    select count(*) from ossobject where _1 like 'Chen%'

    Devuelve todos los registros cuya marca de tiempo en la segunda columna sea posterior a 2018-08-09 11:30:25 y cuyo valor en la tercera columna supere 200.

    select * from ossobject where _2 > cast('2018-08-09 11:30:25' as timestamp) and _3 > 200

    Calcula el promedio, la suma, el máximo y el mínimo de los números de punto flotante en la segunda columna.

    select AVG(cast(_6 as double)), SUM(cast(_6 as double)), MAX(cast(_6 as double)), MIN(cast(_6 as double)) from ossobject

    Devuelve todos los registros donde la cadena concatenada de la primera y tercera columna comienza con 'Tom' y termina con 'Anderson'.

    select * from ossobject where (_1

    _3) like 'Tom%Anderson'

    Devuelve todos los registros cuyo valor en la primera columna sea divisible entre 3.

    select * from ossobject where (_1 % 3) = 0

    Devuelve todos los registros cuyo valor en la primera columna esté entre 1995 y 2012.

    select * from ossobject where _1 between 1995 and 2012

    Devuelve todos los registros cuyo valor en la quinta columna sea 'N', 'M', 'G' o 'L'.

    select * from ossobject where _5 in ('N', 'M', 'G', 'L')

    Devuelve todos los registros donde el producto de los valores de la segunda y tercera columna sea mayor que la suma de 100 y el valor de la quinta columna.

    select from ossobject where _2 _3 > _5 + 100

  • JSON

    Suponga que tiene el siguiente objeto JSON:

    {
      "contacts":[
    {
      "firstName": "John",
      "lastName": "Smith",
      "isAlive": true,
      "age": 27,
      "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021-3100"
      },
      "phoneNumbers": [
        {
          "type": "home",
          "number": "212 555-1234"
        },
        {
          "type": "office",
          "number": "646 555-4567"
        },
        {
          "type": "mobile",
          "number": "123 456-7890"
        }
      ],
      "children": [],
      "spouse": null
    },... # Additional contact nodes omitted for brevity.
    ]}

    La siguiente tabla muestra ejemplos de SQL.

    Caso de uso

    Instrucción SQL

    Devuelve todos los registros donde el valor de age es 27.

    select from ossobject.contacts[] s where s.age = 27

    Devuelve todos los números telefónicos de casa.

    select s.number from ossobject.contacts[].phoneNumbers[] s where s.type = "home"

    Devuelve todos los registros donde spouse es null.

    select * from ossobject s where s.spouse is null

    Devuelve todos los registros sin hijos.

    select * from ossobject s where s.children[0] is null

    Nota

    No existe una sintaxis específica para representar un arreglo vacío. Utilice la instrucción anterior en su lugar.

Casos de uso

Entre los casos de uso más comunes de SelectObject destacan la consulta paralela de objetos grandes, la consulta de objetos JSON y el análisis de archivos de registro.

  • Consultar objetos grandes en paralelo

    Al igual que la función de descarga multiparte por rango de bytes de la API GetObject, la API SelectObject admite consultas paralelas. Puede dividir los datos de dos maneras:

    • Por fila: es un método habitual para dividir datos. Sin embargo, con datos dispersos, esta división puede generar una carga desequilibrada entre los workers de consulta.

    • Por split: un split es un concepto de OSS para la fragmentación de datos. Contiene varias filas y todos los splits tienen aproximadamente el mismo tamaño.

    Nota

    Dividir los datos por split resulta más eficiente que hacerlo por fila.

    Si confirma que las columnas de su objeto CSV no contienen caracteres de nueva línea, la división por rango de bytes es más sencilla porque no requiere crear metadatos. Si las columnas incluyen caracteres de nueva línea o si consulta un objeto JSON, siga estos pasos:

    1. Llame a la API CreateSelectObjectMeta para obtener el número total de splits del objeto. Para reducir el tiempo de análisis, se recomienda llamar a esta API de forma asíncrona antes de iniciar la consulta.

    2. Determine el grado de paralelismo (n) según los recursos de su cliente. Luego, divida el número total de splits entre n para calcular cuántos splits debe procesar cada consulta paralela.

    3. En el cuerpo de la solicitud, especifique el rango de splits que desea consultar, por ejemplo, split-range=1-20.

    4. Combine los resultados de todas las consultas paralelas.

  • Consultar objetos JSON

    Cuando consulte objetos JSON, limite la ruta JSON en la cláusula FROM para mejorar el rendimiento.

    Considere el siguiente ejemplo de objeto JSON:

    {
      "contacts":[
    {
      "firstName": "John",
      "lastName": "Smith",
      "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021-3100"
      },
      "phoneNumbers": [
        {
          "type": "home",
          "number": "212 555-1234"
        },
        {
          "type": "office",
          "number": "646 555-4567"
        },
        {
          "type": "mobile",
          "number": "123 456-7890"
        }
      ]
    }
    ]}

    Para encontrar todas las direcciones donde el código postal comienza con '10021', puede escribir la instrucción SQL como select s.address.streetAddress from ossobject.contacts[*] s where s.address.postalCode like '10021%' o bien select s.streetAddress from ossobject.contacts[*].address s where s.postalCode like '10021%'.

    La segunda instrucción, select s.streetAddress from ossobject.contacts[*].address s where s.postalCode like '10021%', ofrece un mejor rendimiento porque su ruta JSON es más precisa.

  • Manejar números de punto flotante de alta precisión en objetos JSON

    Cuando necesite realizar cálculos con números de punto flotante de alta precisión en un objeto JSON, se recomienda establecer la opción ParseJsonNumberAsString en true y luego convertir el valor al tipo decimal. Por ejemplo, si un atributo a tiene el valor 123456789.123456789, utilice la instrucción select s.a from ossobject s where cast(s.a as decimal) > 123456789.12345 para conservar la precisión de los datos originales.

Procedimiento

OSS console

Importante

En la consola de OSS, puede extraer un máximo de 40 MB de datos de un objeto cuyo tamaño no supere los 128 MB.

  1. Inicie sesión en la consola de OSS.

  2. En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.

  3. En el panel de navegación izquierdo, elija Object Management > Objects.

  4. Busque el objeto de destino y elija more > Select Content en la columna Actions.

  5. En el panel Select Content, configure los parámetros según las siguientes descripciones.

    Parámetro

    Descripción

    Object Type

    Solo se admiten los tipos de objeto CSV y JSON.

    Delimiter

    Este parámetro solo aplica a objetos CSV. Puede elegir una coma (,) o un delimitador personalizado.

    Title Row

    Este parámetro solo aplica a objetos CSV. Especifique si la primera fila del objeto contiene encabezados de columna.

    JSON Format

    Este parámetro solo aplica a objetos JSON. Seleccione el formato que coincida con su objeto JSON.

    Compression Format

    Especifique si el objeto está comprimido. Solo se admite la compresión GZIP.

  6. Haga clic en Preview.

    Importante

    La vista previa de un objeto en la clase de almacenamiento Standard genera cargos de análisis de SelectObject. Para los objetos en las clases Infrequent Access, Archive, Cold Archive o Deep Cold Archive, la vista previa genera tanto cargos de análisis de SelectObject como cargos de recuperación de datos. Para obtener más información, consulte Data processing fees.

  7. Haga clic en Next, luego introduzca y ejecute una instrucción SQL.

    Suponga que tiene un objeto CSV llamado People con tres columnas: Name, Company y Age.

    • Para encontrar personas mayores de 50 años cuyo nombre comience con 'Lora', ejecute la siguiente instrucción SQL. En ella, _1, _2 y _3 son índices de columna que representan la primera, segunda y tercera columna, respectivamente.

      select * from ossobject where _1 like 'Lora*' and _3 > 50
    • Para contar el número de filas del objeto y obtener las edades máxima y mínima, ejecute la siguiente instrucción SQL:

      select count(*), max(cast(_3 as int)), min(cast(_3 as int)) from ossobject
  8. Consulte los resultados de la ejecución.

    También puede hacer clic en Download para guardar localmente el contenido seleccionado.

OSS SDKs

Puede consultar objetos mediante los SDK de OSS para Java, Python y Go.

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

/**
 * Examples of create select object metadata and select object.
 *
 */
public class SelectObjectSample {
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Specify the name of the bucket. Example: examplebucket. 
    private static String bucketName = "examplebucket";

    public static void main(String[] args) throws Exception {
      
      	// 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 configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        // Specify the full path of the object that you want to query, and then query the data of the object by using SELECT statements. Do not include the bucket name in the full path. 
        // Specify the full path of the CSV object. 
        selectCsvSample("test.csv", ossClient);
        // Specify the full path of the JSON object. 
        selectJsonSample("test.json", ossClient);
        ossClient.shutdown();
    }

    private static void selectCsvSample(String key, OSS ossClient) throws Exception {
        // Specify the content of the object that you want to upload. 
        String content = "name,school,company,age\r\n" +
                "Lora Francis,School A,Staples Inc,27\r\n" +
                "Eleanor Little,School B,\"Conectiv, Inc\",43\r\n" +
                "Rosie Hughes,School C,Western Gas Resources Inc,44\r\n" +
                "Lawrence Ross,School D,MetLife Inc.,24";

        ossClient.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

        SelectObjectMetadata selectObjectMetadata = ossClient.createSelectObjectMetadata(
                new CreateSelectObjectMetadataRequest(bucketName, key)
                        .withInputSerialization(
                                new InputSerialization().withCsvInputFormat(
                                        // Specify the delimiter that is used to separate different records in the content. Example: \r\n. 
                                        new CSVFormat().withHeaderInfo(CSVFormat.Header.Use).withRecordDelimiter("\r\n"))));
        System.out.println(selectObjectMetadata.getCsvObjectMetadata().getTotalLines());
        System.out.println(selectObjectMetadata.getCsvObjectMetadata().getSplits());

        SelectObjectRequest selectObjectRequest =
                new SelectObjectRequest(bucketName, key)
                        .withInputSerialization(
                                new InputSerialization().withCsvInputFormat(
                                        new CSVFormat().withHeaderInfo(CSVFormat.Header.Use).withRecordDelimiter("\r\n")))
                        .withOutputSerialization(new OutputSerialization().withCsvOutputFormat(new CSVFormat()));
        // Use a SELECT statement to query all records whose values are greater than 40 in the 4th column. 
        selectObjectRequest.setExpression("select * from ossobject where _4 > 40");
        OSSObject ossObject = ossClient.selectObject(selectObjectRequest);

        // Read the content of the object. 
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }
        reader.close();

        ossClient.deleteObject(bucketName, key);
    }

    private static void selectJsonSample(String key, OSS ossClient) throws Exception {
        // Specify the content of the object that you want to upload. 
        final String content = "{\n" +
                "\t\"name\": \"Lora Francis\",\n" +
                "\t\"age\": 27,\n" +
                "\t\"company\": \"Staples Inc\"\n" +
                "}\n" +
                "{\n" +
                "\t\"name\": \"Eleanor Little\",\n" +
                "\t\"age\": 43,\n" +
                "\t\"company\": \"Conectiv, Inc\"\n" +
                "}\n" +
                "{\n" +
                "\t\"name\": \"Rosie Hughes\",\n" +
                "\t\"age\": 44,\n" +
                "\t\"company\": \"Western Gas Resources Inc\"\n" +
                "}\n" +
                "{\n" +
                "\t\"name\": \"Lawrence Ross\",\n" +
                "\t\"age\": 24,\n" +
                "\t\"company\": \"MetLife Inc.\"\n" +
                "}";

        ossClient.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

        SelectObjectRequest selectObjectRequest =
                new SelectObjectRequest(bucketName, key)
                        .withInputSerialization(new InputSerialization()
                                .withCompressionType(CompressionType.NONE)
                                .withJsonInputFormat(new JsonFormat().withJsonType(JsonType.LINES)))
                        .withOutputSerialization(new OutputSerialization()
                                .withCrcEnabled(true)
                                .withJsonOutputFormat(new JsonFormat()))
                        .withExpression("select * from ossobject as s where s.age > 40"); // Use the SELECT statement to query data in the object. 

        OSSObject ossObject = ossClient.selectObject(selectObjectRequest);

        // Read the content of the object. 
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }
        reader.close();

        ossClient.deleteObject(bucketName, key);
    }
}
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def select_call_back(consumed_bytes, total_bytes =  None):
        print('Consumed Bytes:' + str(consumed_bytes) + '\n')

# 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 configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

key ='python_select.csv'
content ='Tom Hanks,USA,45\r\n'*1024
filename ='python_select.csv'

# Upload a CSV file. 
bucket.put_object(key, content)
# Configure the parameters for the SelectObject operation. 
csv_meta_params = {'RecordDelimiter': '\r\n'}
select_csv_params = {'CsvHeaderInfo': 'None',
                    'RecordDelimiter': '\r\n',
                    'LineRange': (500, 1000)}

csv_header = bucket.create_select_object_meta(key, csv_meta_params)
print(csv_header.rows)
print(csv_header.splits)
result = bucket.select_object(key, "select * from ossobject where _3 > 44", select_call_back, select_csv_params)
select_content = result.read()
print(select_content)

result = bucket.select_object_to_file(key, filename,
      "select * from ossobject where _3 > 44", select_call_back, select_csv_params)
bucket.delete_object(key)

###JSON DOCUMENT
key =  'python_select.json'
content =  "{\"contacts\":[{\"key1\":1,\"key2\":\"hello world1\"},{\"key1\":2,\"key2\":\"hello world2\"}]}"
filename =  'python_select.json'
# Upload a JSON DOCUMENT object. 
bucket.put_object(key, content)
select_json_params = {'Json_Type': 'DOCUMENT'}
result = bucket.select_object(key, "select s.key2 from ossobject.contacts[*] s where s.key1 = 1", None, select_json_params)
select_content = result.read()
print(select_content)

result = bucket.select_object_to_file(key, filename,
      "select s.key2 from ossobject.contacts[*] s where s.key1 = 1", None, select_json_params)
bucket.delete_object(key)

###JSON LINES
key =  'python_select_lines.json'
content =  "{\"key1\":1,\"key2\":\"hello world1\"}\n{\"key1\":2,\"key2\":\"hello world2\"}"
filename =  'python_select.json'
# Upload a JSON LINES object. 
bucket.put_object(key, content)
select_json_params = {'Json_Type': 'LINES'}
json_header = bucket.create_select_object_meta(key,select_json_params)
print(json_header.rows)
print(json_header.splits)

result = bucket.select_object(key, "select s.key2 from ossobject s where s.key1 = 1", None, select_json_params)
select_content =  result.read()
print(select_content)
result = bucket.select_object_to_file(key, filename,
           "select s.key2 from ossobject s where s.key1 = 1", None, select_json_params)
bucket.delete_object(key)
package main

import (
	"context"
	"flag"
	"io"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to select an object.
	request := &oss.SelectObjectRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		Key:    oss.Ptr(objectName), // The object name.
		SelectRequest: &oss.SelectRequest{
			Expression: oss.Ptr("select * from ossobject limit 10"), // Define an SQL expression to query the first 10 rows of data in the object.
			InputSerializationSelect: oss.InputSerializationSelect{
				CsvBodyInput: &oss.CSVSelectInput{
					FileHeaderInfo: oss.Ptr("Use"),
				},
			},
			OutputSerializationSelect: oss.OutputSerializationSelect{
				OutputHeader: oss.Ptr(true),
			},
		},
	}

	// Execute the request to select the object.
	result, err := client.SelectObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to select object %v", err)
	}

	content, err := io.ReadAll(result.Body)
	if err != nil {
		log.Fatalf("failed to read object %v", err)
	}

	// Print the result of selecting the object.
	log.Printf("select object result:%#v\n", string(content))
}

ossutil CLI

Puede utilizar la herramienta de línea de comandos ossutil para consultar objetos. Para obtener instrucciones de instalación, consulte Install ossutil.

El siguiente comando ejecuta una instrucción SQL en el objeto llamado exampleobject dentro del bucket examplebucket. La solicitud usa sintaxis CSV.

ossutil api select-object --bucket examplebucket --key exampleobject --select-request "{\"Expression\":\"c2VsZWN0IFllYXIsU3RhdGVBYmJyLCBDaXR5TmFtZSwgU2hvcnRfUXVlc3Rpb25fVGV4dCBmcm9tIG9zc29iamVjdA==\",\"InputSerialization\":{\"CSV\":{\"FileHeaderInfo\":\"Use\",\"Range\":\"line-range=0-100\"}},\"OutputSerialization\":{\"JSON\":{\"RecordDelimiter\":\",\"}}}"

Para obtener más información sobre este comando, consulte select-object.

Referencia de API

Las operaciones descritas anteriormente se basan en la API subyacente SelectObject. Si tiene requisitos avanzados, puede enviar solicitudes directas a la API REST. Cuando envíe solicitudes directas, deberá calcular manualmente la firma de autenticación. Para obtener más información, consulte SelectObject.