# Supabase

## Prerequisitos

1. Registra una cuenta en [Supabase](https://supabase.com/)
2. Haz clic en **New project**

<figure><img src="/files/zFfdNXzz24U0zkNiwXqO" alt=""><figcaption></figcaption></figure>

3. Ingresa los campos requeridos

| Nombre del Campo          | Descripción                               |
| ------------------------- | ----------------------------------------- |
| **Name**                  | nombre del proyecto a crear (ej. Flowise) |
| **Database** **Password** | contraseña para tu base de datos postgres |

<figure><img src="/files/PD5t4ASVCEQYnA91N0pq" alt=""><figcaption></figcaption></figure>

4. Haz clic en **Create new project** y espera a que el proyecto termine de configurarse
5. Haz clic en **SQL Editor**

<figure><img src="/files/8BkDQxEIg17YVQQgvXTa" alt=""><figcaption></figcaption></figure>

6. Haz clic en **New query**

<figure><img src="/files/E78heWbA3917Rcmr02ho" alt=""><figcaption></figcaption></figure>

7. Copia y pega la siguiente consulta SQL y ejecútala con `Ctrl + Enter` o haciendo clic en **RUN**. Toma nota del nombre de la tabla y el nombre de la función.

* **Nombre de la tabla**: `documents`
* **Nombre de la consulta**: `match_documents`

```plsql
-- Habilita la extensión pgvector para trabajar con vectores de embeddings
create extension vector;

-- Crea una tabla para almacenar tus documentos
create table documents (
  id bigserial primary key,
  content text, -- corresponde a Document.pageContent
  metadata jsonb, -- corresponde a Document.metadata
  embedding vector(1536) -- 1536 funciona para embeddings de OpenAI, cambiar si es necesario
);

-- Crea una función para buscar documentos
create function match_documents (
  query_embedding vector(1536),
  match_count int DEFAULT null,
  filter jsonb DEFAULT '{}'
) returns table (
  id bigint,
  content text,
  metadata jsonb,
  similarity float
)
language plpgsql
as $$
#variable_conflict use_column
begin
  return query
  select
    id,
    content,
    metadata,
    1 - (documents.embedding <=> query_embedding) as similarity
  from documents
  where metadata @> filter
  order by documents.embedding <=> query_embedding
  limit match_count;
end;
$$;
```

En algunos casos, podrías estar usando [Record Manager](/espanol/documentacion-oficial/integraciones/langchain/record-managers.md) para hacer seguimiento de los upserts y prevenir duplicaciones. Como Record Manager genera un UUID aleatorio para cada embedding, tendrás que cambiar la entidad de la columna id a texto:

```sql
-- Habilita la extensión pgvector para trabajar con vectores de embeddings
create extension vector;

-- Crea una tabla para almacenar tus documentos
create table documents (
  id text primary key, -- CAMBIAR A TEXT
  content text,
  metadata jsonb,
  embedding vector(1536)
);

-- Crea una función para buscar documentos
create function match_documents (
  query_embedding vector(1536),
  match_count int DEFAULT null,
  filter jsonb DEFAULT '{}'
) returns table (
  id text, -- CAMBIAR A TEXT
  content text,
  metadata jsonb,
  similarity float
)
language plpgsql
as $$
#variable_conflict use_column
begin
  return query
  select
    id,
    content,
    metadata,
    1 - (documents.embedding <=> query_embedding) as similarity
  from documents
  where metadata @> filter
  order by documents.embedding <=> query_embedding
  limit match_count;
end;
$$;
```

<figure><img src="/files/unvQ88I2GTdTtnhYrC5N" alt=""><figcaption></figcaption></figure>

## Configuración

1. Haz clic en **Project Settings**

<figure><img src="/files/G7b3hpwr7W8NJxF8WSdB" alt=""><figcaption></figcaption></figure>

2. Obtén tu **Project URL & API Key**

<figure><img src="/files/Hs7XdVlekNolbT75bS4S" alt=""><figcaption></figcaption></figure>

3. Copia y pega cada detalle (*API Key, URL, Table Name, Query Name*) en el nodo **Supabase**

<figure><img src="/files/D3qar2uA0GzsGA5PxXCp" alt="" width="331"><figcaption></figcaption></figure>

4. **Document** puede conectarse con cualquier nodo de la categoría [**Document Loader**](/espanol/documentacion-oficial/integraciones/langchain/document-loaders.md)
5. **Embeddings** puede conectarse con cualquier nodo de la categoría [**Embeddings**](/espanol/documentacion-oficial/integraciones/langchain/embeddings.md)

## Filtrado

Supongamos que tienes diferentes documentos insertados, cada uno especificado con un valor único bajo la clave de metadata `{source}`

<figure><img src="/files/hAXVdusTcXLA3JorbC0J" alt=""><figcaption></figcaption></figure>

Puedes usar filtrado de metadata para consultar metadata específica:

**UI**

<figure><img src="/files/zDrXOJnWi5BFSGNitpo9" alt="" width="232"><figcaption></figcaption></figure>

**API**

```json
"overrideConfig": {
    "supabaseMetadataFilter": {
        "source": "henry"
    }
}
```

## Recursos

* [LangChain JS Supabase](https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabase)
* [Supabase Blog Post](https://supabase.com/blog/openai-embeddings-postgres-vector)
* [Metadata Filtering](https://js.langchain.com/docs/integrations/vectorstores/supabase#metadata-filtering)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flowiseai.com/espanol/documentacion-oficial/integraciones/langchain/vector-stores/supabase.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
