!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

You are viewing the **preview** v0.2 docs. View the **stable** v0.1 docs [here](/v0.1/docs/get_started/introduction/). Leave feedback on the v0.2 docs [here](https://github.com/langchain-ai/langchainjs/discussions/5386).

[

![🦜️🔗 Langchain](/v0.2/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.2/img/brand/wordmark-dark.png)

](/v0.2/)[Integrations](/v0.2/docs/integrations/platforms/)[API Reference](https://v02.api.js.langchain.com)

[More](#)

*   [People](/v0.2/docs/people/)
*   [Community](/v0.2/docs/community)
*   [Tutorials](/v0.2/docs/additional_resources/tutorials)
*   [Contributing](/v0.2/docs/contributing)

[v0.2](#)

*   [v0.2](/v0.2/docs/introduction)
*   [v0.1](https://js.langchain.com/v0.1/docs/get_started/introduction)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Providers](/v0.2/docs/integrations/platforms/)
    
    *   [Providers](/v0.2/docs/integrations/platforms/)
    *   [Anthropic](/v0.2/docs/integrations/platforms/anthropic)
    *   [AWS](/v0.2/docs/integrations/platforms/aws)
    *   [Google](/v0.2/docs/integrations/platforms/google)
    *   [Microsoft](/v0.2/docs/integrations/platforms/microsoft)
    *   [OpenAI](/v0.2/docs/integrations/platforms/openai)
*   [Components](/v0.2/docs/integrations/components)
    
    *   [Chat models](/v0.2/docs/integrations/chat/)
        
    *   [LLMs](/v0.2/docs/integrations/llms/)
        
    *   [Embedding models](/v0.2/docs/integrations/text_embedding)
        
    *   [Document loaders](/v0.2/docs/integrations/document_loaders)
        
    *   [Document transformers](/v0.2/docs/integrations/document_transformers)
        
    *   [Vector stores](/v0.2/docs/integrations/vectorstores)
        
        *   [Memory](/v0.2/docs/integrations/vectorstores/memory)
        *   [AnalyticDB](/v0.2/docs/integrations/vectorstores/analyticdb)
        *   [Astra DB](/v0.2/docs/integrations/vectorstores/astradb)
        *   [Azure AI Search](/v0.2/docs/integrations/vectorstores/azure_aisearch)
        *   [Azure Cosmos DB](/v0.2/docs/integrations/vectorstores/azure_cosmosdb)
        *   [Cassandra](/v0.2/docs/integrations/vectorstores/cassandra)
        *   [Chroma](/v0.2/docs/integrations/vectorstores/chroma)
        *   [ClickHouse](/v0.2/docs/integrations/vectorstores/clickhouse)
        *   [CloseVector](/v0.2/docs/integrations/vectorstores/closevector)
        *   [Cloudflare Vectorize](/v0.2/docs/integrations/vectorstores/cloudflare_vectorize)
        *   [Convex](/v0.2/docs/integrations/vectorstores/convex)
        *   [Couchbase](/v0.2/docs/integrations/vectorstores/couchbase)
        *   [Elasticsearch](/v0.2/docs/integrations/vectorstores/elasticsearch)
        *   [Faiss](/v0.2/docs/integrations/vectorstores/faiss)
        *   [Google Vertex AI Matching Engine](/v0.2/docs/integrations/vectorstores/googlevertexai)
        *   [SAP HANA Cloud Vector Engine](/v0.2/docs/integrations/vectorstores/hanavector)
        *   [HNSWLib](/v0.2/docs/integrations/vectorstores/hnswlib)
        *   [LanceDB](/v0.2/docs/integrations/vectorstores/lancedb)
        *   [Milvus](/v0.2/docs/integrations/vectorstores/milvus)
        *   [Momento Vector Index (MVI)](/v0.2/docs/integrations/vectorstores/momento_vector_index)
        *   [MongoDB Atlas](/v0.2/docs/integrations/vectorstores/mongodb_atlas)
        *   [MyScale](/v0.2/docs/integrations/vectorstores/myscale)
        *   [Neo4j Vector Index](/v0.2/docs/integrations/vectorstores/neo4jvector)
        *   [Neon Postgres](/v0.2/docs/integrations/vectorstores/neon)
        *   [OpenSearch](/v0.2/docs/integrations/vectorstores/opensearch)
        *   [PGVector](/v0.2/docs/integrations/vectorstores/pgvector)
        *   [Pinecone](/v0.2/docs/integrations/vectorstores/pinecone)
        *   [Prisma](/v0.2/docs/integrations/vectorstores/prisma)
        *   [Qdrant](/v0.2/docs/integrations/vectorstores/qdrant)
        *   [Redis](/v0.2/docs/integrations/vectorstores/redis)
        *   [Rockset](/v0.2/docs/integrations/vectorstores/rockset)
        *   [SingleStore](/v0.2/docs/integrations/vectorstores/singlestore)
        *   [Supabase](/v0.2/docs/integrations/vectorstores/supabase)
        *   [Tigris](/v0.2/docs/integrations/vectorstores/tigris)
        *   [Turbopuffer](/v0.2/docs/integrations/vectorstores/turbopuffer)
        *   [TypeORM](/v0.2/docs/integrations/vectorstores/typeorm)
        *   [Typesense](/v0.2/docs/integrations/vectorstores/typesense)
        *   [Upstash Vector](/v0.2/docs/integrations/vectorstores/upstash)
        *   [USearch](/v0.2/docs/integrations/vectorstores/usearch)
        *   [Vectara](/v0.2/docs/integrations/vectorstores/vectara)
        *   [Vercel Postgres](/v0.2/docs/integrations/vectorstores/vercel_postgres)
        *   [Voy](/v0.2/docs/integrations/vectorstores/voy)
        *   [Weaviate](/v0.2/docs/integrations/vectorstores/weaviate)
        *   [Xata](/v0.2/docs/integrations/vectorstores/xata)
        *   [Zep](/v0.2/docs/integrations/vectorstores/zep)
    *   [Retrievers](/v0.2/docs/integrations/retrievers)
        
    *   [Tools](/v0.2/docs/integrations/tools)
        
    *   [Toolkits](/v0.2/docs/integrations/toolkits)
        
    *   [Stores](/v0.2/docs/integrations/stores/)
        

*   [](/v0.2/)
*   [Components](/v0.2/docs/integrations/components)
*   [Vector stores](/v0.2/docs/integrations/vectorstores)
*   Supabase

On this page

Supabase
========

Langchain supports using Supabase Postgres database as a vector store, using the `pgvector` postgres extension. Refer to the [Supabase blog post](https://supabase.com/blog/openai-embeddings-postgres-vector) for more information.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

### Install the library with[​](#install-the-library-with "Direct link to Install the library with")

*   npm
*   Yarn
*   pnpm

    npm install -S @supabase/supabase-js

    yarn add @supabase/supabase-js

    pnpm add @supabase/supabase-js

### Create a table and search function in your database[​](#create-a-table-and-search-function-in-your-database "Direct link to Create a table and search function in your database")

Run this in your database:

    -- Enable the pgvector extension to work with embedding vectorscreate extension vector;-- Create a table to store your documentscreate table documents (  id bigserial primary key,  content text, -- corresponds to Document.pageContent  metadata jsonb, -- corresponds to Document.metadata  embedding vector(1536) -- 1536 works for OpenAI embeddings, change if needed);-- Create a function to search for documentscreate function match_documents (  query_embedding vector(1536),  match_count int DEFAULT null,  filter jsonb DEFAULT '{}') returns table (  id bigint,  content text,  metadata jsonb,  embedding jsonb,  similarity float)language plpgsqlas $$#variable_conflict use_columnbegin  return query  select    id,    content,    metadata,    (embedding::text)::jsonb as embedding,    1 - (documents.embedding <=> query_embedding) as similarity  from documents  where metadata @> filter  order by documents.embedding <=> query_embedding  limit match_count;end;$$;

Usage[​](#usage "Direct link to Usage")
---------------------------------------

tip

See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/openai @langchain/community

    yarn add @langchain/openai @langchain/community

    pnpm add @langchain/openai @langchain/community

### Standard Usage[​](#standard-usage "Direct link to Standard Usage")

The below example shows how to perform a basic similarity search with Supabase:

    import { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";import { OpenAIEmbeddings } from "@langchain/openai";import { createClient } from "@supabase/supabase-js";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabaseconst privateKey = process.env.SUPABASE_PRIVATE_KEY;if (!privateKey) throw new Error(`Expected env var SUPABASE_PRIVATE_KEY`);const url = process.env.SUPABASE_URL;if (!url) throw new Error(`Expected env var SUPABASE_URL`);export const run = async () => {  const client = createClient(url, privateKey);  const vectorStore = await SupabaseVectorStore.fromTexts(    ["Hello world", "Bye bye", "What's this?"],    [{ id: 2 }, { id: 1 }, { id: 3 }],    new OpenAIEmbeddings(),    {      client,      tableName: "documents",      queryName: "match_documents",    }  );  const resultOne = await vectorStore.similaritySearch("Hello world", 1);  console.log(resultOne);};

#### API Reference:

*   [SupabaseVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) from `@langchain/community/vectorstores/supabase`
*   [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`

### Metadata Filtering[​](#metadata-filtering "Direct link to Metadata Filtering")

Given the above `match_documents` Postgres function, you can also pass a filter parameter to only documents with a specific metadata field value. This filter parameter is a JSON object, and the `match_documents` function will use the Postgres JSONB Containment operator `@>` to filter documents by the metadata field values you specify. See details on the [Postgres JSONB Containment operator](https://www.postgresql.org/docs/current/datatype-json.html#JSON-CONTAINMENT) for more information.

**Note:** If you've previously been using `SupabaseVectorStore`, you may need to drop and recreate the `match_documents` function per the updated SQL above to use this functionality.

    import { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";import { OpenAIEmbeddings } from "@langchain/openai";import { createClient } from "@supabase/supabase-js";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabaseconst privateKey = process.env.SUPABASE_PRIVATE_KEY;if (!privateKey) throw new Error(`Expected env var SUPABASE_PRIVATE_KEY`);const url = process.env.SUPABASE_URL;if (!url) throw new Error(`Expected env var SUPABASE_URL`);export const run = async () => {  const client = createClient(url, privateKey);  const vectorStore = await SupabaseVectorStore.fromTexts(    ["Hello world", "Hello world", "Hello world"],    [{ user_id: 2 }, { user_id: 1 }, { user_id: 3 }],    new OpenAIEmbeddings(),    {      client,      tableName: "documents",      queryName: "match_documents",    }  );  const result = await vectorStore.similaritySearch("Hello world", 1, {    user_id: 3,  });  console.log(result);};

#### API Reference:

*   [SupabaseVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) from `@langchain/community/vectorstores/supabase`
*   [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`

### Metadata Query Builder Filtering[​](#metadata-query-builder-filtering "Direct link to Metadata Query Builder Filtering")

You can also use query builder-style filtering similar to how [the Supabase JavaScript library works](https://supabase.com/docs/reference/javascript/using-filters) instead of passing an object. Note that since most of the filter properties are in the metadata column, you need to use arrow operators (`->` for integer or `->>` for text) as defined in [Postgrest API documentation](https://postgrest.org/en/stable/references/api/tables_views.html?highlight=operators#json-columns) and specify the data type of the property (e.g. the column should look something like `metadata->some_int_value::int`).

    import {  SupabaseFilterRPCCall,  SupabaseVectorStore,} from "@langchain/community/vectorstores/supabase";import { OpenAIEmbeddings } from "@langchain/openai";import { createClient } from "@supabase/supabase-js";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabaseconst privateKey = process.env.SUPABASE_PRIVATE_KEY;if (!privateKey) throw new Error(`Expected env var SUPABASE_PRIVATE_KEY`);const url = process.env.SUPABASE_URL;if (!url) throw new Error(`Expected env var SUPABASE_URL`);export const run = async () => {  const client = createClient(url, privateKey);  const embeddings = new OpenAIEmbeddings();  const store = new SupabaseVectorStore(embeddings, {    client,    tableName: "documents",  });  const docs = [    {      pageContent:        "This is a long text, but it actually means something because vector database does not understand Lorem Ipsum. So I would need to expand upon the notion of quantum fluff, a theorectical concept where subatomic particles coalesce to form transient multidimensional spaces. Yet, this abstraction holds no real-world application or comprehensible meaning, reflecting a cosmic puzzle.",      metadata: { b: 1, c: 10, stuff: "right" },    },    {      pageContent:        "This is a long text, but it actually means something because vector database does not understand Lorem Ipsum. So I would need to proceed by discussing the echo of virtual tweets in the binary corridors of the digital universe. Each tweet, like a pixelated canary, hums in an unseen frequency, a fascinatingly perplexing phenomenon that, while conjuring vivid imagery, lacks any concrete implication or real-world relevance, portraying a paradox of multidimensional spaces in the age of cyber folklore.",      metadata: { b: 2, c: 9, stuff: "right" },    },    { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "right" } },    { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "wrong" } },    { pageContent: "hi", metadata: { b: 2, c: 8, stuff: "right" } },    { pageContent: "bye", metadata: { b: 3, c: 7, stuff: "right" } },    { pageContent: "what's this", metadata: { b: 4, c: 6, stuff: "right" } },  ];  // Also supports an additional {ids: []} parameter for upsertion  await store.addDocuments(docs);  const funcFilterA: SupabaseFilterRPCCall = (rpc) =>    rpc      .filter("metadata->b::int", "lt", 3)      .filter("metadata->c::int", "gt", 7)      .textSearch("content", `'multidimensional' & 'spaces'`, {        config: "english",      });  const resultA = await store.similaritySearch("quantum", 4, funcFilterA);  const funcFilterB: SupabaseFilterRPCCall = (rpc) =>    rpc      .filter("metadata->b::int", "lt", 3)      .filter("metadata->c::int", "gt", 7)      .filter("metadata->>stuff", "eq", "right");  const resultB = await store.similaritySearch("hello", 2, funcFilterB);  console.log(resultA, resultB);};

#### API Reference:

*   [SupabaseFilterRPCCall](https://v02.api.js.langchain.com/types/langchain_community_vectorstores_supabase.SupabaseFilterRPCCall.html) from `@langchain/community/vectorstores/supabase`
*   [SupabaseVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) from `@langchain/community/vectorstores/supabase`
*   [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`

### Maximal marginal relevance[​](#maximal-marginal-relevance "Direct link to Maximal marginal relevance")

You can use maximal marginal relevance search, which optimizes for similarity to the query AND diversity.

**Note:** If you've previously been using `SupabaseVectorStore`, you may need to drop and recreate the `match_documents` function per the updated SQL above to use this functionality.

    import { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";import { OpenAIEmbeddings } from "@langchain/openai";import { createClient } from "@supabase/supabase-js";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabaseconst privateKey = process.env.SUPABASE_PRIVATE_KEY;if (!privateKey) throw new Error(`Expected env var SUPABASE_PRIVATE_KEY`);const url = process.env.SUPABASE_URL;if (!url) throw new Error(`Expected env var SUPABASE_URL`);export const run = async () => {  const client = createClient(url, privateKey);  const vectorStore = await SupabaseVectorStore.fromTexts(    ["Hello world", "Bye bye", "What's this?"],    [{ id: 2 }, { id: 1 }, { id: 3 }],    new OpenAIEmbeddings(),    {      client,      tableName: "documents",      queryName: "match_documents",    }  );  const resultOne = await vectorStore.maxMarginalRelevanceSearch(    "Hello world",    { k: 1 }  );  console.log(resultOne);};

#### API Reference:

*   [SupabaseVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) from `@langchain/community/vectorstores/supabase`
*   [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`

### Document deletion[​](#document-deletion "Direct link to Document deletion")

    import { SupabaseVectorStore } from "@langchain/community/vectorstores/supabase";import { OpenAIEmbeddings } from "@langchain/openai";import { createClient } from "@supabase/supabase-js";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabaseconst privateKey = process.env.SUPABASE_PRIVATE_KEY;if (!privateKey) throw new Error(`Expected env var SUPABASE_PRIVATE_KEY`);const url = process.env.SUPABASE_URL;if (!url) throw new Error(`Expected env var SUPABASE_URL`);export const run = async () => {  const client = createClient(url, privateKey);  const embeddings = new OpenAIEmbeddings();  const store = new SupabaseVectorStore(embeddings, {    client,    tableName: "documents",  });  const docs = [    { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "right" } },    { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "wrong" } },  ];  // Also takes an additional {ids: []} parameter for upsertion  const ids = await store.addDocuments(docs);  const resultA = await store.similaritySearch("hello", 2);  console.log(resultA);  /*    [      Document { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "right" } },      Document { pageContent: "hello", metadata: { b: 1, c: 9, stuff: "wrong" } },    ]  */  await store.delete({ ids });  const resultB = await store.similaritySearch("hello", 2);  console.log(resultB);  /*    []  */};

#### API Reference:

*   [SupabaseVectorStore](https://v02.api.js.langchain.com/classes/langchain_community_vectorstores_supabase.SupabaseVectorStore.html) from `@langchain/community/vectorstores/supabase`
*   [OpenAIEmbeddings](https://v02.api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`

* * *

#### Was this page helpful?

  

#### You can leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

SingleStore

](/v0.2/docs/integrations/vectorstores/singlestore)[

Next

Tigris

](/v0.2/docs/integrations/vectorstores/tigris)

*   [Setup](#setup)
    *   [Install the library with](#install-the-library-with)
    *   [Create a table and search function in your database](#create-a-table-and-search-function-in-your-database)
*   [Usage](#usage)
    *   [Standard Usage](#standard-usage)
    *   [Metadata Filtering](#metadata-filtering)
    *   [Metadata Query Builder Filtering](#metadata-query-builder-filtering)
    *   [Maximal marginal relevance](#maximal-marginal-relevance)
    *   [Document deletion](#document-deletion)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.