> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Fornece uma interface semelhante a uma tabela para `SELECT` e `INSERT` de dados do Google Cloud Storage. Requer o papel do IAM `Storage Object User`.

# gcs

Fornece uma interface semelhante a uma tabela para `SELECT` e `INSERT` de dados do [Google Cloud Storage](https://cloud.google.com/storage/). Requer o [papel do IAM `Storage Object User`](https://cloud.google.com/storage/docs/access-control/iam-roles).

Este é um alias da [função de tabela s3](/pt-BR/reference/functions/table-functions/s3).

Se você tiver várias réplicas no cluster, poderá usar a [função s3Cluster](/pt-BR/reference/functions/table-functions/s3Cluster) (que funciona com GCS) para paralelizar inserções.

<div id="syntax">
  ## Sintaxe
</div>

```sql theme={null}
gcs(url [, NOSIGN | hmac_key, hmac_secret] [,format] [,structure] [,compression_method])
gcs(named_collection[, option=value [,..]])
```

<Tip>
  **GCS**

  A função de tabela GCS se integra ao Google Cloud Storage usando a API XML do GCS e chaves HMAC.
  Consulte a [documentação de interoperabilidade do Google](https://cloud.google.com/storage/docs/interoperability) para mais detalhes sobre o endpoint e o HMAC.
</Tip>

<div id="arguments">
  ## Argumentos
</div>

| Argumento                    | Descrição                                                                                                                                                                                                    |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `url`                        | Caminho do bucket para o arquivo. Suporta os seguintes curingas no modo somente leitura: `*`, `**`, `?`, `{abc,def}` e `{N..M}`, em que `N`, `M` — números, `'abc'`, `'def'` — strings.                      |
| `NOSIGN`                     | Se esta palavra-chave for fornecida no lugar das credenciais, nenhuma requisição será assinada.                                                                                                              |
| `hmac_key` and `hmac_secret` | Chaves que especificam as credenciais a serem usadas com o endpoint informado. Opcional.                                                                                                                     |
| `format`                     | O [formato](/pt-BR/reference/formats) do arquivo.                                                                                                                                                            |
| `structure`                  | Estrutura da tabela. Formato `'column1_name column1_type, column2_name column2_type, ...'`.                                                                                                                  |
| `compression_method`         | O parâmetro é opcional. Valores aceitos: `none`, `gzip` ou `gz`, `brotli` ou `br`, `xz` ou `LZMA`, `zstd` ou `zst`. Por padrão, o método de compressão é detectado automaticamente pela extensão do arquivo. |

<Info>
  **GCS**

  O caminho do GCS tem este formato, pois o endpoint da Google XML API é diferente do da JSON API:

  ```text theme={null}
    https://storage.googleapis.com/<bucket>/<folder>/<filename(s)>
  ```

  e não ~~[https://storage.cloud.google.com](https://storage.cloud.google.com)~~.
</Info>

Os argumentos também podem ser passados usando [coleções nomeadas](/pt-BR/concepts/features/configuration/server-config/named-collections). Nesse caso, `url`, `format`, `structure`, `compression_method` funcionam da mesma forma, e alguns parâmetros extras são aceitos:

| Parâmetro                     | Descrição                                                                                                                                                                                                                                 |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `access_key_id`               | `hmac_key`, opcional.                                                                                                                                                                                                                     |
| `secret_access_key`           | `hmac_secret`, opcional.                                                                                                                                                                                                                  |
| `filename`                    | Acrescentado à URL, se especificado.                                                                                                                                                                                                      |
| `use_environment_credentials` | Habilitado por padrão, permite passar parâmetros extras usando as variáveis de ambiente `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN`, `AWS_EC2_METADATA_DISABLED`. |
| `no_sign_request`             | Desabilitado por padrão.                                                                                                                                                                                                                  |
| `expiration_window_seconds`   | O valor padrão é 120.                                                                                                                                                                                                                     |

<div id="returned_value">
  ## Valor retornado
</div>

Uma tabela com a estrutura especificada para ler ou gravar dados no arquivo especificado.

<div id="examples">
  ## Exemplos
</div>

Selecionando as duas primeiras linhas da tabela a partir do arquivo do GCS `https://storage.googleapis.com/my-test-bucket-768/data.csv`:

```sql theme={null}
SELECT *
FROM gcs('https://storage.googleapis.com/clickhouse_public_datasets/my-test-bucket-768/data.csv.gz', 'CSV', 'column1 UInt32, column2 UInt32, column3 UInt32')
LIMIT 2;
```

```text theme={null}
┌─column1─┬─column2─┬─column3─┐
│       1 │       2 │       3 │
│       3 │       2 │       1 │
└─────────┴─────────┴─────────┘
```

Semelhante, mas de um arquivo com método de compressão `gzip`:

```sql theme={null}
SELECT *
FROM gcs('https://storage.googleapis.com/clickhouse_public_datasets/my-test-bucket-768/data.csv.gz', 'CSV', 'column1 UInt32, column2 UInt32, column3 UInt32', 'gzip')
LIMIT 2;
```

```text theme={null}
┌─column1─┬─column2─┬─column3─┐
│       1 │       2 │       3 │
│       3 │       2 │       1 │
└─────────┴─────────┴─────────┘
```

<div id="usage">
  ## Uso
</div>

Suponha que temos vários arquivos com as seguintes URIs no GCS:

* '[https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;1.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;1.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;2.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;2.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;3.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;3.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;4.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/some\&#95;prefix/some\&#95;file\&#95;4.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;1.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;1.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;2.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;2.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;3.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;3.csv\&#39);
* '[https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;4.csv\&#39](https://storage.googleapis.com/my-test-bucket-768/another\&#95;prefix/some\&#95;file\&#95;4.csv\&#39);

Conte o número de linhas nos arquivos que terminam com os números de 1 a 3:

```sql theme={null}
SELECT count(*)
FROM gcs('https://storage.googleapis.com/clickhouse_public_datasets/my-test-bucket-768/{some,another}_prefix/some_file_{1..3}.csv', 'CSV', 'column1 UInt32, column2 UInt32, column3 UInt32')
```

```text theme={null}
┌─count()─┐
│      18 │
└─────────┘
```

Conte o total de linhas em todos os arquivos nestes dois diretórios:

```sql theme={null}
SELECT count(*)
FROM gcs('https://storage.googleapis.com/clickhouse_public_datasets/my-test-bucket-768/{some,another}_prefix/*', 'CSV', 'column1 UInt32, column2 UInt32, column3 UInt32')
```

```text theme={null}
┌─count()─┐
│      24 │
└─────────┘
```

<Warning>
  Se a lista de arquivos contiver intervalos numéricos com zeros à esquerda, use a construção com chaves para cada dígito separadamente ou use `?`.
</Warning>

Conte o número total de linhas em arquivos chamados `file-000.csv`, `file-001.csv`, ... , `file-999.csv`:

```sql theme={null}
SELECT count(*)
FROM gcs('https://storage.googleapis.com/clickhouse_public_datasets/my-test-bucket-768/big_prefix/file-{000..999}.csv', 'CSV', 'name String, value UInt32');
```

```text theme={null}
┌─count()─┐
│      12 │
└─────────┘
```

Insira dados no arquivo `test-data.csv.gz`:

```sql theme={null}
INSERT INTO FUNCTION gcs('https://storage.googleapis.com/my-test-bucket-768/test-data.csv.gz', 'CSV', 'name String, value UInt32', 'gzip')
VALUES ('test-data', 1), ('test-data-2', 2);
```

Insira dados no arquivo `test-data.csv.gz` a partir de uma tabela existente:

```sql theme={null}
INSERT INTO FUNCTION gcs('https://storage.googleapis.com/my-test-bucket-768/test-data.csv.gz', 'CSV', 'name String, value UInt32', 'gzip')
SELECT name, value FROM existing_table;
```

O glob `**` pode ser usado para percorrer diretórios de forma recursiva. Considere o exemplo abaixo: ele buscará todos os arquivos do diretório `my-test-bucket-768` recursivamente:

```sql theme={null}
SELECT * FROM gcs('https://storage.googleapis.com/my-test-bucket-768/**', 'CSV', 'name String, value UInt32', 'gzip');
```

O trecho abaixo obtém dados de todos os arquivos `test-data.csv.gz` de qualquer pasta dentro do diretório `my-test-bucket`, de forma recursiva:

```sql theme={null}
SELECT * FROM gcs('https://storage.googleapis.com/my-test-bucket-768/**/test-data.csv.gz', 'CSV', 'name String, value UInt32', 'gzip');
```

Para casos de uso em produção, recomenda-se usar [coleções nomeadas](/pt-BR/concepts/features/configuration/server-config/named-collections). Veja o exemplo:

```sql theme={null}

CREATE NAMED COLLECTION creds AS
        access_key_id = '***',
        secret_access_key = '***';
SELECT count(*)
FROM gcs(creds, url='https://s3-object-url.csv')
```

<div id="partitioned-write">
  ## Gravação particionada
</div>

Se você especificar a expressão `PARTITION BY` ao inserir dados na tabela `GCS`, será criado um arquivo separado para cada valor de partição. Dividir os dados em arquivos separados ajuda a aumentar a eficiência das operações de leitura.

**Exemplos**

1. Usar o ID da partição em uma chave cria arquivos separados:

```sql theme={null}
INSERT INTO TABLE FUNCTION
    gcs('http://bucket.amazonaws.com/my_bucket/file_{_partition_id}.csv', 'CSV', 'a String, b UInt32, c UInt32')
    PARTITION BY a VALUES ('x', 2, 3), ('x', 4, 5), ('y', 11, 12), ('y', 13, 14), ('z', 21, 22), ('z', 23, 24);
```

Como resultado, os dados são gravados em três arquivos: `file_x.csv`, `file_y.csv` e `file_z.csv`.

2. Usar o ID da partição no nome do bucket cria arquivos em buckets diferentes:

```sql theme={null}
INSERT INTO TABLE FUNCTION
    gcs('http://bucket.amazonaws.com/my_bucket_{_partition_id}/file.csv', 'CSV', 'a UInt32, b UInt32, c UInt32')
    PARTITION BY a VALUES (1, 2, 3), (1, 4, 5), (10, 11, 12), (10, 13, 14), (20, 21, 22), (20, 23, 24);
```

Como resultado, os dados são gravados em três arquivos, em buckets diferentes: `my_bucket_1/file.csv`, `my_bucket_10/file.csv` e `my_bucket_20/file.csv`.

<div id="related">
  ## Relacionados
</div>

* [função de tabela S3](/pt-BR/reference/functions/table-functions/s3)
* [motor S3](/pt-BR/reference/engines/table-engines/integrations/s3)
