Todos los productos
Search
Centro de documentos

MaxCompute:Manage tables

Última actualización: Sep 21, 2026

PyODPS proporciona métodos para crear, leer, escribir y gestionar tablas y particiones de MaxCompute. Esta página describe las operaciones comunes con tablas e incluye ejemplos de código ejecutables.

Listar todas las tablas

Llame a list_tables() sobre el objeto de entrada para iterar por todas las tablas de un proyecto.

for table in odps.list_tables():
    # Query all tables in a project.

Comprobar si existe una tabla

Llame a exist_table() sobre el objeto de entrada para comprobar si existe una tabla. Después, use get_table() para recuperar los metadatos de la tabla.

t = odps.get_table('table_name')
t.schema
odps.Schema {
  c_int_a                 bigint
  c_int_b                 bigint
  c_double_a              double
  c_double_b              double
  c_string_a              string
  c_string_b              string
  c_bool_a                boolean
  c_bool_b                boolean
  c_datetime_a            datetime
  c_datetime_b            datetime
}
t.lifecycle
-1
print(t.creation_time)
2014-05-15 14:58:43
t.is_virtual_view
False
t.size
1408
t.schema.columns
[<column c_int_a, type bigint>,
 <column c_int_b, type bigint>,
 <column c_double_a, type double>,
 <column c_double_b, type double>,
 <column c_string_a, type string>,
 <column c_string_b, type string>,
 <column c_bool_a, type boolean>,
 <column c_bool_b, type boolean>,
 <column c_datetime_a, type datetime>,
 <column c_datetime_b, type datetime>]

El objeto de tabla expone las siguientes propiedades:

Property

Description

t.schema

El objeto Schema con las definiciones de columnas

t.lifecycle

El valor del ciclo de vida (-1 indica que no se estableció ningún ciclo de vida)

t.creation_time

La marca de tiempo de creación de la tabla

t.is_virtual_view

Indica si la tabla es una vista virtual

t.size

El tamaño de la tabla en bytes

t.schema.columns

Una lista con todos los objetos de columna

Crear un esquema de tabla

Existen dos enfoques para crear un esquema de tabla.

Definir columnas y particiones de forma explícita

Importe Schema, Column y Partition desde odps.models. Luego, pase las listas de columnas y particiones al constructor de Schema. Este enfoque admite el parámetro comment en cada columna y partición.

from odps.models import Schema, Column, Partition
columns = [
    Column(name='num', type='bigint', comment='the column'),
    Column(name='num2', type='double', comment='the column2'),
]
partitions = [Partition(name='pt', type='string', comment='the partition')]
schema = Schema(columns=columns, partitions=partitions)

Una vez creado el esquema, revise su contenido con estas propiedades:

  • Todas las columnas (incluidas las columnas de clave de partición): Salida:

      print(schema.columns)
      [<column num, type bigint>,
       <column num2, type double>,
       <partition pt, type string>]
  • Solo las columnas de clave de partición: Salida:

      print(schema.partitions)
      [<partition pt, type string>]
  • Nombres de columnas que no son de partición: Salida:

      print(schema.names)
      ['num', 'num2']
  • Tipos de datos de las columnas que no son de partición: Salida:

      print(schema.types)
      [bigint, double]

Usar Schema.from_lists()

Schema.from_lists() es una forma abreviada que acepta listas de nombres y tipos. Este método resulta más sencillo, pero no admite comentarios de columnas ni de particiones de manera directa.

from odps.models import Schema
schema = Schema.from_lists(['num', 'num2'], ['bigint', 'double'], ['pt'], ['string'])
print(schema.columns)

Salida:

[<column num, type bigint>,
 <column num2, type double>,
 <partition pt, type string>]

Crear una tabla

Llame a o.create_table() para crear una tabla. Asegúrese de que todos los tipos de datos de las columnas sean válidos. Dispone de dos opciones: pasar un objeto Schema o pasar las definiciones de columnas como cadenas de texto.

Crear una tabla a partir de un esquema

Primero construya un objeto Schema y luego páselo a create_table().

# Create a table schema.
from odps.models import Schema
schema = Schema.from_lists(['num', 'num2'], ['bigint', 'double'], ['pt'], ['string'])

# Create a table by using the schema that you created.
table = o.create_table('my_new_table', schema)

# Create a table only if no table with the same name exists.
table = o.create_table('my_new_table', schema, if_not_exists=True)

# Configure the lifecycle of the table.
table = o.create_table('my_new_table', schema, lifecycle=7)

Compruebe que la tabla se haya creado correctamente:

print(o.exist_table('my_new_table'))

Si se devuelve True, la tabla se creó correctamente.

Crear una tabla a partir de definiciones de columnas

Pase los nombres y tipos de datos de las columnas como cadena de texto o tupla a create_table().

# Create a partitioned table named my_new_table with specified common columns and partition key columns.
table = o.create_table('my_new_table', ('num bigint, num2 double', 'pt string'), if_not_exists=True)

# Create a non-partitioned table named my_new_table02.
table = o.create_table('my_new_table02', 'num bigint, num2 double', if_not_exists=True)

Compruebe que la tabla se haya creado correctamente:

print(o.exist_table('my_new_table'))

Si se devuelve True, la tabla se creó correctamente.

Habilitar los tipos de datos extendidos de MaxCompute V2.0

De forma predeterminada, create_table() solo admite los tipos de datos BIGINT, DOUBLE, DECIMAL, STRING, DATETIME, BOOLEAN, MAP y ARRAY. Para usar tipos adicionales como TINYINT y STRUCT, establezca options.sql.use_odps2_extension en True.

