オブジェクトのリスト

このページでは、Cloud Storage バケットに保存されているオブジェクトを一覧表示する方法について説明します。表示されるオブジェクトは名前順に並べられます。

始める前に

オブジェクトの一覧表示に必要な権限を取得するには、リストするオブジェクトを含むバケットに対するストレージ オブジェクト閲覧者(roles/storage.objectViewer)の IAM ロールを付与するよう管理者に依頼してください。マネージド フォルダ内のオブジェクトを一覧表示する場合は、バケットではなく、表示するオブジェクトを含むマネージド フォルダに roles/storage.objectViewer を付与します。

Cloud de Confiance コンソールを使用してこのページのタスクを実施する場合は、ストレージ オブジェクト閲覧者(roles/storage.objectViewer)ロールに加えて、閲覧者(roles/viewer)の基本ロールを付与するよう管理者に依頼してください。

これらのロールには、オブジェクトを一覧取得するために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.objects.list
  • storage.buckets.list
    • この権限は、 Cloud de Confiance コンソールを使用してこのページのタスクを実施する場合にのみ必要です。

これらの権限は、他の事前定義ロールカスタムロールを使用して取得することもできます。

バケットのロールの付与については、バケットでの IAM ポリシーの設定と管理をご覧ください。

バケット内のオブジェクトを一覧表示する

コンソール

  1. Cloud de Confiance コンソールで Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットリストで、コンテンツを表示するバケットの名前をクリックします。

コマンドライン

gcloud storage ls コマンドを使用します。

gcloud storage ls gs://BUCKET_NAME

