すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:最終変更時刻が特定の期間内の OSS オブジェクトをフィルタリングする

最終更新日:Jun 29, 2025

最終変更時刻が特定の期間内の Object Storage Service (OSS) オブジェクトをフィルタリングする場合、データインデックス機能を使用できます。オブジェクトの最終変更時刻の開始日と終了日をインデックス条件として指定して、オブジェクトクエリ効率を向上させることができます。この機能は、監査証跡、データ同期、定期バックアップ、コスト分析、またはその他のビジネスシナリオにおける時間依存オブジェクトの正確な取得に適しています。

シナリオ

  • 監査とコンプライアンスの要件

    企業または組織は、コンプライアンスを確保するために、データ活動を定期的にレビューする必要があります。特定の期間内にアップロードされたオブジェクトをクエリすると、データライフサイクルの管理、データ生成と変更履歴の追跡、およびデータの監査に役立ちます。

  • データのバックアップと復元

    バックアップポリシーを指定してバックアップまたはリカバリ操作を実行する場合、指定された時間範囲内に新しく追加または更新されたオブジェクトをクエリすると、バックアップターゲットを特定するのに役立ち、ストレージ使用量と転送コストを削減できます。

  • データ分析とレポート生成

    ビッグデータ分析、ログ処理、またはビジネスレポート作成に関連するアプリケーションの場合、特定の期間内に生成された新しいデータを、毎日、毎週、または毎月など、定期的に処理する必要があります。特定の期間内に生成されたオブジェクトをクエリすると、分析するデータセットをすばやく特定し、データ抽出プロセスを簡素化できます。

  • コンテンツ管理システムによって実行されるデータ同期

    コンテンツ管理システムは、アップロードまたは更新されたオブジェクトを定期的に同期して、Web サイトコンテンツの適時性と整合性を維持する必要があります。

  • コストの最適化とリソースの削除

    企業は、不要になったオブジェクトを定期的にレビューして削除する必要があります。特定の期間内に更新されていないオブジェクトをクエリすると、不要になったオブジェクトを特定するのに役立ちます。これにより、リソースを効率的に使用できます。

  • トラブルシューティングと問題の追跡

    システム障害、データ損失、または異常な動作が発生した場合、特定の期間内にアップロードされたオブジェクトをクエリすると、エンジニアは問題の原因となっている可能性のあるオブジェクトまたは操作をすばやく特定できます。

  • コラボレーションとバージョン管理

    マルチユーザーコラボレーション環境では、特定の期間内にアップロードされたオブジェクトをクエリすると、履歴バージョンを特定の時点まで参照、比較、または復元できます。

手順

OSS コンソールを使用する

  1. OSS コンソール にログインします。

  2. 左側のナビゲーションウィンドウで、バケットリスト をクリックします。 [バケット] ページで、目的のバケットを見つけてクリックします。

  3. 左側のナビゲーションツリーで、オブジェクト管理 > データのインデックス作成 を選択します。

  4. データのインデックス作成 ページで、メタデータ管理 をオンにします。

    メタデータ管理が有効になるまでの時間は、バケット内のオブジェクトの数によって異なります。

  5. [OSS メタデータ条件] セクションで、[最終変更日時] の右側に [開始日] と [終了日] を指定します。開始日と終了日の値は秒単位まで正確です。他のパラメーターについては、デフォルト設定を保持します。

  6. オブジェクトのソート順 セクションで、[並べ替え順序] を [昇順] に、[並べ替え基準] を [オブジェクト名] に設定します。

  7. クエリ をクリックします。

OSS SDK を使用する

データインデックス機能を使用して特定の条件を満たすオブジェクトをクエリできるのは、OSS SDK for Java、OSS SDK for Python、および OSS SDK for Go のみです。データインデックス機能を使用してバケット内のオブジェクトをクエリする前に、バケットのメタデータ管理機能を有効にする必要があります。

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 {

    // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou.
    private static String region = "cn-hangzhou";
    
    // 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();
        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Set the maximum number of objects that you want to return to 100. 
            int maxResults = 100;
            // Specify the start date and end date of the last modified time of the objects that you want to query. In this example, the start date is set to December 1, 2023 and the end date is set to 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" +
                    "}";
            // Specify that the returned results are sorted in ascending order by object name. 
            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());
                    // Query the ETag values that are used to identify the content of the objects. 
                    System.out.println("ETag: " + file.getETag());
                    // Query the access control list (ACL) of the objects.
                    System.out.println("ObjectACL: " + file.getObjectACL());
                    // Query the type of the objects. 
                    System.out.println("OssObjectType: " + file.getOssObjectType());
                    // Query the storage class of the objects. 
                    System.out.println("OssStorageClass: " + file.getOssStorageClass());
                    // Query the number of tags of the objects. 
                    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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket0703')

# Specify the start date and end date of the last modified time of the objects that you want to query. In this example, the start date is set to December 1, 2023 and the end date is set to March 31, 2024. 
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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
	// 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. Specify 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)
	}
	// Specify the start date and end date of the last modified time of the objects that you want to query. In this example, the start date is set to December 1, 2023 and the end date is set to 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"
}`,
                // Specify that the returned results are sorted in ascending order by object name. 
		Sort:  "Filename",
		Order: "asc",
	}
	// Query objects that match specific conditions and list object information based on specific fields and sorting methods. 
	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)
		}
	}
}

RESTful API を使用する

ビジネスで高度なカスタマイズが必要な場合は、RESTful API を直接呼び出すことができます。API を直接呼び出すには、コードに署名計算を含める必要があります。詳細については、「DoMetaQuery」をご参照ください。

参考資料

データインデックス機能は、ストレージクラス、ACL、オブジェクトサイズなど、複数のフィルタリング条件をサポートしており、特定の条件を満たすオブジェクトを効率的にフィルタリングできます。たとえば、バケット内で ACL がパブリック読み取りであるオブジェクト、またはサイズが 64 KB 未満のオブジェクトをクエリできます。詳細については、「データインデックス」をご参照ください。