The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: vector and analytics storage (#39716)
Chris Chinchillaba16b2c189fb
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.tsindex 5c358d9fd32..408492b92b3 100644--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts@@ -1878,143 +1878,201 @@ export const storage: NavMenuConstant = {url: '/guides/storage',items: [{ name: 'Overview', url: '/guides/storage' },- { name: 'Quickstart', url: '/guides/storage/quickstart' },{- name: 'Buckets',+ name: 'File Buckets',url: undefined,items: [+ { name: 'Quickstart', url: '/guides/storage/quickstart' },{ name: 'Fundamentals', url: '/guides/storage/buckets/fundamentals' },{name: 'Creating Buckets',url: '/guides/storage/buckets/creating-buckets' as `/${string}`,},- ],- },- {- name: 'Security',- url: undefined,- items: [{- name: 'Ownership',- url: '/guides/storage/security/ownership' as `/${string}`,+ name: 'Security',+ url: '/guides/storage/security',+ items: [+ {+ name: 'Ownership',+ url: '/guides/storage/security/ownership' as `/${string}`,+ },+ {+ name: 'Access Control',+ url: '/guides/storage/security/access-control' as `/${string}`,+ },+ ],},{- name: 'Access Control',- url: '/guides/storage/security/access-control' as `/${string}`,+ name: 'Uploads',+ url: '/guides/storage/uploads',+ items: [+ {+ name: 'Standard Uploads',+ url: '/guides/storage/uploads/standard-uploads' as `/${string}`,+ },+ {+ name: 'Resumable Uploads',+ url: '/guides/storage/uploads/resumable-uploads' as `/${string}`,+ },+ {+ name: 'S3 Uploads',+ url: '/guides/storage/uploads/s3-uploads' as `/${string}`,+ },+ { name: 'Limits', url: '/guides/storage/uploads/file-limits', enabled: billingEnabled },+ ],},- ],- },- {- name: 'Uploads',- url: undefined,- items: [{- name: 'Standard Uploads',- url: '/guides/storage/uploads/standard-uploads' as `/${string}`,+ name: 'Serving',+ url: '/guides/storage/serving',+ items: [+ { name: 'Serving assets', url: '/guides/storage/serving/downloads' },+ {+ name: 'Image Transformations',+ url: '/guides/storage/serving/image-transformations' as `/${string}`,+ },+ {+ name: 'Bandwidth & Storage Egress',+ url: '/guides/storage/serving/bandwidth' as `/${string}`,+ enabled: billingEnabled,+ },+ ],},{- name: 'Resumable Uploads',- url: '/guides/storage/uploads/resumable-uploads' as `/${string}`,+ name: 'Management',+ url: '/guides/storage/management',+ items: [+ { name: 'Copy / Move Objects', url: '/guides/storage/management/copy-move-objects' },+ { name: 'Delete Objects', url: '/guides/storage/management/delete-objects' },+ ],},{- name: 'S3 Uploads',- url: '/guides/storage/uploads/s3-uploads' as `/${string}`,+ name: 'S3',+ url: '/guides/storage/s3',+ items: [+ { name: 'Authentication', url: '/guides/storage/s3/authentication' },+ { name: 'API Compatibility', url: '/guides/storage/s3/compatibility' },+ ],},- { name: 'Limits', url: '/guides/storage/uploads/file-limits', enabled: billingEnabled },- ],- },- {- name: 'Serving',- url: undefined,- items: [- { name: 'Serving assets', url: '/guides/storage/serving/downloads' },{- name: 'Image Transformations',- url: '/guides/storage/serving/image-transformations' as `/${string}`,+ name: 'CDN',+ url: '/guides/storage/cdn',+ items: [+ { name: 'Fundamentals', url: '/guides/storage/cdn/fundamentals' },+ { name: 'Smart CDN', url: '/guides/storage/cdn/smart-cdn' },+ { name: 'Metrics', url: '/guides/storage/cdn/metrics' },+ ],},{- name: 'Bandwidth & Storage Egress',- url: '/guides/storage/serving/bandwidth' as `/${string}`,- enabled: billingEnabled,+ name: 'Debugging',+ url: '/guides/storage/debugging',+ items: [+ { name: 'Logs', url: '/guides/storage/debugging/logs' },+ { name: 'Error Codes', url: '/guides/storage/debugging/error-codes' },+ { name: 'Troubleshooting', url: '/guides/storage/troubleshooting' },+ ],+ },+ {+ name: 'Schema',+ url: '/guides/storage/schema',+ items: [+ { name: 'Database Design', url: '/guides/storage/schema/design' },+ {+ name: 'Helper Functions',+ url: '/guides/storage/schema/helper-functions' as `/${string}`,+ },+ { name: 'Custom Roles', url: '/guides/storage/schema/custom-roles' },+ ],+ },+ {+ name: 'Going to production',+ url: '/guides/storage/production',+ items: [{ name: 'Scaling', url: '/guides/storage/production/scaling' }],},- ],- },- {- name: 'Management',- url: undefined,- items: [- { name: 'Copy / Move Objects', url: '/guides/storage/management/copy-move-objects' },- { name: 'Delete Objects', url: '/guides/storage/management/delete-objects' },{name: 'Pricing',- url: '/guides/storage/management/pricing' as `/${string}`,+ url: '/guides/storage/pricing' as `/${string}`,enabled: billingEnabled,},],},- {- name: 'S3',- url: undefined,- items: [- { name: 'Authentication', url: '/guides/storage/s3/authentication' },- { name: 'API Compatibility', url: '/guides/storage/s3/compatibility' },- ],- },{name: 'Analytics Buckets',- url: undefined,items: [{ name: 'Introduction', url: '/guides/storage/analytics/introduction' },{- name: 'Creating Analytics Buckets',+ name: 'Creating Buckets',url: '/guides/storage/analytics/creating-analytics-buckets' as `/${string}`,},{- name: 'Connecting to Analytics Buckets',+ name: 'Iceberg Catalog',url: '/guides/storage/analytics/connecting-to-analytics-bucket' as `/${string}`,},+ {+ name: 'Realtime Data-Sync',+ url: '/guides/storage/analytics/etl' as `/${string}`,+ },+ {+ name: 'Query with Postgres',+ url: '/guides/storage/analytics/query-with-postgres' as `/${string}`,+ },+ {+ name: 'Examples',+ url: '/guides/storage/analytics/examples' as `/${string}`,+ items: [+ {+ name: 'Using DuckDB',+ url: '/guides/storage/analytics/examples/duckdb',+ },+ {+ name: 'Using PyIceberg',+ url: '/guides/storage/analytics/examples/pyiceberg',+ },+ {+ name: 'Using Apache Spark',+ url: '/guides/storage/analytics/examples/apache-spark',+ },+ ],+ },{name: 'Limits',url: '/guides/storage/analytics/limits' as `/${string}`,enabled: billingEnabled,},+ {+ name: 'Pricing',+ url: '/guides/storage/analytics/pricing' as `/${string}`,+ enabled: billingEnabled,+ },],},{- name: 'CDN',- url: undefined,- items: [- { name: 'Fundamentals', url: '/guides/storage/cdn/fundamentals' },- { name: 'Smart CDN', url: '/guides/storage/cdn/smart-cdn' },- { name: 'Metrics', url: '/guides/storage/cdn/metrics' },- ],- },- {- name: 'Debugging',- url: undefined,- items: [- { name: 'Logs', url: '/guides/storage/debugging/logs' },- { name: 'Error Codes', url: '/guides/storage/debugging/error-codes' },- { name: 'Troubleshooting', url: '/guides/storage/troubleshooting' },- ],- },- {- name: 'Schema',- url: undefined,+ name: 'Vector Buckets',+ url: '/guides/storage/vector',items: [- { name: 'Database Design', url: '/guides/storage/schema/design' },+ { name: 'Introduction', url: '/guides/storage/vector/introduction' },{- name: 'Helper Functions',- url: '/guides/storage/schema/helper-functions' as `/${string}`,+ name: 'Creating Buckets',+ url: '/guides/storage/vector/creating-vector-buckets' as `/${string}`,+ },+ {+ name: 'Working with Indexes',+ url: '/guides/storage/vector/working-with-indexes' as `/${string}`,+ },+ {+ name: 'Storing Vectors',+ url: '/guides/storage/vector/storing-vectors' as `/${string}`,+ },+ {+ name: 'Querying Vectors',+ url: '/guides/storage/vector/querying-vectors' as `/${string}`,+ },+ {+ name: 'Limits',+ url: '/guides/storage/vector/limits' as `/${string}`,+ enabled: billingEnabled,},- { name: 'Custom Roles', url: '/guides/storage/schema/custom-roles' },],},- {- name: 'Going to production',- url: undefined,- items: [{ name: 'Scaling', url: '/guides/storage/production/scaling' }],- },],}diff --git a/apps/docs/content/guides/storage.mdx b/apps/docs/content/guides/storage.mdxindex fd840fdec13..5139bd5873e 100644--- a/apps/docs/content/guides/storage.mdx+++ b/apps/docs/content/guides/storage.mdx@@ -7,11 +7,64 @@ sidebar_label: 'Overview'hideToc: true----Supabase Storage makes it simple to upload and serve files of any size, providing a robust framework for file access controls.+Supabase Storage is a robust, scalable solution for managing files of any size with fine-grained access controls and optimized delivery. Whether you're storing user-generated content, analytics data, or vector embeddings, Supabase Storage provides specialized bucket types to meet your specific needs.-## Features+## Key features-You can use Supabase Storage to store images, videos, documents, and any other file type. Serve your assets with a global CDN to reduce latency from over 285 cities globally. Supabase Storage includes a built-in image optimizer, so you can resize and compress your media files on the fly.+- **Multi Protocol** - S3 compatible Storage, RESTful API, TUS resumable uploads+- **Global CDN** - Serve your assets with lightning-fast performance from over 285 cities worldwide+- **Image Optimization** - Resize, compress, and transform media files on the fly with built-in image processing+- **Fine-grained Access Control** - Manage file permissions with row-level security and custom policies+- **Multiple Bucket Types** - Specialized storage solutions for different use cases++## Storage bucket types++Supabase Storage offers different bucket types optimized for specific use cases:++### Files buckets++Store and serve traditional files including images, videos, documents, and general-purpose content. Ideal for user-generated content, media libraries, and asset management.++**Use cases:** Images, videos, documents, PDFs, archives++**Features:**++- Global CDN delivery+- Image optimization and transformation+- Row-level security integration+- Direct URL access for files++[Learn more about Files Buckets](/docs/guides/storage/quickstart)++### Analytics buckets++Purpose-built for storing and analyzing data in open table formats like Apache Iceberg. Perfect for time-series data, logs, and large-scale analytical workloads.++**Use cases:** Data lakes, analytics pipelines, ETL operations, historical data analysis++**Features:**++- Apache Iceberg table format support+- SQL-accessible via Postgres foreign tables+- Partitioned data organization+- Efficient data querying and transformation++[Learn more about Analytics Buckets](/docs/guides/storage/analytics/introduction)++### Vector buckets++Specialized storage for vector embeddings and similarity search operations. Designed for AI and ML applications requiring semantic search capabilities.++**Use cases:** AI-powered search, semantic similarity matching, embedding storage, RAG systems++**Features:**++- Optimized vector indexing (HNSW, Flat)+- Multiple distance metrics (cosine, euclidean, L2)+- Metadata filtering for vectors+- Similarity search queries++[Learn more about Vector Buckets](/docs/guides/storage/vector/introduction)## Examplesdiff --git a/apps/docs/content/guides/storage/analytics/connecting-to-analytics-bucket.mdx b/apps/docs/content/guides/storage/analytics/connecting-to-analytics-bucket.mdxindex b68b367779e..d5fd6ac718d 100644--- a/apps/docs/content/guides/storage/analytics/connecting-to-analytics-bucket.mdx+++ b/apps/docs/content/guides/storage/analytics/connecting-to-analytics-bucket.mdx@@ -1,187 +1,65 @@----title: 'Connecting to Analytics Buckets'+title: 'Iceberg Catalog'----<Admonition type="caution">+<Admonition type="caution" title="This feature is in alpha">-This feature is in **Private Alpha**. API stability and backward compatibility are not guaranteed at this stage. Reach out from this [Form](https://forms.supabase.com/analytics-buckets) to request access+Expect rapid changes, limited features, and possible breaking updates. [share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.</Admonition>-When interacting with Analytics Buckets, you authenticate against two main services - the Iceberg REST Catalog and the S3-Compatible Storage Endpoint.+Analytics buckets require authentication with two distinct services:-The **Iceberg REST Catalog** acts as the central management system for Iceberg tables. It allows Iceberg clients, such as PyIceberg and Apache Spark, to perform metadata operations including:+## Architecture overview++**Iceberg REST Catalog** serves as the metadata management system for your Iceberg tables. It enables Iceberg clients such as PyIceberg and Apache Spark to perform critical operations:- Creating and managing tables and namespaces- Tracking schemas and handling schema evolution-- Managing partitions and snapshots+- Managing partitions and table snapshots- Ensuring transactional consistency and isolation-The REST Catalog itself does not store the actual data. Instead, it stores metadata describing the structure, schema, and partitioning strategy of Iceberg tables.--Actual data storage and retrieval operations occur through the separate S3-compatible endpoint, optimized for reading and writing large analytical datasets stored in Parquet files.+The REST Catalog only stores metadata describing your data's structure, schema, and partitioning strategy—not the actual data itself.-## Authentication+**S3-Compatible Storage Endpoint** handles the actual data storage and retrieval. It's optimized for reading and writing large analytical datasets stored in Parquet format, separate from the metadata management layer.-To connect to an Analytics Bucket, you will need+## Authentication setup-- An Iceberg client (Spark, PyIceberg, etc) which supports the REST Catalog interface.-- S3 credentials to authenticate your Iceberg client with the underlying S3 Bucket.- To create S3 Credentials go to [**Project Settings > Storage**](/dashboard/project/_/storage/settings), for more information, see the [S3 Authentication Guide](/docs/guides/storage/s3/authentication). We will support other authentication methods in the future.+To connect to an analytics bucket, you need:-- The project reference and Service key for your Supabase project.- You can find your Service key in the Supabase Dashboard under [**Project Settings > API**.](/dashboard/project/_/settings/api-keys)+### 1. S3 credentials-You will now have an **Access Key** and a **Secret Key** that you can use to authenticate your Iceberg client.+Create S3 credentials through [**Project Settings > Storage**](/dashboard/project/_/storage/settings). See the [S3 Authentication Guide](/docs/guides/storage/s3/authentication) for detailed instructions.-## Connecting via PyIceberg+You'll obtain:-PyIceberg is a Python client for Apache Iceberg, facilitating interaction with Iceberg Buckets.+- **Access Key ID**+- **Secret Access Key**+- **Region** (e.g., `us-east-1`)-**Installation**+### 2. Supabase service key-```bash-pip install pyiceberg pyarrow-```+Retrieve your Service Key from [**Project Settings > API**](/dashboard/project/_/settings/api-keys). This key authenticates requests to the Iceberg REST Catalog.-Here's a comprehensive example using PyIceberg with clearly separated configuration:--```python-from pyiceberg.catalog import load_catalog-import pyarrow as pa-import datetime--# Supabase project ref-PROJECT_REF = "<your-supabase-project-ref>"--# Configuration for Iceberg REST Catalog-WAREHOUSE = "your-analytics-bucket-name"-TOKEN = "SERVICE_KEY"--# Configuration for S3-Compatible Storage-S3_ACCESS_KEY = "KEY"-S3_SECRET_KEY = "SECRET"-S3_REGION = "PROJECT_REGION"--S3_ENDPOINT = f"https://{PROJECT_REF}.supabase.co/storage/v1/s3"-CATALOG_URI = f"https://{PROJECT_REF}.supabase.co/storage/v1/iceberg"--# Load the Iceberg catalog-catalog = load_catalog(- "analytics-bucket",- type="rest",- warehouse=WAREHOUSE,- uri=CATALOG_URI,- token=TOKEN,- **{- "py-io-impl": "pyiceberg.io.pyarrow.PyArrowFileIO",- "s3.endpoint": S3_ENDPOINT,- "s3.access-key-id": S3_ACCESS_KEY,- "s3.secret-access-key": S3_SECRET_KEY,- "s3.region": S3_REGION,- "s3.force-virtual-addressing": False,- },-)--# Create namespace if it doesn't exist-catalog.create_namespace_if_not_exists("default")--# Define schema for your Iceberg table-schema = pa.schema([- pa.field("event_id", pa.int64()),- pa.field("event_name", pa.string()),- pa.field("event_timestamp", pa.timestamp("ms")),-])--# Create table (if it doesn't exist already)-table = catalog.create_table_if_not_exists(("default", "events"), schema=schema)--# Generate and insert sample data-current_time = datetime.datetime.now()-data = pa.table({- "event_id": [1, 2, 3],- "event_name": ["login", "logout", "purchase"],- "event_timestamp": [current_time, current_time, current_time],-})--# Append data to the Iceberg table-table.append(data)--# Scan table and print data as pandas DataFrame-df = table.scan().to_pandas()-print(df)-```+### 3. Project reference-## Connecting via Apache Spark--Apache Spark allows distributed analytical queries against Iceberg Buckets.--```python-from pyspark.sql import SparkSession--# Supabase project ref-PROJECT_REF = "<your-supabase-ref>"--# Configuration for Iceberg REST Catalog-WAREHOUSE = "your-analytics-bucket-name"-TOKEN = "SERVICE_KEY"--# Configuration for S3-Compatible Storage-S3_ACCESS_KEY = "KEY"-S3_SECRET_KEY = "SECRET"-S3_REGION = "PROJECT_REGION"--S3_ENDPOINT = f"https://{PROJECT_REF}.supabase.co/storage/v1/s3"-CATALOG_URI = f"https://{PROJECT_REF}.supabase.co/storage/v1/iceberg"--# Initialize Spark session with Iceberg configuration-spark = SparkSession.builder \- .master("local[*]") \- .appName("SupabaseIceberg") \- .config("spark.driver.host", "127.0.0.1") \- .config("spark.driver.bindAddress", "127.0.0.1") \- .config('spark.jars.packages', 'org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.6.1,org.apache.iceberg:iceberg-aws-bundle:1.6.1') \- .config("spark.sql.extensions", "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions") \- .config("spark.sql.catalog.my_catalog", "org.apache.iceberg.spark.SparkCatalog") \- .config("spark.sql.catalog.my_catalog.type", "rest") \- .config("spark.sql.catalog.my_catalog.uri", CATALOG_URI) \- .config("spark.sql.catalog.my_catalog.warehouse", WAREHOUSE) \- .config("spark.sql.catalog.my_catalog.token", TOKEN) \- .config("spark.sql.catalog.my_catalog.s3.endpoint", S3_ENDPOINT) \- .config("spark.sql.catalog.my_catalog.s3.path-style-access", "true") \- .config("spark.sql.catalog.my_catalog.s3.access-key-id", S3_ACCESS_KEY) \- .config("spark.sql.catalog.my_catalog.s3.secret-access-key", S3_SECRET_KEY) \- .config("spark.sql.catalog.my_catalog.s3.remote-signing-enabled", "false") \- .config("spark.sql.defaultCatalog", "my_catalog") \- .getOrCreate()--# SQL Operations-spark.sql("CREATE NAMESPACE IF NOT EXISTS analytics")--spark.sql("""- CREATE TABLE IF NOT EXISTS analytics.users (- user_id BIGINT,- username STRING- )- USING iceberg-""")--spark.sql("""- INSERT INTO analytics.users (user_id, username)- VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')-""")--result_df = spark.sql("SELECT * FROM analytics.users")-result_df.show()-```+Your Supabase project reference is the subdomain in your project URL (e.g., `your-project-ref` in `https://your-project-ref.supabase.co`).-## Connecting to the Iceberg REST Catalog directly+## Testing your connection-To authenticate with the Iceberg REST Catalog directly, you need to provide a valid Supabase **Service key** as a Bearer token.+You can verify your setup by making a direct request to the Iceberg REST Catalog. Provide your Service Key as a Bearer token:-```+```bashcurl \--request GET -sL \- --url 'https://<your-supabase-project>.supabase.co/storage/v1/iceberg/v1/config?warehouse=<bucket-name>' \+ --url 'https://<your-project-ref>.supabase.co/storage/v1/iceberg/v1/config?warehouse=<bucket-name>' \--header 'Authorization: Bearer <your-service-key>'```++A successful response returns the catalog configuration including warehouse location and settings.++## Next steps++- [Connect with PyIceberg](/docs/guides/storage/analytics/examples/pyiceberg)+- [Connect with Apache Spark](/docs/guides/storage/analytics/examples/apache-spark)+- [Query with Postgres](/docs/guides/storage/analytics/query-with-postgres)diff --git a/apps/docs/content/guides/storage/analytics/creating-analytics-buckets.mdx b/apps/docs/content/guides/storage/analytics/creating-analytics-buckets.mdxindex 16f0b3831a0..d22a283f4b8 100644--- a/apps/docs/content/guides/storage/analytics/creating-analytics-buckets.mdx+++ b/apps/docs/content/guides/storage/analytics/creating-analytics-buckets.mdx@@ -1,41 +1,50 @@---title: 'Creating Analytics Buckets'-subtitle: ''+subtitle: 'Set up your first analytics bucket using the SDK or dashboard.'---<Admonition type="caution">-This feature is in **Private Alpha**. API stability and backward compatibility are not guaranteed at this stage. Reach out from this [Form](https://forms.supabase.com/analytics-buckets) to request access+This feature is in **Private Alpha**. API stability and backward compatibility are not guaranteed at this stage. Request access through this [form](https://forms.supabase.com/analytics-buckets).</Admonition>-Analytics Buckets use [Apache Iceberg](https://iceberg.apache.org/), an open-table format for managing large analytical datasets.-You can interact with them using tools such as [PyIceberg](https://py.iceberg.apache.org/), [Apache Spark](https://spark.apache.org/) or any client which supports the [standard Iceberg REST Catalog API](https://editor-next.swagger.io/?url=https://raw.githubusercontent.com/apache/iceberg/main/open-api/rest-catalog-open-api.yaml).+Analytics buckets use [Apache Iceberg](https://iceberg.apache.org/), an open-table format for efficient management of large analytical datasets. You can interact with analytics buckets using tools such as [PyIceberg](https://py.iceberg.apache.org/), [Apache Spark](https://spark.apache.org/), or any client supporting the [Iceberg REST Catalog API](https://editor-next.swagger.io/?url=https://raw.githubusercontent.com/apache/iceberg/main/open-api/rest-catalog-open-api.yaml).-You can create an Analytics Bucket using either the Supabase SDK or the Supabase Dashboard.+## Creating an Analytics bucket++You can create an analytics bucket using either the Supabase SDK or the Supabase Dashboard.### Using the Supabase SDK-{/* prettier-ignore */}```tsimport { createClient } from '@supabase/supabase-js'-const supabase = createClient(- 'https://your-project.supabase.co',- 'publishable-or-anon-key'-)+const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++const { data, error } = await supabase.storage.analytics.createBucket('analytics-data')-const { data, error } =- await supabase.storage.analytics.createBucket('analytics-data')+if (error) {+ console.error('Failed to create analytics bucket:', error)+} else {+ console.log('Analytics bucket created:', data)+}```### Using the Supabase Dashboard-1. Navigate to the Storage section in the Supabase Dashboard.-2. Click on "Create Bucket".-3. Enter a name for your bucket (e.g., my-analytics-bucket).-4. Select "Analytics Bucket" as the bucket type.+1. Navigate to the **Storage** section in the Supabase Dashboard.+2. Click **Create Bucket**.+3. Enter a name for your bucket (e.g., `my-analytics-bucket`).+4. Select **Analytics Bucket** as the bucket type.+5. Click **Create**.++<img alt="Create Analytics Bucket in Dashboard" src="/docs/img/storage/iceberg-bucket.png" />++## Next steps-<img alt="Storage schema design" src="/docs/img/storage/iceberg-bucket.png" />+Once you've created your analytics bucket, you can:-Now, that you have created your Analytics Bucket, you can start [connecting to it](/docs/guides/storage/analytics/connecting-to-analytics-bucket) with Iceberg clients like PyIceberg or Apache Spark.+- [Connect with Iceberg clients](/docs/guides/storage/analytics/connecting-to-analytics-bucket) like PyIceberg or Apache Spark+- [Set up real-time replication](/docs/guides/storage/analytics/etl) from your Postgres database+- [Query data with Postgres](/docs/guides/storage/analytics/query-with-postgres) using the Iceberg Foreign Data Wrapperdiff --git a/apps/docs/content/guides/storage/analytics/etl.mdx b/apps/docs/content/guides/storage/analytics/etl.mdxnew file mode 100644index 00000000000..34f89f96383--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/etl.mdx@@ -0,0 +1,81 @@+---+title: 'Realtime Data Sync to Analytics Buckets'+subtitle: 'Replicate your PostgreSQL data to analytics buckets in real-time.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++By combining Supabase's **ETL service** with **Analytics Buckets**, you can build an end-to-end data warehouse solution that automatically syncs changes from your Postgres database to Iceberg tables.++## How it works++The ETL pipeline captures changes (INSERT, UPDATE, DELETE) from your Postgres database in real-time and writes them to your analytics bucket. This allows you to maintain an always-up-to-date data warehouse without impacting your production workloads.++## Setup steps++### Step 1: Create an Analytics bucket++First, create a new analytics bucket to store your replicated data:++1. Navigate to **Storage** in the Supabase Dashboard.+2. Click **Create Bucket**.+3. Enter a name (e.g., `my-warehouse`).+4. Select **Analytics Bucket** as the type.+5. Click **Create**.++<Image+ alt="Creating a new analytics bucket"+ src="/docs/img/database/replication/etl-iceberg-new-bucket.png"+ zoomable+/>++### Step 2: Create a publication++A publication defines which tables and change types will be replicated. Create one using SQL in the Supabase SQL Editor:++```sql+-- Create publication for tables you want to replicate+CREATE PUBLICATION pub_warehouse+ FOR TABLE users, orders, products;+```++This publication will track all changes (INSERT, UPDATE, DELETE) for the specified tables. For advanced use cases, see the [Replication Configuration Guide](/docs/guides/database/replication/etl-replication-setup).++### Step 3: Create the ETL pipeline++Now set up the pipeline to sync data to your analytics bucket:++1. Navigate to **Database > Replication** in the Supabase Dashboard.+2. Click **Create Pipeline**.+3. Select the **Publication** you created in Step 2.+4. Select your **Analytics Bucket** as the destination.+5. Configure any additional settings as needed.+6. Click **Create and Start**.++<Image+ alt="ETL pipeline configuration"+ src="/docs/img/database/replication/etl-iceberg-details.png"+ zoomable+/>++## Monitoring your pipeline++Once started, you can monitor the pipeline status directly in the **Database > Replication** section:++- **Status** - Shows if the pipeline is running, paused, or encountered errors+- **Sync Progress** - View the number of records replicated+- **Logs** - Check detailed logs for troubleshooting++## Next steps++Once data is flowing to your analytics bucket, you can:++- [Query with SQL via Postgres](/docs/guides/storage/analytics/query-with-postgres)+- [Connect with PyIceberg](/docs/guides/storage/analytics/examples/pyiceberg)+- [Analyze with Apache Spark](/docs/guides/storage/analytics/examples/apache-spark)++For advanced topics, see the [ETL Replication Monitoring Guide](/docs/guides/database/replication/etl-replication-monitoring).diff --git a/apps/docs/content/guides/storage/analytics/examples/apache-spark.mdx b/apps/docs/content/guides/storage/analytics/examples/apache-spark.mdxnew file mode 100644index 00000000000..845b88ff469--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/examples/apache-spark.mdx@@ -0,0 +1,265 @@+---+title: 'Apache Spark'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Apache Spark enables distributed analytical processing of large datasets stored in your analytics buckets. Use it for complex transformations, aggregations, and machine learning workflows.++## Installation++First, ensure you have Spark installed. For Python-based workflows:++```bash+pip install pyspark+```++For detailed Spark setup instructions, see the [Apache Spark documentation](https://spark.apache.org/docs/latest/).++## Basic setup++Here's a complete example showing how to configure Spark with your Supabase analytics bucket:++```python+from pyspark.sql import SparkSession++# Configuration - Update with your Supabase credentials+PROJECT_REF = "your-project-ref"+WAREHOUSE = "your-analytics-bucket-name"+SERVICE_KEY = "your-service-key"++# S3 credentials from Project Settings > Storage+S3_ACCESS_KEY = "your-access-key"+S3_SECRET_KEY = "your-secret-key"+S3_REGION = "us-east-1"++# Construct Supabase endpoints+S3_ENDPOINT = f"https://{PROJECT_REF}.supabase.co/storage/v1/s3"+CATALOG_URI = f"https://{PROJECT_REF}.supabase.co/storage/v1/iceberg"++# Initialize Spark session with Iceberg configuration+spark = SparkSession.builder \+ .master("local[*]") \+ .appName("SupabaseIceberg") \+ .config("spark.driver.host", "127.0.0.1") \+ .config("spark.driver.bindAddress", "127.0.0.1") \+ .config(+ 'spark.jars.packages',+ 'org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.6.1,org.apache.iceberg:iceberg-aws-bundle:1.6.1'+ ) \+ .config("spark.sql.extensions", "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions") \+ .config("spark.sql.catalog.supabase", "org.apache.iceberg.spark.SparkCatalog") \+ .config("spark.sql.catalog.supabase.type", "rest") \+ .config("spark.sql.catalog.supabase.uri", CATALOG_URI) \+ .config("spark.sql.catalog.supabase.warehouse", WAREHOUSE) \+ .config("spark.sql.catalog.supabase.token", SERVICE_KEY) \+ .config("spark.sql.catalog.supabase.s3.endpoint", S3_ENDPOINT) \+ .config("spark.sql.catalog.supabase.s3.path-style-access", "true") \+ .config("spark.sql.catalog.supabase.s3.access-key-id", S3_ACCESS_KEY) \+ .config("spark.sql.catalog.supabase.s3.secret-access-key", S3_SECRET_KEY) \+ .config("spark.sql.catalog.supabase.s3.remote-signing-enabled", "false") \+ .config("spark.sql.defaultCatalog", "supabase") \+ .getOrCreate()++print("✓ Spark session initialized with Iceberg")+```++## Creating tables++```python+# Create a namespace for organization+spark.sql("CREATE NAMESPACE IF NOT EXISTS analytics")++# Create a new Iceberg table+spark.sql("""+ CREATE TABLE IF NOT EXISTS analytics.events (+ event_id BIGINT,+ user_id BIGINT,+ event_name STRING,+ event_timestamp TIMESTAMP,+ properties STRING+ )+ USING iceberg+""")++print("✓ Created table: analytics.events")+```++## Writing data++```python+# Insert data into the table+spark.sql("""+ INSERT INTO analytics.events (event_id, user_id, event_name, event_timestamp, properties)+ VALUES+ (1, 101, 'login', TIMESTAMP '2024-01-15 10:30:00', '{"browser":"chrome"}'),+ (2, 102, 'view_product', TIMESTAMP '2024-01-15 10:35:00', '{"product_id":"123"}'),+ (3, 101, 'logout', TIMESTAMP '2024-01-15 10:40:00', '{}'),+ (4, 103, 'purchase', TIMESTAMP '2024-01-15 10:45:00', '{"amount":99.99}')+""")++print("✓ Inserted 4 rows into analytics.events")+```++## Reading data++```python+# Read the entire table+result_df = spark.sql("SELECT * FROM analytics.events")+result_df.show(truncate=False)++# Apply filters+filtered_df = spark.sql("""+ SELECT event_id, user_id, event_name+ FROM analytics.events+ WHERE event_name = 'login'+""")+filtered_df.show()++# Aggregations+summary_df = spark.sql("""+ SELECT+ event_name,+ COUNT(*) as event_count,+ COUNT(DISTINCT user_id) as unique_users+ FROM analytics.events+ GROUP BY event_name+ ORDER BY event_count DESC+""")+summary_df.show()+```++## Advanced operations++### Working with dataframes++```python+# Read as DataFrame+events_df = spark.read.format("iceberg").load("analytics.events")++# Apply Spark transformations+from pyspark.sql.functions import count, col, year, month++# Monthly event counts+monthly_events = events_df \+ .withColumn("month", month(col("event_timestamp"))) \+ .withColumn("year", year(col("event_timestamp"))) \+ .groupBy("year", "month", "event_name") \+ .agg(count("event_id").alias("count")) \+ .orderBy("year", "month")++monthly_events.show()+```++### Joining tables++```python+# Create another table+spark.sql("""+ CREATE TABLE IF NOT EXISTS analytics.users (+ user_id BIGINT,+ username STRING,+ email STRING+ )+ USING iceberg+""")++spark.sql("""+ INSERT INTO analytics.users VALUES+ (101, 'alice', '[email protected]'),+ (102, 'bob', '[email protected]'),+ (103, 'charlie', '[email protected]')+""")++# Join events with users+joined_df = spark.sql("""+ SELECT+ e.event_id,+ e.event_name,+ u.username,+ u.email,+ e.event_timestamp+ FROM analytics.events e+ JOIN analytics.users u ON e.user_id = u.user_id+ ORDER BY e.event_timestamp+""")++joined_df.show(truncate=False)+```++### Exporting results++```python+# Export to Parquet+spark.sql("""+ SELECT event_name, COUNT(*) as count+ FROM analytics.events+ GROUP BY event_name+""").write \+ .mode("overwrite") \+ .parquet("/tmp/event_summary.parquet")++# Export to CSV+spark.sql("""+ SELECT *+ FROM analytics.events+ WHERE event_timestamp > TIMESTAMP '2024-01-15 10:30:00'+""").write \+ .mode("overwrite") \+ .option("header", "true") \+ .csv("/tmp/recent_events.csv")++print("✓ Results exported")+```++## Performance best practices++- **Partition tables** - Partition large tables by date or region for faster queries+- **Select columns** - Only select columns you need to reduce I/O+- **Use filters early** - Apply WHERE clauses to reduce data processed+- **Cache frequently accessed tables** - Use `spark.catalog.cacheTable()` for tables accessed multiple times+- **Cluster mode** - Use cluster mode for production workloads instead of local mode++## Complete example: Data processing pipeline++```python+from pyspark.sql import SparkSession+from pyspark.sql.functions import col, year, month, count++# Setup (see Basic Setup section above)+spark = SparkSession.builder \+ .master("local[*]") \+ .appName("SupabaseAnalytics") \+ .config("spark.sql.defaultCatalog", "supabase") \+ # ... (add all config from Basic Setup)+ .getOrCreate()++# Step 1: Read raw events+raw_events = spark.sql("SELECT * FROM analytics.events")++# Step 2: Transform and aggregate+monthly_summary = raw_events \+ .withColumn("month", month(col("event_timestamp"))) \+ .withColumn("year", year(col("event_timestamp"))) \+ .groupBy("year", "month", "event_name") \+ .agg(count("event_id").alias("total_events"))++# Step 3: Save results+monthly_summary.write \+ .mode("overwrite") \+ .option("path", "analytics.monthly_summary") \+ .saveAsTable("analytics.monthly_summary")++print("✓ Pipeline completed")+monthly_summary.show()+```++## Next steps++- [Query with Postgres](/docs/guides/storage/analytics/query-with-postgres)+- [Connect with PyIceberg](/docs/guides/storage/analytics/examples/pyiceberg)+- [Explore with DuckDB](/docs/guides/storage/analytics/examples/duckdb)diff --git a/apps/docs/content/guides/storage/analytics/examples/duckdb.mdx b/apps/docs/content/guides/storage/analytics/examples/duckdb.mdxnew file mode 100644index 00000000000..e622c94d0d2--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/examples/duckdb.mdx@@ -0,0 +1,158 @@+---+title: 'DuckDB'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++DuckDB is a high-performance SQL database system optimized for analytical workloads. It can directly query Iceberg tables stored in your analytics buckets, making it ideal for data exploration and complex analytical queries.++## Installation++Install DuckDB and the Iceberg extension:++```bash+pip install duckdb duckdb-iceberg+```++## Connecting to Analytics buckets++Here's a complete example of connecting to your Supabase analytics bucket and querying Iceberg tables:++```python+import duckdb+import os++# Configuration+PROJECT_REF = "your-project-ref"+WAREHOUSE = "your-analytics-bucket-name"+SERVICE_KEY = "your-service-key"++# S3 credentials+S3_ACCESS_KEY = "your-access-key"+S3_SECRET_KEY = "your-secret-key"+S3_REGION = "us-east-1"++# Construct endpoints+S3_ENDPOINT = f"https://{PROJECT_REF}.supabase.co/storage/v1/s3"+CATALOG_URI = f"https://{PROJECT_REF}.supabase.co/storage/v1/iceberg"++# Initialize DuckDB connection+conn = duckdb.connect(":memory:")++# Install and load the Iceberg extension+conn.install_extension("iceberg")+conn.load_extension("iceberg")++# Configure Iceberg catalog with Supabase credentials+conn.execute(f"""+ CREATE SECRET (+ TYPE S3,+ KEY_ID '{S3_ACCESS_KEY}',+ SECRET '{S3_SECRET_KEY}',+ REGION '{S3_REGION}',+ ENDPOINT '{S3_ENDPOINT}',+ URL_STYLE 'virtual'+ );+""")++# Configure the REST catalog+conn.execute(f"""+ ATTACH 'iceberg://{CATALOG_URI}' AS iceberg_catalog+ (+ TYPE ICEBERG_REST,+ WAREHOUSE '{WAREHOUSE}',+ TOKEN '{SERVICE_KEY}'+ );+""")++# Query your Iceberg tables+result = conn.execute("""+ SELECT *+ FROM iceberg_catalog.default.events+ LIMIT 10+""").fetchall()++for row in result:+ print(row)++# Complex aggregation example+analytics = conn.execute("""+ SELECT+ event_name,+ COUNT(*) as event_count,+ COUNT(DISTINCT user_id) as unique_users+ FROM iceberg_catalog.default.events+ GROUP BY event_name+ ORDER BY event_count DESC+""").fetchdf()++print(analytics)+```++## Key features with DuckDB++### Efficient data exploration++DuckDB's lazy evaluation means it only scans the data you need:++```python+# This only reads the columns you select+events = conn.execute("""+ SELECT event_id, event_name, event_timestamp+ FROM iceberg_catalog.default.events+ WHERE event_timestamp > NOW() - INTERVAL '7 days'+""").fetchdf()+```++### Converting to Pandas++Convert results to Pandas DataFrames for further analysis:++```python+df = conn.execute("""+ SELECT *+ FROM iceberg_catalog.default.events+""").fetchdf()++# Use pandas for visualization or further processing+print(df.describe())+```++### Exporting results++Save your analytical results to various formats:++```python+# Export to Parquet+conn.execute("""+ COPY (+ SELECT * FROM iceberg_catalog.default.events+ ) TO 'results.parquet'+""")++# Export to CSV+conn.execute("""+ COPY (+ SELECT event_name, COUNT(*) as count+ FROM iceberg_catalog.default.events+ GROUP BY event_name+ ) TO 'summary.csv' (FORMAT CSV, HEADER true)+""")+```++## Best practices++- **Connection pooling** - Reuse connections for multiple queries+- **Partition pruning** - Filter by partition columns to improve query performance+- **Column selection** - Only select columns you need to reduce I/O+- **Limit results** - Use LIMIT during exploration to avoid processing large datasets++## Next steps++- [Query with Postgres](/docs/guides/storage/analytics/query-with-postgres)+- [Connect with PyIceberg](/docs/guides/storage/analytics/examples/pyiceberg)+- [Analyze with Apache Spark](/docs/guides/storage/analytics/examples/apache-spark)diff --git a/apps/docs/content/guides/storage/analytics/examples/pyiceberg.mdx b/apps/docs/content/guides/storage/analytics/examples/pyiceberg.mdxnew file mode 100644index 00000000000..200d39321cc--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/examples/pyiceberg.mdx@@ -0,0 +1,223 @@+---+title: 'PyIceberg'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++PyIceberg is a Python client for Apache Iceberg that enables programmatic interaction with Iceberg tables. Use it to create, read, update, and delete data in your analytics buckets.++## Installation++```bash+pip install pyiceberg pyarrow+```++## Basic setup++Here's a complete example showing how to connect to your Supabase analytics bucket and perform operations:++```python+from pyiceberg.catalog import load_catalog+import pyarrow as pa+import datetime++# Configuration - Update with your Supabase credentials+PROJECT_REF = "your-project-ref"+WAREHOUSE = "your-analytics-bucket-name"+SERVICE_KEY = "your-service-key"++# S3 credentials from Project Settings > Storage+S3_ACCESS_KEY = "your-access-key"+S3_SECRET_KEY = "your-secret-key"+S3_REGION = "us-east-1"++# Construct Supabase endpoints+S3_ENDPOINT = f"https://{PROJECT_REF}.supabase.co/storage/v1/s3"+CATALOG_URI = f"https://{PROJECT_REF}.supabase.co/storage/v1/iceberg"++# Load the Iceberg REST Catalog+catalog = load_catalog(+ "supabase-analytics",+ type="rest",+ warehouse=WAREHOUSE,+ uri=CATALOG_URI,+ token=SERVICE_KEY,+ **{+ "py-io-impl": "pyiceberg.io.pyarrow.PyArrowFileIO",+ "s3.endpoint": S3_ENDPOINT,+ "s3.access-key-id": S3_ACCESS_KEY,+ "s3.secret-access-key": S3_SECRET_KEY,+ "s3.region": S3_REGION,+ "s3.force-virtual-addressing": False,+ },+)++print("✓ Successfully connected to Iceberg catalog")+```++## Creating tables++```python+# Create a namespace for organization+catalog.create_namespace_if_not_exists("analytics")++# Define the schema for your Iceberg table+schema = pa.schema([+ pa.field("event_id", pa.int64()),+ pa.field("user_id", pa.int64()),+ pa.field("event_name", pa.string()),+ pa.field("event_timestamp", pa.timestamp("ms")),+ pa.field("properties", pa.string()),+])++# Create the table+table = catalog.create_table_if_not_exists(+ ("analytics", "events"),+ schema=schema+)++print("✓ Created table: analytics.events")+```++## Writing data++```python+import datetime++# Prepare your data+current_time = datetime.datetime.now()+data = pa.table({+ "event_id": [1, 2, 3, 4, 5],+ "user_id": [101, 102, 101, 103, 102],+ "event_name": ["login", "view_product", "logout", "purchase", "login"],+ "event_timestamp": [current_time] * 5,+ "properties": [+ '{"browser":"chrome"}',+ '{"product_id":"123"}',+ '{}',+ '{"amount":99.99}',+ '{"browser":"firefox"}'+ ],+})++# Append data to the table+table.append(data)+print("✓ Appended 5 rows to analytics.events")+```++## Reading data++```python+# Scan the entire table+scan_result = table.scan().to_pandas()+print(f"Total rows: {len(scan_result)}")+print(scan_result.head())++# Query with filters+filtered = table.scan(+ filter="event_name = 'login'"+).to_pandas()+print(f"Login events: {len(filtered)}")++# Select specific columns+selected = table.scan(+ selected_fields=["user_id", "event_name", "event_timestamp"]+).to_pandas()+print(selected.head())+```++## Advanced operations++### Listing tables and namespaces++```python+# List all namespaces+namespaces = catalog.list_namespaces()+print("Namespaces:", namespaces)++# List tables in a namespace+tables = catalog.list_tables("analytics")+print("Tables in analytics:", tables)++# Get table metadata+table_metadata = catalog.load_table(("analytics", "events"))+print("Schema:", table_metadata.schema())+print("Partitions:", table_metadata.partitions())+```++### Handling errors++```python+try:+ # Attempt to load a table+ table = catalog.load_table(("analytics", "nonexistent"))+except Exception as e:+ print(f"Error loading table: {e}")++# Check if table exists before creating+namespace = "analytics"+table_name = "events"++try:+ existing_table = catalog.load_table((namespace, table_name))+ print(f"Table already exists")+except Exception:+ print(f"Table does not exist, creating...")+ table = catalog.create_table((namespace, table_name), schema=schema)+```++## Performance tips++- **Batch writes** - Insert data in batches rather than row-by-row for better performance+- **Partition strategies** - Use partitioning for large tables to improve query performance+- **Schema evolution** - PyIceberg supports schema changes without rewriting data+- **Data format** - Use Parquet for efficient columnar storage++## Complete example: ETL pipeline++```python+from pyiceberg.catalog import load_catalog+import pyarrow as pa+import pandas as pd++# Setup (see Basic Setup section above)+catalog = load_catalog(...)++# Step 1: Create analytics namespace+catalog.create_namespace_if_not_exists("warehouse")++# Step 2: Define table schema+schema = pa.schema([+ pa.field("id", pa.int64()),+ pa.field("name", pa.string()),+ pa.field("created_at", pa.timestamp("ms")),+])++# Step 3: Create table+table = catalog.create_table_if_not_exists(+ ("warehouse", "products"),+ schema=schema+)++# Step 4: Load data from CSV or database+df = pd.read_csv("products.csv")+data = pa.Table.from_pandas(df)++# Step 5: Write to analytics bucket+table.append(data)+print(f"✓ Loaded {len(data)} products to warehouse.products")++# Step 6: Verify+result = table.scan().to_pandas()+print(result.describe())+```++## Next steps++- [Query with Postgres](/docs/guides/storage/analytics/query-with-postgres)+- [Analyze with Apache Spark](/docs/guides/storage/analytics/examples/apache-spark)+- [Explore with DuckDB](/docs/guides/storage/analytics/examples/duckdb)diff --git a/apps/docs/content/guides/storage/analytics/introduction.mdx b/apps/docs/content/guides/storage/analytics/introduction.mdxindex 0f4249efe97..9c15769def8 100644--- a/apps/docs/content/guides/storage/analytics/introduction.mdx+++ b/apps/docs/content/guides/storage/analytics/introduction.mdx@@ -1,24 +1,34 @@---title: 'Analytics Buckets'-subtitle: ''+subtitle: 'Store large datasets for analytics and reporting.'----<Admonition type="caution">+<Admonition type="caution" title="This feature is in alpha">-This feature is in **Private Alpha**. API stability and backward compatibility are not guaranteed at this stage. Reach out from this [Form](https://forms.supabase.com/analytics-buckets) to request access+Expect rapid changes, limited features, and possible breaking updates. [share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.</Admonition>-**Analytics Buckets** are designed for analytical workflows on large datasets without impacting your main database.+Analytics buckets enable analytical workflows on large-scale datasets while keeping your primary database optimized for transactional operations.-Postgres tables are optimized for handling real-time, transactional workloads with frequent inserts, updates, deletes and low-latency queries. **Analytical workloads** have very different requirements: processing large volumes of historical data, running complex queries and aggregations, minimizing storage costs, and ensuring these analytical queries do not interfere with the production traffic.+## Why Analytics buckets?-**Analytics Buckets** address these requirements using [Apache Iceberg](https://iceberg.apache.org/), an open-table format for managing large analytical datasets efficiently.+Postgres tables are purpose-built for transactional workloads with frequent inserts, updates, deletes, and low-latency queries. Analytical workloads have fundamentally different requirements:-Analytics Buckets are ideal for-• Data warehousing and business intelligence-• Historical data archiving-• Periodically refreshed real-time analytics-• Complex analytical queries over large datasets+- Processing large volumes of historical data+- Running complex queries and aggregations+- Minimizing storage costs+- Preventing analytical queries from impacting production traffic-By separating transactional and analytical workloads, Supabase makes it easy to build scalable analytics pipelines without impacting your primary Postgres performance.+Analytics buckets address these requirements using [Apache Iceberg](https://iceberg.apache.org/), an open-table format specifically designed for efficient management of large analytical datasets.++## Ideal use cases++Analytics buckets are perfect for:++- **Data warehousing and business intelligence** - Build scalable data warehouses for BI tools+- **Historical data archiving** - Retain large volumes of historical data cost-effectively+- **Periodically refreshed analytics** - Maintain near real-time analytical views+- **Complex analytical queries** - Execute sophisticated aggregations and joins over large datasets++By separating transactional and analytical workloads, Supabase lets you build scalable analytics pipelines without compromising your primary Postgres performance.diff --git a/apps/docs/content/guides/storage/analytics/limits.mdx b/apps/docs/content/guides/storage/analytics/limits.mdxindex 0eac0b0f57c..3e4ca58b948 100644--- a/apps/docs/content/guides/storage/analytics/limits.mdx+++ b/apps/docs/content/guides/storage/analytics/limits.mdx@@ -3,21 +3,16 @@ title: 'Analytics Buckets Limits'subtitle: ''----<Admonition type="caution">+<Admonition type="caution" title="This feature is in alpha">-This feature is in **Private Alpha**. API stability and backward compatibility are not guaranteed at this stage. Reach out from this [Form](https://forms.supabase.com/analytics-buckets) to request access+Expect rapid changes, limited features, and possible breaking updates. [share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.</Admonition>-The following default limits are applied when this feature is in the private alpha stage, they can be adjusted on a case-by-case basis:+The following default limits are applied when this feature is in the alpha stage, they can be adjusted on a case-by-case basis:| **Category** | **Limit** || --------------------------------------- | --------- |-| Number of Analytics Buckets per project | 2 |+| Number of analytics buckets per project | 2 || Number of namespaces per bucket | 10 || Number of tables per namespace | 10 |--## Pricing--Analytics Buckets are Free to use during the Private Alpha phase,-however, you'll still be charged for the underlying egress.diff --git a/apps/docs/content/guides/storage/analytics/pricing.mdx b/apps/docs/content/guides/storage/analytics/pricing.mdxnew file mode 100644index 00000000000..f9c45a45b7b--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/pricing.mdx@@ -0,0 +1,12 @@+---+title: 'Analytics Buckets Pricing'+subtitle: ''+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Analytics buckets are **free** to use during the alpha phase. You will still be charged for the underlying egress.diff --git a/apps/docs/content/guides/storage/analytics/query-with-postgres.mdx b/apps/docs/content/guides/storage/analytics/query-with-postgres.mdxnew file mode 100644index 00000000000..7ebcefca75e--- /dev/null+++ b/apps/docs/content/guides/storage/analytics/query-with-postgres.mdx@@ -0,0 +1,74 @@+---+title: 'Query with PostgreSQL'+subtitle: 'Query analytics bucket data directly from PostgreSQL using SQL.'+---++Once your data flows into an analytics bucket—either via the [ETL Replication Pipeline](/docs/guides/storage/analytics/etl) or custom pipelines—you can query it directly from Postgres using standard SQL.++This is made possible by the [Iceberg Foreign Data Wrapper](/docs/guides/database/extensions/wrappers/iceberg), which creates a bridge between your Postgres database and Iceberg tables.++## Setup overview++You have two options to enable querying:++1. **Dashboard UI** (recommended) - Streamlined setup through the Supabase Dashboard+2. **Manual installation** - Install the wrapper using SQL and configuration++## Installing via Dashboard UI++The dashboard provides the easiest setup experience:++1. Navigate to your **Analytics Bucket** page in the Supabase Dashboard.+2. Locate the namespace you want to query and click **Query with Postgres**.++<Image+ alt="Query with PostgreSQL button on analytics bucket page"+ src="/docs/img/storage/query-analytics-with-postgres.png"+/>++3. Enter the **Postgres schema** where you want to create the foreign tables.++<Image+ alt="Select destination PostgreSQL schema"+ src="/docs/img/storage/query-analytics-schema-name.png"+/>++4. Click **Connect**. The wrapper is now configured.++## Querying your data++Once the foreign data wrapper is installed, you can query your Iceberg tables using standard SQL:++```sql+select *+from schema_name.table_name+limit 100;+```++### Common query examples++Get the latest events:++```sql+select event_id, event_name, event_timestamp+from analytics.events+order by event_timestamp desc+limit 1000;+```++Join with transactional data:++```sql+SELECT+ e.event_id,+ e.event_name,+ u.user_email+FROM analytics.events e+JOIN public.users u ON e.user_id = u.id+WHERE e.event_timestamp > NOW() - INTERVAL '7 days'+LIMIT 100;+```++## Manual installation++For advanced use cases, you can manually install and configure the Iceberg Foreign Data Wrapper. See the [Iceberg Foreign Data Wrapper documentation](/docs/guides/database/extensions/wrappers/iceberg) for detailed instructions.diff --git a/apps/docs/content/guides/storage/management/pricing.mdx b/apps/docs/content/guides/storage/pricing.mdxsimilarity index 100%rename from apps/docs/content/guides/storage/management/pricing.mdxrename to apps/docs/content/guides/storage/pricing.mdxdiff --git a/apps/docs/content/guides/storage/vector/creating-vector-buckets.mdx b/apps/docs/content/guides/storage/vector/creating-vector-buckets.mdxnew file mode 100644index 00000000000..389cb222380--- /dev/null+++ b/apps/docs/content/guides/storage/vector/creating-vector-buckets.mdx@@ -0,0 +1,85 @@+---+title: 'Creating Vector Buckets'+subtitle: 'Set up vector buckets and indexes using the dashboard or JavaScript SDK.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Vector buckets organize your vector data into logical units. Within each bucket, you create indexes that define how vectors are stored and searched based on their dimensions and distance metrics.++## Creating a Vector bucket++You can create vector buckets using either the Supabase Dashboard or the JavaScript SDK.++### Using the Supabase Dashboard++1. Navigate to the **Storage** section in the Supabase Dashboard.+2. Click **Create Bucket**.+3. Enter a name for your bucket (e.g., `embeddings` or `semantic-search`).+4. Select **Vector Bucket** as the bucket type.+5. Click **Create**.++Your vector bucket is now ready. The next step is to create indexes within it.++### Using the JavaScript SDK++```typescript+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++// Create a vector bucket+await supabase.storage.vectors.createBucket('embeddings')++console.log('✓ Vector bucket created: embeddings')+```++## Creating indexes++Indexes organize vectors within a bucket with consistent dimensions and distance metrics. For comprehensive index management documentation, see [Working with Vector Indexes](/docs/guides/storage/vector/working-with-indexes).++### Quick start: Creating an index via Dashboard++1. Open your vector bucket.+2. Click **Create Index**.+3. Enter an index name (e.g., `documents-openai`).+4. Set the dimension matching your embeddings (e.g., `1536` for OpenAI's text-embedding-3-small).+5. Select the distance metric (`cosine`, `euclidean`, or `l2`).+6. Click **Create**.++### Quick start: Creating an index via JavaScript SDK++```typescript+const bucket = supabase.storage.vectors.from('embeddings')++// Create an index+await bucket.createIndex({+ indexName: 'documents-openai',+ dataType: 'float32',+ dimension: 1536,+ distanceMetric: 'cosine',+})++console.log('✓ Index created: documents-openai')+```++### Key details++- **Dimension** must match your embedding model (e.g., 1536 for OpenAI)+- **Distance metric** (`cosine`, `euclidean`, or `l2`) is immutable after creation+- **Maximum indexes per bucket**: 10+- **Maximum batch size**: 500 vectors per operation++For detailed information on distance metrics, embedding dimensions, managing multiple indexes, and advanced index operations, see [Working with Vector Indexes](/docs/guides/storage/vector/working-with-indexes).++## Next steps++After creating your bucket and indexes, you can:++- [Store vectors](/docs/guides/storage/vector/storing-vectors)+- [Query vectors with similarity search](/docs/guides/storage/vector/querying-vectors)+- [Explore vector bucket limits](/docs/guides/storage/vector/limits)diff --git a/apps/docs/content/guides/storage/vector/introduction.mdx b/apps/docs/content/guides/storage/vector/introduction.mdxnew file mode 100644index 00000000000..bb08e7fd46c--- /dev/null+++ b/apps/docs/content/guides/storage/vector/introduction.mdx@@ -0,0 +1,54 @@+---+title: 'Vector Buckets'+subtitle: 'Store, index, and query vector embeddings at scale with similarity search.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Vector buckets enable efficient storage and similarity search of vector embeddings. Built on S3-compatible storage, they provide high-performance semantic search capabilities for AI and machine learning applications.++## What are Vector buckets?++Vector buckets are specialized storage containers optimized for vector data. Unlike traditional databases optimized for transactional queries, vector buckets use specialized indexing and distance metrics to perform fast similarity searches across millions of embeddings.++Each vector bucket contains:++- **Indexes** - Organized collections of vectors with consistent dimensions and distance metrics+- **Vectors** - Embeddings with associated metadata for filtering and enrichment+- **Metadata** - Additional context about vectors (text, tags, IDs, etc.)++## Key features++- **Similarity Search** - Find semantically similar vectors using cosine, euclidean, or L2 distance metrics+- **Metadata Filtering** - Filter results by associated metadata before/after similarity search+- **Batch Operations** - Insert, update, and query up to 500 vectors per request+- **Scalable Storage** - Store millions of vectors in a single index+- **S3 Native** - Built on proven S3 infrastructure for reliability and durability++## Ideal use cases++Vector buckets excel at:++- **Semantic Search** - Find documents or images similar to a query+- **Recommendation Systems** - Suggest products, content, or connections based on embeddings+- **Clustering & Anomaly Detection** - Group similar items or identify outliers+- **Image Search** - Retrieve visually similar images from large catalogs+- **RAG (Retrieval-Augmented Generation)** - Find relevant context for LLM queries+- **Personalization** - Recommend tailored content based on user embeddings++## How Vector buckets work++1. **Create a bucket** to organize your vector data+2. **Create indexes** within the bucket with specified dimensions and distance metrics+3. **Store vectors** with embeddings and optional metadata+4. **Query vectors** using similarity search to find nearest neighbors++The system automatically handles indexing and optimization, making searches fast and reliable even with millions of vectors.++## Next steps++Get started by learning how to [create vector buckets](/docs/guides/storage/vector/creating-vector-buckets) or dive into [storing vectors](/docs/guides/storage/vector/storing-vectors).diff --git a/apps/docs/content/guides/storage/vector/limits.mdx b/apps/docs/content/guides/storage/vector/limits.mdxnew file mode 100644index 00000000000..0b0883367af--- /dev/null+++ b/apps/docs/content/guides/storage/vector/limits.mdx@@ -0,0 +1,21 @@+---+title: 'Vector Bucket Limits'+subtitle: 'Understanding capacity, quotas, and billing for vector buckets.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Vector buckets have default limits during the alpha phase. These limits are designed to ensure fair resource allocation and can be adjusted on a case-by-case basis for production workloads.++## Storage limits++| Limit | Value | Notes |+| ----------------------- | ------------ | ----------------------------------------------------- |+| **Buckets per project** | 10 | Maximum number of vector buckets per Supabase project |+| **Indexes per bucket** | 10 | Maximum number of indexes per bucket |+| **Vector dimensions** | Max 4096 | Maximum dimension size for embeddings |+| **Batch size** | 1000 vectors | Maximum vectors per single insert/update request |diff --git a/apps/docs/content/guides/storage/vector/querying-vectors.mdx b/apps/docs/content/guides/storage/vector/querying-vectors.mdxnew file mode 100644index 00000000000..e9038012837--- /dev/null+++ b/apps/docs/content/guides/storage/vector/querying-vectors.mdx@@ -0,0 +1,489 @@+---+title: 'Querying Vectors'+subtitle: 'Perform similarity search and retrieve vectors using JavaScript SDK or PostgreSQL.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Vector similarity search finds vectors most similar to a query vector using distance metrics. You can query vectors using the JavaScript SDK or directly from Postgres using SQL.++## Basic similarity search++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++const index = supabase.storage.vectors.from('embeddings').index('documents-openai')++// Query with a vector embedding+const { data, error } = await index.queryVectors({+ queryVector: {+ float32: [0.1, 0.2, 0.3 /* ... embedding of 1536 dimensions ... */],+ },+ topK: 5,+ returnDistance: true,+ returnMetadata: true,+})++if (error) {+ console.error('Query failed:', error)+} else {+ // Results are ranked by similarity (lowest distance = most similar)+ data.vectors.forEach((result, rank) => {+ console.log(`${rank + 1}. ${result.metadata?.title}`)+ console.log(` Similarity score: ${result.distance.toFixed(4)}`)+ })+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Setup S3 Vector Wrapper (one-time setup)+-- https://supabase.com/docs/guides/database/extensions/wrappers/s3_vectors++-- Query similar vectors+SELECT+ key,+ metadata->>'title' as title,+ embd_distance(data) as distance,+ (1 - embd_distance(data)) as similarity_score+FROM s3_vectors.documents_openai+WHERE data <==> '[0.1, 0.2, 0.3, /* ... embedding ... */]'::embd+ORDER BY embd_distance(data) ASC+LIMIT 5;+```++</TabPanel>+</Tabs>++## Semantic search++Find documents similar to a query by embedding the query text:++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+import { createClient } from '@supabase/supabase-js'+import OpenAI from 'openai'++const supabase = createClient(...)+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })++async function semanticSearch(query, topK = 5) {+ // Embed the query+ const queryEmbedding = await openai.embeddings.create({+ model: 'text-embedding-3-small',+ input: query+ })++ const queryVector = queryEmbedding.data[0].embedding++ // Search for similar vectors+ const { data, error } = await supabase.storage.vectors+ .from('embeddings')+ .index('documents-openai')+ .queryVectors({+ queryVector: { float32: queryVector },+ topK,+ returnDistance: true,+ returnMetadata: true+ })++ if (error) {+ throw error+ }++ return data.vectors.map((result) => ({+ id: result.key,+ title: result.metadata?.title,+ similarity: 1 - result.distance, // Convert distance to similarity (0-1)+ metadata: result.metadata+ }))+}++// Usage+const results = await semanticSearch('How do I use vector search?')+results.forEach((result) => {+ console.log(`${result.title} (${(result.similarity * 100).toFixed(1)}% similar)`)+})+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Semantic search from PostgreSQL+-- First, generate embedding from external API and store in a variable+-- Then use it to query vectors++WITH query_embedding AS (+ SELECT '[/* ... embedding from OpenAI API ... */]'::embd as embedding+)+SELECT+ key,+ metadata->>'title' as title,+ embd_distance(data) as distance,+ (1 - embd_distance(data)) as similarity_score+FROM s3_vectors.documents_openai,+ query_embedding+WHERE data <==> query_embedding.embedding+ORDER BY embd_distance(data) ASC+LIMIT 5;+```++</TabPanel>+</Tabs>++## Filtered similarity search++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+const index = supabase.storage.vectors+ .from('embeddings')+ .index('documents-openai')++// Search with metadata filter+const { data } = await index.queryVectors({+ queryVector: { float32: [...embedding...] },+ topK: 10,+ filter: {+ // Filter by metadata fields+ category: 'electronics',+ in_stock: true,+ price: { $lte: 500 } // Less than or equal to 500+ },+ returnDistance: true,+ returnMetadata: true+})+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Search with metadata filters+SELECT+ key,+ metadata->>'title' as title,+ (metadata->>'price')::numeric as price,+ embd_distance(data) as distance,+ (1 - embd_distance(data)) as similarity+FROM s3_vectors.documents_openai+WHERE data <==> '[...]'::embd+ AND (metadata->>'category') = 'electronics'+ AND (metadata->>'in_stock')::boolean = true+ AND (metadata->>'price')::numeric <= 500+ORDER BY embd_distance(data) ASC+LIMIT 10;+```++</TabPanel>+</Tabs>++## Retrieving specific vectors++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+const index = supabase.storage.vectors.from('embeddings').index('documents-openai')++const { data, error } = await index.getVectors({+ keys: ['doc-1', 'doc-2', 'doc-3'],+ returnData: true,+ returnMetadata: true,+})++if (!error) {+ data.vectors.forEach((vector) => {+ console.log(`${vector.key}: ${vector.metadata?.title}`)+ })+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Retrieve specific vectors by key+SELECT+ key,+ data as embedding,+ metadata+FROM s3_vectors.documents_openai+WHERE key IN ('doc-1', 'doc-2', 'doc-3');+```++</TabPanel>+</Tabs>++## Listing vectors++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+const index = supabase.storage.vectors.from('embeddings').index('documents-openai')++let nextToken = undefined+let pageCount = 0++do {+ const { data, error } = await index.listVectors({+ maxResults: 100,+ nextToken,+ returnData: false, // Don't return embeddings for faster response+ returnMetadata: true,+ })++ if (error) break++ pageCount+++ console.log(`Page ${pageCount}: ${data.vectors.length} vectors`)++ data.vectors.forEach((vector) => {+ console.log(` - ${vector.key}: ${vector.metadata?.title}`)+ })++ nextToken = data.nextToken+} while (nextToken)+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- List all vectors with pagination+SELECT+ key,+ metadata+FROM s3_vectors.documents_openai+ORDER BY key ASC+LIMIT 100+OFFSET 0;++-- To paginate, increase OFFSET for next page:+-- OFFSET 100 for page 2, OFFSET 200 for page 3, etc.+```++</TabPanel>+</Tabs>++## Hybrid search: Vectors + relational data++Combine similarity search with SQL filtering and joins:++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+async function hybridSearch(queryVector, filters) {+ const index = supabase.storage.vectors.from('embeddings').index('documents-openai')++ // Get similar vectors with filters+ const { data: vectorResults } = await index.queryVectors({+ queryVector: { float32: queryVector },+ topK: 100,+ filter: filters,+ returnDistance: true,+ returnMetadata: true,+ })++ // Get additional details from relational database+ const { data: details } = await supabase+ .from('documents')+ .select('*')+ .in(+ 'id',+ vectorResults.vectors.map((v) => v.metadata?.doc_id)+ )++ // Merge results+ return vectorResults.vectors.map((vector) => {+ const detail = details?.find((d) => d.id === vector.metadata?.doc_id)+ return {+ ...vector,+ ...detail,+ }+ })+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Hybrid search: vectors + relational data join+SELECT+ v.key as vector_id,+ v.metadata->>'title' as vector_title,+ d.id as document_id,+ d.full_text,+ d.author,+ d.created_at,+ embd_distance(v.data) as similarity_score+FROM s3_vectors.documents_openai v+LEFT JOIN public.documents d+ ON v.metadata->>'doc_id' = d.id::text+WHERE v.data <==> '[...]'::embd+ AND embd_distance(v.data) < 0.3 -- High similarity threshold+ AND d.category = 'articles'+ORDER BY embd_distance(v.data) ASC+LIMIT 50;+```++</TabPanel>+</Tabs>++## Real-world examples++### RAG (retrieval-augmented generation)++```typescript+import OpenAI from 'openai'+import { createClient } from '@supabase/supabase-js'++async function retrieveContextForLLM(userQuery) {+ const supabase = createClient(...)+ const openai = new OpenAI()++ // 1. Embed the user query+ const queryEmbedding = await openai.embeddings.create({+ model: 'text-embedding-3-small',+ input: userQuery+ })++ // 2. Retrieve relevant documents+ const { data: vectorResults } = await supabase.storage.vectors+ .from('embeddings')+ .index('documents-openai')+ .queryVectors({+ queryVector: { float32: queryEmbedding.data[0].embedding },+ topK: 5,+ returnMetadata: true+ })++ // 3. Use vectors to augment LLM prompt+ const context = vectorResults.vectors+ .map(v => v.metadata?.content || '')+ .join('\n\n')++ const response = await openai.chat.completions.create({+ model: 'gpt-4',+ messages: [+ {+ role: 'system',+ content: `Use the following context to answer the user's question:\n\n${context}`+ },+ {+ role: 'user',+ content: userQuery+ }+ ]+ })++ return response.choices[0].message.content+}+```++### Product recommendations++```typescript+async function recommendProducts(userEmbedding, topK = 5) {+ const supabase = createClient(...)++ // Find similar products+ const { data } = await supabase.storage.vectors+ .from('embeddings')+ .index('products-openai')+ .queryVectors({+ queryVector: { float32: userEmbedding },+ topK,+ filter: {+ in_stock: true+ },+ returnMetadata: true+ })++ return data.vectors.map((result) => ({+ id: result.metadata?.product_id,+ name: result.metadata?.name,+ price: result.metadata?.price,+ similarity: 1 - result.distance+ }))+}+```++### Filtering before similarity search++```typescript+// Use metadata filters to reduce search scope+const { data } = await index.queryVectors({+ queryVector,+ topK: 100,+ filter: {+ category: 'electronics', // Pre-filter by category+ },+})+```++## Next steps++- [Store vectors](/docs/guides/storage/vector/storing-vectors)+- [Work with vector indexes](/docs/guides/storage/vector/working-with-indexes)+- [Explore vector bucket limits](/docs/guides/storage/vector/limits)diff --git a/apps/docs/content/guides/storage/vector/storing-vectors.mdx b/apps/docs/content/guides/storage/vector/storing-vectors.mdxnew file mode 100644index 00000000000..c3ce2ed43b2--- /dev/null+++ b/apps/docs/content/guides/storage/vector/storing-vectors.mdx@@ -0,0 +1,411 @@+---+title: 'Storing Vectors'+subtitle: 'Insert and update vector embeddings with metadata using the JavaScript SDK or Postgres.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Once you've created a bucket and index, you can start storing vectors. Vectors can include optional metadata for filtering and enrichment during queries.++## Basic vector insertion++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++// Get bucket and index+const bucket = supabase.storage.vectors.from('embeddings')+const index = bucket.index('documents-openai')++// Insert vectors+const { error } = await index.putVectors({+ vectors: [+ {+ key: 'doc-1',+ data: {+ float32: [0.1, 0.2, 0.3 /* ... rest of embedding ... */],+ },+ metadata: {+ title: 'Getting Started with Vector Buckets',+ source: 'documentation',+ },+ },+ {+ key: 'doc-2',+ data: {+ float32: [0.4, 0.5, 0.6 /* ... rest of embedding ... */],+ },+ metadata: {+ title: 'Advanced Vector Search',+ source: 'blog',+ },+ },+ ],+})++if (error) {+ console.error('Error storing vectors:', error)+} else {+ console.log('✓ Vectors stored successfully')+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Setup S3 Vector Wrapper (one-time setup)+-- https://supabase.com/docs/guides/database/extensions/wrappers/s3_vectors++-- Insert vectors into the index+INSERT INTO s3_vectors.documents_openai (key, data, metadata)+VALUES+ (+ 'doc-1',+ '[0.1, 0.2, 0.3, /* ... rest of embedding ... */]'::embd,+ '{"title": "Getting Started with Vector Buckets", "source": "documentation"}'::jsonb+ ),+ (+ 'doc-2',+ '[0.4, 0.5, 0.6, /* ... rest of embedding ... */]'::embd,+ '{"title": "Advanced Vector Search", "source": "blog"}'::jsonb+ );+```++</TabPanel>+</Tabs>++## Storing vectors from Embeddings API++Generate embeddings using an LLM API and store them directly:++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+import { createClient } from '@supabase/supabase-js'+import OpenAI from 'openai'++const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++const openai = new OpenAI({+ apiKey: process.env.OPENAI_API_KEY,+})++// Documents to embed and store+const documents = [+ { id: '1', title: 'How to Train Your AI', content: 'Guide for training models...' },+ { id: '2', title: 'Vector Search Best Practices', content: 'Tips for semantic search...' },+ {+ id: '3',+ title: 'Building RAG Systems',+ content: 'Implementing retrieval-augmented generation...',+ },+]++// Generate embeddings+const embeddings = await openai.embeddings.create({+ model: 'text-embedding-3-small',+ input: documents.map((doc) => doc.content),+})++// Prepare vectors for storage+const vectors = documents.map((doc, index) => ({+ key: doc.id,+ data: {+ float32: embeddings.data[index].embedding,+ },+ metadata: {+ title: doc.title,+ source: 'knowledge_base',+ created_at: new Date().toISOString(),+ },+}))++// Store vectors in batches (max 500 per request)+const bucket = supabase.storage.vectors.from('embeddings')+const vectorIndex = bucket.index('documents-openai')++for (let i = 0; i < vectors.length; i += 500) {+ const batch = vectors.slice(i, i + 500)+ const { error } = await vectorIndex.putVectors({ vectors: batch })++ if (error) {+ console.error(`Error storing batch ${i / 500 + 1}:`, error)+ } else {+ console.log(`✓ Stored batch ${i / 500 + 1} (${batch.length} vectors)`)+ }+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Insert vectors with pre-generated embeddings+INSERT INTO s3_vectors.documents_openai (key, data, metadata)+VALUES+ (+ '1',+ '[0.1, 0.2, 0.3, /* ... rest of embedding ... */]'::embd,+ '{"title": "How to Train Your AI", "source": "knowledge_base", "created_at": "2025-01-01T00:00:00Z"}'::jsonb+ ),+ (+ '2',+ '[0.4, 0.5, 0.6, /* ... rest of embedding ... */]'::embd,+ '{"title": "Vector Search Best Practices", "source": "knowledge_base", "created_at": "2025-01-01T00:00:00Z"}'::jsonb+ ),+ (+ '3',+ '[0.7, 0.8, 0.9, /* ... rest of embedding ... */]'::embd,+ '{"title": "Building RAG Systems", "source": "knowledge_base", "created_at": "2025-01-01T00:00:00Z"}'::jsonb+ );+```++</TabPanel>+</Tabs>++## Updating vectors++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+const index = bucket.index('documents-openai')++// Update a vector (same key)+const { error } = await index.putVectors({+ vectors: [+ {+ key: 'doc-1',+ data: {+ float32: [0.15, 0.25, 0.35 /* ... updated embedding ... */],+ },+ metadata: {+ title: 'Getting Started with Vector Buckets - Updated',+ updated_at: new Date().toISOString(),+ },+ },+ ],+})++if (!error) {+ console.log('✓ Vector updated successfully')+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Update a vector (delete and re-insert)+DELETE FROM s3_vectors.documents_openai WHERE key = 'doc-1';++INSERT INTO s3_vectors.documents_openai (key, data, metadata)+VALUES (+ 'doc-1',+ '[0.15, 0.25, 0.35, /* ... updated embedding ... */]'::embd,+ '{"title": "Getting Started with Vector Buckets - Updated", "updated_at": "2025-01-01T00:00:00Z"}'::jsonb+);+```++</TabPanel>+</Tabs>++## Deleting vectors++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="javascript"+ queryGroup="language"+>+<TabPanel id="javascript" label="JavaScript">++```typescript+const index = bucket.index('documents-openai')++// Delete specific vectors+const { error } = await index.deleteVectors({+ keys: ['doc-1', 'doc-2'],+})++if (!error) {+ console.log('✓ Vectors deleted successfully')+}+```++</TabPanel>++<TabPanel id="sql" label="SQL (via S3 Vector Wrapper)">++```sql+-- Delete vectors by key+DELETE FROM s3_vectors.documents_openai+WHERE key IN ('doc-1', 'doc-2');+```++</TabPanel>+</Tabs>++## Metadata best practices++Metadata makes vectors more useful by enabling filtering and context:++```typescript+const vectors = [+ {+ key: 'product-001',+ data: { float32: [...] },+ metadata: {+ product_id: 'prod-001',+ category: 'electronics',+ price: 299.99,+ in_stock: true,+ tags: ['laptop', 'portable'],+ description: 'High-performance ultrabook'+ }+ },+ {+ key: 'product-002',+ data: { float32: [...] },+ metadata: {+ product_id: 'prod-002',+ category: 'electronics',+ price: 99.99,+ in_stock: true,+ tags: ['headphones', 'wireless'],+ description: 'Noise-cancelling wireless headphones'+ }+ }+]++const { error } = await index.putVectors({ vectors })+```++### Metadata field guidelines++- **Keep it lightweight** - Metadata is returned with query results, so large values increase response size+- **Use consistent types** - Store the same field with consistent data types across vectors+- **Index key fields** - Mark fields you'll filter by to improve query performance+- **Avoid nested objects** - While supported, flat structures are easier to filter++## Batch processing large datasets++For storing large numbers of vectors efficiently:++```typescript+import { createClient } from '@supabase/supabase-js'+import fs from 'fs'++const supabase = createClient(...)+const index = supabase.storage.vectors+ .from('embeddings')+ .index('documents-openai')++// Read embeddings from file+const embeddingsFile = fs.readFileSync('embeddings.jsonl', 'utf-8')+const lines = embeddingsFile.split('\n').filter(line => line.trim())++const vectors = lines.map((line, idx) => {+ const { key, embedding, metadata } = JSON.parse(line)+ return {+ key,+ data: { float32: embedding },+ metadata+ }+})++// Process in batches+const BATCH_SIZE = 500+let processed = 0++for (let i = 0; i < vectors.length; i += BATCH_SIZE) {+ const batch = vectors.slice(i, i + BATCH_SIZE)++ try {+ const { error } = await index.putVectors({ vectors: batch })++ if (error) throw error++ processed += batch.length+ console.log(`Progress: ${processed}/${vectors.length}`)+ } catch (error) {+ console.error(`Batch failed at offset ${i}:`, error)+ // Optionally implement retry logic+ }+}++console.log('✓ All vectors stored successfully')+```++## Performance optimization++### Batch operations++Always use batch operations for better performance:++```typescript+// ❌ Inefficient - Multiple requests+for (const vector of vectors) {+ await index.putVectors({ vectors: [vector] })+}++// ✅ Efficient - Single batch operation+await index.putVectors({ vectors })+```++### Metadata considerations++Keep metadata concise:++```typescript+// ❌ Large metadata+metadata: {+ full_document_text: 'Very long document content...',+ detailed_analysis: { /* large object */ }+}++// ✅ Lean metadata+metadata: {+ doc_id: 'doc-123',+ category: 'news',+ summary: 'Brief summary'+}+```++## Next steps++- [Query vectors with similarity search](/docs/guides/storage/vector/querying-vectors)+- [Work with vector indexes](/docs/guides/storage/vector/working-with-indexes)+- [Explore vector bucket limits](/docs/guides/storage/vector/limits)diff --git a/apps/docs/content/guides/storage/vector/working-with-indexes.mdx b/apps/docs/content/guides/storage/vector/working-with-indexes.mdxnew file mode 100644index 00000000000..3cf039aea8c--- /dev/null+++ b/apps/docs/content/guides/storage/vector/working-with-indexes.mdx@@ -0,0 +1,213 @@+---+title: 'Working with Vector Indexes'+subtitle: 'Create, manage, and optimize vector indexes for efficient similarity search.'+---++<Admonition type="caution" title="This feature is in alpha">++Expect rapid changes, limited features, and possible breaking updates. [Share feedback](https://github.com/orgs/supabase/discussions/40116) as we refine the experience and expand access.++</Admonition>++Vector indexes organize embeddings within a bucket with consistent dimensions and distance metrics. Each index defines how similarity searches are performed across your vectors.++## Understanding vector indexes++An index specifies:++- **Index Name** - Unique identifier within the bucket+- **Dimension** - Size of vector embeddings (e.g., 1536 for OpenAI)+- **Distance Metric** - Similarity calculation method (cosine, euclidean, or L2)+- **Data Type** - Vector format (currently `float32`)++Think of an index as a table in a traditional database. It has a schema (dimension) and a query strategy (distance metric).++## Creating indexes++### Via Dashboard++1. Open your vector bucket in the Supabase Dashboard.+2. Click **Create Index**.+3. Enter an index name (e.g., `documents-openai`).+4. Set the dimension matching your embeddings (e.g., `1536` for OpenAI's text-embedding-3-small).+5. Select the distance metric (`cosine`, `euclidean`, or `l2`).+6. Click **Create**.++### Via JavaScript SDK++```typescript+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://your-project.supabase.co', 'your-service-key')++const bucket = supabase.storage.vectors.from('embeddings')++// Create an index+const { data, error } = await bucket.createIndex({+ indexName: 'documents-openai',+ dataType: 'float32',+ dimension: 1536,+ distanceMetric: 'cosine',+})++if (error) {+ console.error('Error creating index:', error)+} else {+ console.log('Index created:', data)+}+```++### Choosing the right metric++Most modern embedding models work best with **cosine** distance:++- **OpenAI** (text-embedding-3-small, text-embedding-3-large): Cosine+- **Cohere** (embed-english-v3.0): Cosine+- **Hugging Face** (sentence-transformers): Cosine+- **Google** (text-embedding-004): Cosine+- **Llama 2** embeddings: Cosine or L2++**Tip**: Check your embedding model's documentation for the recommended distance metric.++**Important**: Creating an index with incorrect dimensions will cause insert and query operations to fail.++## Managing multiple indexes++Create multiple indexes for different use cases or embedding models:++```typescript+const bucket = supabase.storage.vectors.from('embeddings')++// Index for OpenAI embeddings+await bucket.createIndex({+ indexName: 'documents-openai',+ dimension: 1536,+ distanceMetric: 'cosine',+ dataType: 'float32',+})++// Index for Cohere embeddings+await bucket.createIndex({+ indexName: 'documents-cohere',+ dimension: 1024,+ distanceMetric: 'cosine',+ dataType: 'float32',+})++// Index for different use case+await bucket.createIndex({+ indexName: 'images-openai',+ dimension: 1536,+ distanceMetric: 'cosine',+ dataType: 'float32',+})++// List all indexes+const { data: indexes } = await bucket.listIndexes()+console.log('All indexes:', indexes)+```++### Use cases for multiple indexes++- **Different embedding models** - Store vectors from OpenAI, Cohere, and local models separately+- **Different domains** - Maintain separate indexes for documents, images, products, etc.+- **A/B testing** - Compare different embedding models side-by-side+- **Multi-language** - Keep language-specific embeddings separate++## Listing and inspecting indexes++### List all indexes in a bucket++```typescript+const bucket = supabase.storage.vectors.from('embeddings')++const { data: indexes, error } = await bucket.listIndexes()++if (!error) {+ indexes?.forEach((index) => {+ console.log(`Index: ${index.name}`)+ console.log(` Dimension: ${index.dimension}`)+ console.log(` Distance: ${index.distanceMetric}`)+ })+}+```++### Get index details++```typescript+const { data: indexDetails, error } = await bucket.getIndex('documents-openai')++if (!error && indexDetails) {+ console.log(`Index: ${indexDetails.name}`)+ console.log(`Created at: ${indexDetails.createdAt}`)+ console.log(`Dimension: ${indexDetails.dimension}`)+ console.log(`Distance metric: ${indexDetails.distanceMetric}`)+}+```++## Deleting indexes++Delete an index to free storage space:++```typescript+const bucket = supabase.storage.vectors.from('embeddings')++const { error } = await bucket.deleteIndex('documents-openai')++if (error) {+ console.error('Error deleting index:', error)+} else {+ console.log('Index deleted successfully')+}+```++### Before deleting an index++**Warning**: Deleting an index is permanent and cannot be undone.++- **Backup important data** - Export vectors before deletion if needed+- **Update applications** - Ensure no code references the deleted index+- **Check dependencies** - Verify no active queries use the index+- **Plan the deletion** - Do this during low-traffic periods++### Immutable properties++Once created, these properties **cannot be changed**:++- **Dimension** - Must create new index with different dimension+- **Distance metric** - Cannot change after creation+- **Data type** - Currently only `float32` supported++### Optimizing index performance++```typescript+// Good - Appropriate batch size+const batch = vectors.slice(0, 250)+await index.putVectors({ vectors: batch })++// Good - Filter metadata before query+const { data } = await index.queryVectors({+ queryVector,+ topK: 5,+ filter: { category: 'electronics' },+})++// Avoid - Single vector inserts+for (const vector of vectors) {+ await index.putVectors({ vectors: [vector] })+}++// Avoid - Returning unnecessary data+const { data } = await index.queryVectors({+ queryVector,+ topK: 1000, // Too many results+ returnData: true, // Include large embeddings+})+```++## Next steps++- [Store vectors in indexes](/docs/guides/storage/vector/storing-vectors)+- [Query vectors for similarity search](/docs/guides/storage/vector/querying-vectors)+- [Understand vector bucket limits](/docs/guides/storage/vector/limits)+- [Create vector buckets](/docs/guides/storage/vector/creating-vector-buckets)diff --git a/apps/docs/public/img/storage/query-analytics-schema-name.png b/apps/docs/public/img/storage/query-analytics-schema-name.pngnew file mode 100644index 00000000000..107ae48a70eBinary files /dev/null and b/apps/docs/public/img/storage/query-analytics-schema-name.png differdiff --git a/apps/docs/public/img/storage/query-analytics-with-postgres.png b/apps/docs/public/img/storage/query-analytics-with-postgres.pngnew file mode 100644index 00000000000..e7e5b1c01a6Binary files /dev/null and b/apps/docs/public/img/storage/query-analytics-with-postgres.png differdiff --git a/apps/studio/components/interfaces/Storage/Storage.constants.ts b/apps/studio/components/interfaces/Storage/Storage.constants.tsindex f38e691985f..9860334c711 100644--- a/apps/studio/components/interfaces/Storage/Storage.constants.ts+++ b/apps/studio/components/interfaces/Storage/Storage.constants.ts@@ -89,5 +89,5 @@ export const BUCKET_TYPES = {docsUrl: `${DOCS_URL}/guides/storage/vectors`,},}-+export const BUCKET_TYPE_KEYS = Object.keys(BUCKET_TYPES) as Array<keyof typeof BUCKET_TYPES>export const DEFAULT_BUCKET_TYPE: keyof typeof BUCKET_TYPES = 'files'diff --git a/packages/config/ui.config.js b/packages/config/ui.config.jsindex 836d8dba4c7..c7cff332eca 100644--- a/packages/config/ui.config.js+++ b/packages/config/ui.config.js@@ -347,10 +347,10 @@ const uiConfig = {'mask-image': 'linear-gradient(to left, white 98%, transparent 100%)',},'input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button':- {- '-webkit-appearance': 'none',- margin: '0',- },+ {+ '-webkit-appearance': 'none',+ margin: '0',+ },})addVariant('data-open-parent', '[data-state="open"] &')addVariant('data-closed-parent', '[data-state="closed"] &')diff --git a/supa-mdx-lint/Rule001HeadingCase.toml b/supa-mdx-lint/Rule001HeadingCase.tomlindex 39a8cb44967..5e559e3a652 100644--- a/supa-mdx-lint/Rule001HeadingCase.toml+++ b/supa-mdx-lint/Rule001HeadingCase.toml@@ -60,9 +60,11 @@ may_uppercase = ["Docker","Drain","Drizzle",+ "DuckDB","Edge Functions?","Editor","Egress",+ "Embeddings API","Enterprise","Enterprise Plan","Events",@@ -148,6 +150,7 @@ may_uppercase = ["OrbStack","OrioleDB","PGAudit",+ "Pandas","PgBouncer","Phoenix","Pro Plan",@@ -227,6 +230,7 @@ may_uppercase = ["Vault","VSCode","Vecs",+ "Vector","Vercel","Vercel Marketplace","Visual Studio Code",diff --git a/supa-mdx-lint/Rule003Spelling.toml b/supa-mdx-lint/Rule003Spelling.tomlindex ed6eace5b1d..bb972d24e21 100644--- a/supa-mdx-lint/Rule003Spelling.toml+++ b/supa-mdx-lint/Rule003Spelling.toml@@ -31,6 +31,7 @@ allow_list = ["BootFailure","[Bb]reakpoints?","[Bb]uilt-ins?",+ "[Cc]atalogs?","[Cc]hangelogs?","[Cc]odebases?","[Cc]odepaths?",@@ -45,6 +46,7 @@ allow_list = ["[Cc]ryptography","[Cc]ryptosystem","[Cc]utover",+ "[Dd]ata[Ff]rames?","[Dd]atasets?","[Dd]atasources?","[Dd]e facto",@@ -52,6 +54,7 @@ allow_list = ["[Dd]evs?","[Dd]iff(s|ing|ed)?","[Dd]ropdown",+ "DuckDB","EarlyDrop","[Ee]nqueues?","[Ee]ntrypoints?",