ここで

  • BUCKET_NAME は、一覧表示するオブジェクトを含むバケットの名前です。例: my-bucket

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
  for (auto&& object_metadata : client.ListObjects(bucket_name)) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& bucket_prefix) {
  for (auto&& object_metadata :
       client.ListObjects(bucket_name, gcs::Prefix(bucket_prefix))) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListFilesSample
{
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFiles(
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var storageObjects = storage.ListObjects(bucketName);
        Console.WriteLine($"Files in bucket {bucketName}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }

        return storageObjects;
    }
}

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListFilesWithPrefixSample
{
    /// <summary>
    /// Prefixes and delimiters can be used to emulate directory listings.
    /// Prefixes can be used to filter objects starting with prefix.
    /// The delimiter argument can be used to restrict the results to only the
    /// objects in the given "directory". Without the delimiter, the entire  tree
    /// under the prefix is returned.
    /// For example, given these objects:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// If you just specify prefix="a/", you'll get back:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// However, if you specify prefix="a/" and delimiter="/", you'll get back:
    ///   a/1.txt
    /// </summary>
    /// <param name="bucketName">The bucket to list the objects from.</param>
    /// <param name="prefix">The prefix to match. Only objects with names that start with this string will
    /// be returned. This parameter may be null or empty, in which case no filtering
    /// is performed.</param>
    /// <param name="delimiter">Used to list in "directory mode". Only objects whose names (aside from the prefix)
    /// do not contain the delimiter will be returned.</param>
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFilesWithPrefix(
        string bucketName = "your-unique-bucket-name",
        string prefix = "your-prefix",
        string delimiter = "your-delimiter")
    {
        var storage = StorageClient.Create();
        var options = new ListObjectsOptions { Delimiter = delimiter };
        var storageObjects = storage.ListObjects(bucketName, prefix, options);
        Console.WriteLine($"Objects in bucket {bucketName} with prefix {prefix}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }
        return storageObjects;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFiles lists objects within specified bucket.
func listFiles(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, nil)
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects: %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFilesWithPrefix lists objects using prefix and delimeter.
func listFilesWithPrefix(w io.Writer, bucket, prefix, delim string) error {
	// bucket := "bucket-name"
	// prefix := "/foo"
	// delim := "_"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	// Prefixes and delimiters can be used to emulate directory listings.
	// Prefixes can be used to filter objects starting with prefix.
	// The delimiter argument can be used to restrict the results to only the
	// objects in the given "directory". Without the delimiter, the entire tree
	// under the prefix is returned.
	//
	// For example, given these blobs:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// If you just specify prefix="a/", you'll get back:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// However, if you specify prefix="a/" and delim="/", you'll get back:
	//   /a/1.txt
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, &storage.Query{
		Prefix:    prefix,
		Delimiter: delim,
	})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects(): %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjects {
  public static void listObjects(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Page<Blob> blobs = storage.list(bucketName);

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectsWithPrefix {
  public static void listObjectsWithPrefix(
      String projectId, String bucketName, String directoryPrefix) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The directory prefix to search for
    // String directoryPrefix = "myDirectory/"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    /**
     * Using the Storage.BlobListOption.currentDirectory() option here causes the results to display
     * in a "directory-like" mode, showing what objects are in the directory you've specified, as
     * well as what other directories exist in that directory. For example, given these blobs:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>If you specify prefix = "a/" and don't use Storage.BlobListOption.currentDirectory(),
     * you'll get back:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>However, if you specify prefix = "a/" and do use
     * Storage.BlobListOption.currentDirectory(), you'll get back:
     *
     * <p>a/1.txt a/b/
     *
     * <p>Because a/1.txt is the only file in the a/ directory and a/b/ is a directory inside the
     * /a/ directory.
     */
    Page<Blob> blobs =
        storage.list(
            bucketName,
            Storage.BlobListOption.prefix(directoryPrefix),
            Storage.BlobListOption.currentDirectory());

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFiles() {
  // Lists files in the bucket
  const [files] = await storage.bucket(bucketName).getFiles();

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFiles().catch(console.error);

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The directory prefix to search for
// const prefix = 'myDirectory/';

// The delimiter to use
// const delimiter = '/';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFilesByPrefix() {
  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * If you just specify prefix = 'a/', you'll get back:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * However, if you specify prefix='a/' and delimiter='/', you'll get back:
   *
   *   /a/1.txt
   */
  const options = {
    prefix: prefix,
  };

  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  const [files] = await storage.bucket(bucketName).getFiles(options);

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFilesByPrefix().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_objects(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    foreach ($bucket->objects() as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects with specified prefix.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $directoryPrefix the prefix to use in the list objects API call.
 *        (e.g. 'myDirectory/')
 */
function list_objects_with_prefix(string $bucketName, string $directoryPrefix): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $directoryPrefix];
    foreach ($bucket->objects($options) as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

from google.cloud import storage


def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name)

    # Note: The call returns a response only when the iterator is consumed.
    for blob in blobs:
        print(blob.name)

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

from google.cloud import storage


def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
    """Lists all the blobs in the bucket that begin with the prefix.

    This can be used to list all blobs in a "folder", e.g. "public/".

    The delimiter argument can be used to restrict the results to only the
    "files" in the given "folder". Without the delimiter, the entire tree under
    the prefix is returned. For example, given these blobs:

        a/1.txt
        a/b/2.txt

    If you specify prefix ='a/', without a delimiter, you'll get back:

        a/1.txt
        a/b/2.txt

    However, if you specify prefix='a/' and delimiter='/', you'll get back
    only the file directly under 'a/':

        a/1.txt

    As part of the response, you'll also get back a blobs.prefixes entity
    that lists the "subfolders" under `a/`:

        a/b/


    Note: If you only want to list prefixes a/b/ and don't want to iterate over
    blobs, you can do

    ```
    for page in blobs.pages:
        print(page.prefixes)
    ```
    """

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(
        bucket_name, prefix=prefix, delimiter=delimiter
    )

    # Note: The call returns a response only when the iterator is consumed.
    print("Blobs:")
    for blob in blobs:
        print(blob.name)

    if delimiter:
        print("Prefixes:")
        for prefix in blobs.prefixes:
            print(prefix)

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケット内のすべてのオブジェクトを一覧表示する例です。

def list_files bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.files.each do |file|
    puts file.name
  end
end

以下は、特定の接頭辞を持つオブジェクトを一覧表示する例です。

def list_files_with_prefix bucket_name:, prefix:, delimiter: nil
  # Lists all the files in the bucket that begin with the prefix.
  #
  # This can be used to list all files in a "folder", e.g. "public/".
  #
  # The delimiter argument can be used to restrict the results to only the
  # "files" in the given "folder". Without the delimiter, the entire tree under
  # the prefix is returned. For example, given these files:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # If you just specify `prefix: "a"`, you will get back:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # However, if you specify `prefix: "a"` and `delimiter: "/"`, you will get back:
  #
  #     a/1.txt

  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The directory prefix to search for
  # prefix = "a"

  # The delimiter to be used to restrict the results
  # delimiter = "/"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  files   = bucket.files prefix: prefix, delimiter: delimiter

  files.each do |file|
    puts file.name
  end
end

REST API

JSON API

  1. gcloud CLI のインストールと初期化を行います。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. cURL を使用して、オブジェクトを一覧表示するリクエストJSON API を呼び出します。

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/o"

    ここで、BUCKET_NAME はオブジェクトを一覧表示するバケットの名前です。例: my-bucket

XML API

  1. gcloud CLI をインストールして初期化します。これにより、Authorization ヘッダーのアクセス トークンを生成できます。

  2. cURL使用して、GET Bucket リクエストで XML API を呼び出します。

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/BUCKET_NAME?list-type=2"

    ここで、BUCKET_NAME はオブジェクトを一覧表示するバケットの名前です。例: my-bucket

    prefix=PREFIX クエリ文字列パラメータを使用すると、指定した接頭辞を持つオブジェクトのみが含まれる結果を取得できます。

フォルダ内のオブジェクトを一覧表示する

コンソール

  1. Cloud de Confiance コンソールで Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットリストで、フォルダを含むバケットの名前をクリックします。

  3. [バケットの詳細] ページの [オブジェクト] タブで、コンテンツを表示するフォルダの名前をクリックします。

コマンドライン

gcloud storage ls コマンドを使用して、フォルダ内のオブジェクトを一覧表示します。

gcloud storage ls gs://BUCKET_NAME/FOLDER_NAME

ここで

  • BUCKET_NAME は、フォルダを含むバケットの名前です。例: my-bucket

  • FOLDER_NAME は、一覧表示するオブジェクトを含むフォルダの名前です。例: my-folder

REST API

JSON API

フォルダ内のオブジェクトを一覧表示するには、prefix パラメータと delimiter パラメータを設定してオブジェクト リスト リクエストを使用します。prefix パラメータを設定すると、リスト オペレーションは、プレフィックスの下にあるオブジェクトとフォルダのみを返すようにスコープ設定されます。delimiter パラメータを設定すると、レスポンスの prefixes[] リストには、指定された接頭辞の下にあるフォルダの名前が入力されます。

例:

  • バケット my-bucket 内にあるフォルダ image/ のすべてのオブジェクトを一覧表示するには、次の URL を使用します。 "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/"

    これにより、オブジェクト my-bucket/image/cat.jpegmy-bucket/image/dog.jpeg が返される可能性があります。

  • image/ 内のサブフォルダにあるオブジェクトを含めるには、delimiter パラメータ "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image" を削除します。

    これにより、オブジェクト my-bucket/image/cat.jpegmy-bucket/image/dog.jpegmy-bucket/image/dog/shiba.jpeg が返される可能性があります。

オブジェクト リスト リクエストでワイルドカードを使用し、glob 式でオブジェクトを照合するには、matchGlob パラメータを使用します。たとえば、matchGlob=**.jpeg は末尾が .jpeg のオブジェクトと一致します。matchGlob を使用する場合は、delimiter/ に設定する必要があります。

たとえば、次の URL を使用すると、フォルダ image 内で末尾が .jpeg のすべてのオブジェクトと一致します。 "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/&matchGlob=**.jpeg"

パラメータを使用してオブジェクトをフィルタする方法について詳しくは、オブジェクト リストの JSON API リファレンス ドキュメントをご覧ください。

ユースケース

prefix を使用してフォルダの内容を一覧表示することは、バケット全体ではなく、フォルダ内のオブジェクトのみを一覧表示する権限が付与されている場合に便利です。たとえば、マネージド フォルダ my-bucket/my-managed-folder-a/ に対するストレージ オブジェクト閲覧者(roles/storage.objectViewer)の IAM ロールがあり、マネージド フォルダ my-bucket/my-managed-folder-b/ に対するロールは付与されていないとします。my-managed-folder-a 内のオブジェクトのみを取得するには、prefix=my-managed-folder-a/ を指定します。

オブジェクトをフィルタする

オブジェクトを一覧表示するときに、list リクエストで接頭辞または接尾辞を使用して、名前でオブジェクトをフィルタリングできます。

コンソール

バケットまたはフォルダ内のオブジェクトをフィルタして並べ替える方法については、フィルタと並べ替えをご覧ください。

コマンドライン

gcloud storage ls コマンドでワイルドカードを使用すると、接頭辞または接尾辞でオブジェクトをフィルタリングできます。たとえば、次のコマンドは、my-bucket バケット内の名前が image で始まり .png で終わるオブジェクトのみを一覧表示します。

gcloud storage ls gs://my-bucket/image*.png

リクエストが成功すると、次のようなレスポンスが返されます。

gs://my-bucket/image.png
gs://my-bucket/image-dog.png
gs://my-bucket/image-cat.png
...

二重ワイルドカード(**)を使用すると、パス内の 0 個以上のフォルダレベルに一致させることができます。たとえば、次のコマンドは、バケット my-bucket 内の任意のフォルダまたはサブフォルダにある、名前の末尾が .jpeg のオブジェクトのみを一覧表示します。

gcloud storage ls gs://my-bucket/**/*.jpeg

リクエストが成功すると、次のようなレスポンスが返されます。

gs://my-bucket/puppy.jpeg
gs://my-bucket/pug.jpeg
gs://my-bucket/pets/dog.jpeg
...

REST API

フォルダまたはオブジェクト名の接頭辞でオブジェクトをフィルタする方法については、フォルダ内のオブジェクトを一覧表示するをご覧ください。

コンテキストでオブジェクトをフィルタする

フィルタを使用すると、指定したコンテキストプレビュー)を持つオブジェクトのみをリスト レスポンスに表示できます。

コマンドライン

gcloud alpha storage objects list コマンドを使用します。

gcloud alpha storage objects list gs://BUCKET_NAME --metadata-filter='contexts."KEY"="VALUE"'

ここで

  • BUCKET_NAME は、コンテキストでフィルタするオブジェクトが格納されているバケットの名前です。例: my-bucket
  • KEY は、オブジェクトに関連付けられたコンテキスト キーです。
  • VALUE は、コンテキスト キーに関連付けられた値です。

正常に終了すると、レスポンスは次の例のようになります。

---
bucket: my-bucket
contexts:
  Department:
    createTime: '2023-01-01T00:00:00.000000+00:00'
    type: CUSTOM
    updateTime: '2023-01-01T00:00:00.000000+00:00'
    value: HR
  DataClassification:
    createTime: '2023-01-01T00:00:00.000000+00:00'
    type: CUSTOM
    updateTime: '2023-01-01T00:00:00.000000+00:00'
    value: Confidential
name: employees.txt
...

クライアント ライブラリ

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。


import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectContexts {
  public static void listObjectContexts(String projectId, String bucketName, String key)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The context key you want to filter
    // String key = "your-context-key";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
      /*
       * List any object that has a context with the specified key attached
       * String filter = "contexts.\"KEY\":*";
       *
       * List any object that that does not have a context with the specified key attached
       * String filter = "NOT contexts.\"KEY\":*";
       *
       * List any object that has a context with the specified key and value attached
       * String filter = "contexts.\"KEY\"=\"VALUE\"";
       *
       * List any object that does not have a context with the specified key and value attached
       * String filter = "NOT contexts.\"KEY\"=\"VALUE\"";
       */

      String filter = "contexts.\"" + key + "\":*";

      System.out.println("Listing objects for bucket: " + bucketName + "with context key: " + key);
      Page<Blob> blobs = storage.list(bucketName, Storage.BlobListOption.filter(filter));
      for (Blob blob : blobs.iterateAll()) {
        System.out.println(blob.getBlobId().toGsUtilUri());
      }
    }
  }
}

REST API

JSON API

Object: list リクエストは、filter クエリ パラメータの使用方法の例を示しています。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/o/?filter=contexts.%22KEY%22%3D%22VALUE%22"

ここで

  • BUCKET_NAME は、コンテキストでフィルタするオブジェクトが格納されているバケットの名前です。例: my-bucket
  • KEY は、オブジェクトに関連付けられたコンテキスト キーです。
  • VALUE は、コンテキスト キーに関連付けられた値です。

構文

Cloud Storage は、フィルタで次の構文をサポートしています。

構文 説明
contexts."KEY":* 指定されたキーが関連付けられたコンテキストを持つオブジェクトに一致します。
contexts."KEY"="VALUE" 指定されたキーと値が関連付けられたコンテキストを持つオブジェクトに一致します。

NOT contexts."KEY":*

または

-contexts."KEY":*

指定されたキーが関連付けられたコンテキストを持たないオブジェクトに一致します。

NOT contexts."KEY"="VALUE"

または

-contexts."KEY"="VALUE"

指定されたキーと値が関連付けられたコンテキストを持たないオブジェクトに一致します。

オブジェクトを一覧表示する際のパフォーマンスに関する考慮事項

階層型名前空間が有効になっているバケットの基盤となる構造は、フラット名前空間のバケットと比較して、オブジェクトの一覧表示オペレーションのパフォーマンスに影響します。詳細については、階層型名前空間が有効なバケットのパフォーマンスを最適化するをご覧ください。

次のステップ