Todos los productos
Search
Centro de documentos

:Filtrar objetos de OSS por rango de tiempo

Última actualización: Sep 23, 2026

Para filtrar los objetos de un bucket de Object Storage Service (OSS) según un rango de tiempo específico, utilice la función de indexación de datos. Establecer una fecha de inicio y una de fin con base en la última modificación del objeto mejora la eficiencia de las consultas. Esta función resulta útil en escenarios que requieren recuperar archivos sensibles al tiempo de forma precisa, como el seguimiento de auditorías, la sincronización de datos, las copias de seguridad periódicas y el análisis de costos.

Casos de uso

  • Auditorías y comprobaciones de cumplimiento

    Las empresas y organizaciones deben revisar periódicamente las actividades de datos para garantizar el cumplimiento normativo. Consultar los objetos subidos dentro de un rango de tiempo específico ayuda a gestionar el ciclo de vida de los datos, rastrear el historial de creación y modificación, y respaldar los procesos de auditoría.

  • Copias de seguridad y recuperación de datos

    Al ejecutar operaciones de copia de seguridad o recuperación basadas en una política definida, consultar los objetos nuevos o actualizados dentro de un rango de tiempo permite identificar los destinos exactos de la copia de seguridad. Esto ahorra espacio de almacenamiento y reduce los costos de transferencia de datos.

  • Análisis de datos y generación de informes

    En aplicaciones de análisis de big data, procesamiento de registros o informes de negocio, es común necesitar procesar datos nuevos generados durante un periodo determinado, ya sea diario, semanal o mensual. Consultar los objetos dentro de un rango de tiempo le permite localizar rápidamente el conjunto de datos para su análisis y simplifica la extracción de información.

  • Sincronización de sistemas de gestión de contenido

    Un sistema de gestión de contenido debe sincronizar de manera regular los objetos nuevos o actualizados para mantener el contenido del sitio web vigente y completo.

  • Optimización de costos y limpieza de recursos

    Las empresas deben limpiar periódicamente los objetos obsoletos. Consultar los objetos que no se han actualizado en un periodo determinado ayuda a identificar cuáles eliminar, lo que garantiza un uso eficiente de los recursos.

  • Solución de problemas y rastreo de incidencias

    Cuando soluciona fallas del sistema, pérdida de datos o comportamientos anómalos, consultar los objetos de un periodo específico le permite localizar rápidamente los objetos problemáticos o los registros de operación.

  • Colaboración y control de versiones

    En un entorno de colaboración multiusuario, consultar los objetos dentro de un rango de tiempo le permite explorar versiones históricas, comparar cambios o restaurar datos a un momento específico.

Procedimiento

OSS console

  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 > Data Indexing.

  4. En la página Data Indexing, active el interruptor Metadata Management.

    Después de habilitar la gestión de metadatos, la activación toma cierto tiempo. Este lapso depende de la cantidad de objetos en el bucket.

  5. En la sección OSS metadata condition, establezca las fechas de inicio y fin para Last Modified At (con precisión de segundos). Mantenga la configuración predeterminada para los demás parámetros.

  6. En la sección Object Sort Order, seleccione Ascending para ordenar los resultados por nombre de objeto.

  7. Haga clic en Query.

Alibaba Cloud SDK

El OSS SDK for Java, el OSS SDK for Python y el OSS SDK for Go admiten la indexación de datos para consultar objetos que cumplen condiciones específicas. Debe habilitar la gestión de metadatos en el bucket de destino antes de usar esta función.

Java

package com.aliyun.sts.sample;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

public class Demo {

    // This example uses the endpoint of the China (Hangzhou) region. Replace the value with your actual endpoint.
    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Specify the region that corresponds to your endpoint. For example, if your endpoint is oss-cn-hangzhou.aliyuncs.com, set the region to cn-hangzhou.
    private static String region = "cn-hangzhou";
    
    // Specify the bucket name. Example: examplebucket.
    private static String bucketName = "examplebucket";

