Google Cloud SQL for PostgreSQL vector store integration.
Setup:
Install @langchain/google-cloud-sql-pg
npm install @langchain/google-cloud-sql-pg
import { Column, PostgresEngine, PostgresEngineArgs, PostgresVectorStore, VectorStoreTableArgs } from "@langchain/google-cloud-sql-pg";
// Or other embeddings
import { OpenAIEmbeddings } from '@langchain/openai';
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const pgArgs: PostgresEngineArgs = {
user: "db-user",
password: "password"
}
// Create a shared connection pool
const engine: PostgresEngine = await PostgresEngine.fromInstance(
"project-id",
"region",
"instance-name",
"database-name",
pgArgs
);
// (Optional) Specify metadata columns for filtering
// All other metadata will be added to JSON
const vectorStoreTableArgs: VectorStoreTableArgs = {
metadataColumns: [new Column("baz", "TEXT")],
};
// Create a vector store table
await engine.initVectorstoreTable("my-table", 768, vectorStoreTableArgs);
// Customize the vector store
const pvectorArgs: PostgresVectorStoreArgs = {
idColumn: "ID_COLUMN",
contentColumn: "CONTENT_COLUMN",
embeddingColumn: "EMBEDDING_COLUMN",
metadataColumns: ["baz"]
}
const vectorStore = await PostgresVectorStore.initialize(engine, embeddingService, "my-table", pvectorArgs);
import type { Document } from '@langchain/core/documents';
const document1 = { pageContent: "foo", metadata: { baz: "bar" } };
const document2 = { pageContent: "thud", metadata: { bar: "baz" } };
const document3 = { pageContent: "i will be deleted :(", metadata: {} };
const documents: Document[] = [document1, document2, document3];
const ids = ["1", "2", "3"];
await vectorStore.addDocuments(documents, { ids });
await vectorStore.delete({ ids: ["3"] });
const results = await vectorStore.similaritySearch("thud", 1);
for (const doc of results) {
console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
// Output:thud [{"baz":"bar"}]
const resultsWithFilter = await vectorStore.similaritySearch("thud", 1, { baz: "bar" });
for (const doc of resultsWithFilter) {
console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
// Output:foo [{"baz":"bar"}]
const resultsWithScore = await vectorStore.similaritySearchWithScore("qux", 1);
for (const [doc, score] of resultsWithScore) {
console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
// Output:[SIM=0.000000] qux [{"bar":"baz","baz":"bar"}]
const retriever = vectorStore.asRetriever({
searchType: "mmr", // Leave blank for standard similarity search
k: 1,
});
const resultAsRetriever = await retriever.invoke("thud");
console.log(resultAsRetriever);
// Output: [Document({ metadata: { "baz":"bar" }, pageContent: "thud" })]
Embeddings interface for generating vector embeddings from text queries, enabling vector-based similarity searches.
Returns a string representing the type of vector store, which subclasses must implement to identify their specific vector storage type.
Adds documents to the vector store, embedding them first through the
embeddings instance.
Adds precomputed vectors and corresponding documents to the vector store.
Create an index on the vector store table
Creates a VectorStoreRetriever instance with flexible configuration options.
Deletes documents from the vector store based on the specified ids.
Drop the vector index
Check if index exists in the table.
Return documents selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to the query AND diversity among selected documents.
Re-index the vector store table
Searches for documents similar to a text query by embedding the query and performing a similarity search on the resulting vector.
Performs a similarity search using a vector query and returns results along with their similarity scores.
Searches for documents similar to a text query by embedding the query, and returns results with similarity scores.
Creates a VectorStore instance from an array of documents, using the specified
embeddings and database configuration.
Subclasses must implement this method to define how documents are embedded and stored. Throws an error if not overridden.
Creates a VectorStore instance from an array of text strings and optional
metadata, using the specified embeddings and database configuration.
Subclasses must implement this method to define how text and metadata are embedded and stored in the vector store. Throws an error if not overridden.
Create a new PostgresVectorStore instance.
The name of the serializable. Override to provide an alias or to preserve the serialized module name in minified environments.
Implemented as a static method to support loading logic.