from odps import options
options.sql.use_odps2_extension = True
table = o.create_table('my_new_table', 'cat smallint, content struct<title:varchar(100), body:string>')

Eliminar una tabla

Llame a delete_table() sobre el objeto de entrada o a drop() sobre un objeto de tabla.

o.delete_table('my_table_name', if_exists=True)  # Delete a table only if the table exists.
t.drop() # Call the drop() method to drop a table if the table exists.

Gestionar particiones de tabla

Comprobar si una tabla está particionada

table = o.get_table('my_new_table')
if table.schema.partitions:
    print('Table %s is partitioned.' % table.name)

Iterar por las particiones

table = o.get_table('my_new_table')
for partition in table.partitions:  # Iterate over all partitions.
    print(partition.name)  # An iteration step. In this step, the partition name is displayed.
for partition in table.iterate_partitions(spec='pt=test'):  # Iterate over level-2 partitions in the partition named test.
    print(partition.name)  # An iteration step. In this step, the partition name is displayed.
for partition in table.iterate_partitions(spec='dt>20230119'):  # Iterate over level-2 partitions in the partitions that meet the dt>20230119 condition.
    print(partition.name)  # An iteration step. In this step, the partition name is displayed.
Importante

Las expresiones lógicas en iterate_partitions (como dt>20230119) requieren PyODPS 0.11.3 o posterior.

Comprobar si existe una partición

table = o.get_table('my_new_table')
table.exist_partition('pt=test,sub=2015')

Obtener información de una partición

table = o.get_table('my_new_table')
partition = table.get_partition('pt=test')
print(partition.creation_time)
partition.size

Crear una partición

t = o.get_table('my_new_table')
t.create_partition('pt=test', if_not_exists=True)  # Create a partition only if no partition with the same name exists.

Eliminar una partición

t = o.get_table('my_new_table')
t.delete_partition('pt=test', if_exists=True)  # Set the if_exists parameter to True. This ensures that a partition is deleted only if the partition exists.
partition.drop()  # Call the drop() method to drop a partition if the partition exists.

Leer datos de una tabla

Leer los primeros N registros con head()

El método head() recupera hasta 10 000 registros del inicio de una tabla.

from odps import ODPS
t = o.get_table('dual')
for record in t.head(3):
    # Process each record.

Leer con open_reader() mediante una instrucción with

with t.open_reader(partition='pt=test') as reader:
count = reader.count
for record in reader[5:10]  # You can execute the statement multiple times until all records are read. The number of records is specified by count. You can change the code to parallel-operation code.
    # Process one record.

Leer con open_reader() sin una instrucción with

reader = t.open_reader(partition='pt=test')
count = reader.count
for record in reader[5:10]  # You can execute the statement multiple times until all records are read. The number of records is specified by count. You can change the code to parallel-operation code.
    # Process one record.

Leer directamente en un DataFrame de pandas

with t.open_reader(partition='pt=test') as reader:
pd_df = reader.to_pandas()

Escribir datos en una tabla

Escribir con open_writer() mediante una instrucción with

with t.open_writer(partition='pt=test') as writer:
	  records = [[111, 'aaa', True],                 # A list can be used.
	             [222, 'bbb', False],
	             [333, 'ccc', True],
	             [444, 'Chinese', False]]
    writer.write(records)  # Records can be iterable objects.

records = [t.new_record([111, 'aaa', True]),   # Record objects can be used.
           t.new_record([222, 'bbb', False]),
           t.new_record([333, 'ccc', True]),
           t.new_record([444, 'Chinese', False])]
writer.write(records)

Puede pasar listas simples u objetos Record (creados con t.new_record()) a writer.write().

Crear automáticamente una partición durante la escritura

Establezca create_partition=True para crear la partición automáticamente si aún no existe.

with t.open_writer(partition='pt=test', create_partition=True) as writer:
    records = [[111, 'aaa', True],                 # A list can be used.
               [222, 'bbb', False],
               [333, 'ccc', True],
               [444, 'Chinese', False]]
    writer.write(records)  # Records can be iterable objects.

Escribir con write_table()

El método write_table() del objeto de entrada de MaxCompute ofrece una interfaz más sencilla para escribir datos.

records = [[111, 'aaa', True],                 # A list can be used.
           [222, 'bbb', False],
           [333, 'ccc', True],
           [444, 'Chinese', False]]
o.write_table('test_table', records, partition='pt=test', create_partition=True)

Leer y escribir datos en formato Apache Arrow

Apache Arrow es un formato multiplataforma para intercambiar datos entre distintas plataformas. Desde 2021, MaxCompute admite la lectura de datos de tablas en formato Arrow. Esta función es compatible con PyODPS 0.11.2 y versiones posteriores.

Después de instalar pyarrow en su entorno de Python, agregue arrow=True al llamar a open_reader() o a open_writer() para leer o escribir objetos RecordBatch de Arrow.

import pandas as pd
import pyarrow as pa
with t.open_writer(partition='pt=test', create_partition=True, arrow=True) as writer:
    records = [[111, 'aaa', True],
               [222, 'bbb', False],
               [333, 'ccc', True],
               [444, 'Chinese', False]]
    df = pd.DataFrame(records, columns=["int_val", "str_val", "bool_val"])
    # Write a RecordBatch.
    batch = pa.RecordBatch.from_pandas(df)
    writer.write(batch)
    # You can also use Pandas DataFrame directly.
    writer.write(df)