    public static void main(String[] args) throws Exception {
        // Obtain access credentials from environment variables. Before you run this code, make sure that you have configured the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient instance is no longer needed.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare that the V4 signature algorithm is used.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Set the maximum number of objects to return to 100.
            int maxResults = 100;
            // Query objects that were last modified between December 1, 2023 and March 31, 2024.
            String query = "{\n" +
                    "  \"SubQueries\":[\n" +
                    "    {\n" +
                    "      \"Field\":\"FileModifiedTime\",\n" +
                    "      \"Value\": \"2023-12-01T00:00:00.000+08:00\",\n" +
                    "      \"Operation\":\"gt\"\n" +
                    "    },         \n" +
                    "    {\n" +
                    "      \"Field\":\"FileModifiedTime\",\n" +
                    "      \"Value\": \"2024-03-31T23:59:59.000+08:00\",\n" +
                    "      \"Operation\":\"lt\"\n" +
                    "    }\n" +
                    "  ],\n" +
                    "  \"Operation\":\"and\"\n" +
                    "}";
            // Sort the results by object name in ascending order.
            String sort = "Filename";
            DoMetaQueryRequest doMetaQueryRequest = new DoMetaQueryRequest(bucketName, maxResults, query, sort);
            doMetaQueryRequest.setOrder(SortOrder.ASC);
            DoMetaQueryResult doMetaQueryResult = ossClient.doMetaQuery(doMetaQueryRequest);

            if (doMetaQueryResult.getFiles() != null) {
                for (ObjectFile file : doMetaQueryResult.getFiles().getFile()) {
                    System.out.println("Filename: " + file.getFilename());
                    // Obtain the object's ETag.
                    System.out.println("ETag: " + file.getETag());
                    // Obtain the access control list (ACL) of the object.
                    System.out.println("ObjectACL: " + file.getObjectACL());
                    // Obtain the object type.
                    System.out.println("OssObjectType: " + file.getOssObjectType());
                    // Obtain the object storage class.
                    System.out.println("OssStorageClass: " + file.getOssStorageClass());
                    // Obtain the number of object tags.
                    System.out.println("TaggingCount: " + file.getOssTaggingCount());
                    if (file.getOssTagging() != null) {
                        for (Tagging tag : file.getOssTagging().getTagging()) {
                            System.out.println("Key: " + tag.getKey());
                            System.out.println("Value: " + tag.getValue());
                        }
                    }
                    if (file.getOssUserMeta() != null) {
                        for (UserMeta meta : file.getOssUserMeta().getUserMeta()) {
                            System.out.println("Key: " + meta.getKey());
                            System.out.println("Value: " + meta.getValue());
                        }
                    }
                }
            }
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            // Shut down the OSSClient instance.
            ossClient.shutdown();
        }
    }
}

Python

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import MetaQuery, AggregationsRequest
# Obtain access credentials from environment variables. Before you run this code, make sure that you have configured the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# This example uses the endpoint of the China (Hangzhou) region. Replace the value with your actual endpoint.
# Specify the bucket name. Example: examplebucket.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket0703')

# Query objects last modified between December 1, 2023 and March 31, 2024, and sort the results by object name in ascending order.
do_meta_query_request = MetaQuery(max_results=100, query='{"SubQueries":[{"Field":"FileModifiedTime","Value": "2023-12-01T00:00:00.000+08:00","Operation":"gt"}, {"Field":"FileModifiedTime","Value": "2024-03-31T23:59:59.000+08:00","Operation":"lt"}],"Operation":"and"}', sort='Filename', order='asc')
result = bucket.do_bucket_meta_query(do_meta_query_request)

for s in result.files:
    print(s.file_name)
    print(s.etag)
    print(s.oss_object_type)
    print(s.oss_storage_class)
    print(s.oss_crc64)
    print(s.object_acl)

Go

package main

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this code, make sure that you have configured the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance.
	// This example uses the endpoint for the China (Hangzhou) region. Replace the value with your actual endpoint.
	client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Query objects that were last modified between December 1, 2023 and March 31, 2024.
	query := oss.MetaQuery{
		NextToken:  "",
		MaxResults: 100,
		Query: `{
  "SubQueries":[
    {
      "Field":"FileModifiedTime",
      "Value": "2023-12-01T00:00:00.000+08:00",
      "Operation":"gt"
    },         
    {
      "Field":"FileModifiedTime",
      "Value": "2024-03-31T23:59:59.000+08:00",
      "Operation":"lt"
    }
  ],
  "Operation":"and"
}`,
                // Sort the results by object name in ascending order.
		Sort:  "Filename",
		Order: "asc",
	}
	// Query for objects that meet the specified conditions and list the object information based on the specified fields and sort order.
	result, err := client.DoMetaQuery("examplebucket", query)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("NextToken:%s\n", result.NextToken)
	for _, file := range result.Files {
		fmt.Printf("File name: %s\n", file.Filename)
		fmt.Printf("size: %d\n", file.Size)
		fmt.Printf("File Modified Time:%s\n", file.FileModifiedTime)
		fmt.Printf("Oss Object Type:%s\n", file.OssObjectType)
		fmt.Printf("Oss Storage Class:%s\n", file.OssStorageClass)
		fmt.Printf("Object ACL:%s\n", file.ObjectACL)
		fmt.Printf("ETag:%s\n", file.ETag)
		fmt.Printf("Oss CRC64:%s\n", file.OssCRC64)
		fmt.Printf("Oss Tagging Count:%d\n", file.OssTaggingCount)
		for _, tagging := range file.OssTagging {
			fmt.Printf("Oss Tagging Key:%s\n", tagging.Key)
			fmt.Printf("Oss Tagging Value:%s\n", tagging.Value)
		}
		for _, userMeta := range file.OssUserMeta {
			fmt.Printf("Oss User Meta Key:%s\n", userMeta.Key)
			fmt.Printf("Oss User Meta Key Value:%s\n", userMeta.Value)
		}
	}
}

REST API

Si su aplicación requiere un alto grado de personalización, puede enviar solicitudes directamente a la REST API. Para ello, debe escribir código manualmente y calcular la firma. Para obtener más información, consulte DoMetaQuery.

Referencias

La indexación de datos admite varias condiciones de filtro, como la clase de almacenamiento, los permisos de lectura y escritura, y el tamaño del objeto, para ayudarle a encontrar rápidamente los datos que necesita. Por ejemplo, puede consultar todos los objetos con permisos de lectura pública o todos los objetos menores a 64 KB. Para obtener más información, consulte Data indexing.