!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)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

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

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

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

[v0.1](#)

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

*   [](/v0.1/)
*   [Components](/v0.1/docs/integrations/components/)
*   [Vector stores](/v0.1/docs/integrations/vectorstores/)
*   SAP HANA Cloud Vector Engine

On this page

SAP HANA Cloud Vector Engine
============================

[SAP HANA Cloud Vector Engine](https://www.sap.com/events/teched/news-guide/ai.html#article8) is a vector store fully integrated into the `SAP HANA Cloud database`.

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

You'll first need to install either the [`@sap/hana-client`](https://www.npmjs.com/package/@sap/hana-client) or the [`hdb`](https://www.npmjs.com/package/hdb) package, and the [`@langchain/community`](https://www.npmjs.com/package/@langchain/community) package:

tip

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

*   npm
*   Yarn
*   pnpm

    npm install -S @langchain/community @sap/hana-client# ornpm install -S @langchain/community hdb

    yarn add @langchain/community @sap/hana-client# oryarn add @langchain/community hdb

    pnpm add @langchain/community @sap/hana-client# orpnpm add @langchain/community hdb

You'll also need to have database connection to a HANA Cloud instance.

    OPENAI_API_KEY = "Your OpenAI API key"HANA_HOST = "HANA_DB_ADDRESS"HANA_PORT = "HANA_DB_PORT"HANA_UID =  "HANA_DB_USER"HANA_PWD = "HANA_DB_PASSWORD"

#### API Reference:

Create a new index from texts[​](#create-a-new-index-from-texts "Direct link to Create a new index from texts")
---------------------------------------------------------------------------------------------------------------

    import { OpenAIEmbeddings } from "@langchain/openai";import hanaClient from "hdb";import {  HanaDB,  HanaDBArgs,} from "@langchain/community/vectorstores/hanavector";const connectionParams = {  host: process.env.HANA_HOST,  port: process.env.HANA_PORT,  user: process.env.HANA_UID,  password: process.env.HANA_PWD,  // useCesu8 : false};const client = hanaClient.createClient(connectionParams);// connet to hanaDBawait new Promise<void>((resolve, reject) => {  client.connect((err: Error) => {    // Use arrow function here    if (err) {      reject(err);    } else {      console.log("Connected to SAP HANA successfully.");      resolve();    }  });});const embeddings = new OpenAIEmbeddings();const args: HanaDBArgs = {  connection: client,  tableName: "test_fromTexts",};// This function will create a table "test_fromTexts" if not exist, if exists,// then the value will be appended to the table.const vectorStore = await HanaDB.fromTexts(  ["Bye bye", "Hello world", "hello nice world"],  [    { id: 2, name: "2" },    { id: 1, name: "1" },    { id: 3, name: "3" },  ],  embeddings,  args);const response = await vectorStore.similaritySearch("hello world", 2);console.log(response);/* This result is based on no table "test_fromTexts" existing in the database.  [    { pageContent: 'Hello world', metadata: { id: 1, name: '1' } },    { pageContent: 'hello nice world', metadata: { id: 3, name: '3' } }  ]*/client.disconnect();

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [HanaDB](https://api.js.langchain.com/classes/langchain_community_vectorstores_hanavector.HanaDB.html) from `@langchain/community/vectorstores/hanavector`
*   [HanaDBArgs](https://api.js.langchain.com/interfaces/langchain_community_vectorstores_hanavector.HanaDBArgs.html) from `@langchain/community/vectorstores/hanavector`

Create a new index from a loader and perform similarity searches[​](#create-a-new-index-from-a-loader-and-perform-similarity-searches "Direct link to Create a new index from a loader and perform similarity searches")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    import hanaClient from "hdb";import {  HanaDB,  HanaDBArgs,} from "@langchain/community/vectorstores/hanavector";import { OpenAIEmbeddings } from "@langchain/openai";import { TextLoader } from "langchain/document_loaders/fs/text";import { CharacterTextSplitter } from "langchain/text_splitter";const connectionParams = {  host: process.env.HANA_HOST,  port: process.env.HANA_PORT,  user: process.env.HANA_UID,  password: process.env.HANA_PWD,  // useCesu8 : false};const client = hanaClient.createClient(connectionParams);// connet to hanaDBawait new Promise<void>((resolve, reject) => {  client.connect((err: Error) => {    // Use arrow function here    if (err) {      reject(err);    } else {      console.log("Connected to SAP HANA successfully.");      resolve();    }  });});const embeddings = new OpenAIEmbeddings();const args: HanaDBArgs = {  connection: client,  tableName: "test_fromDocs",};// Load documents from fileconst loader = new TextLoader("./state_of_the_union.txt");const rawDocuments = await loader.load();const splitter = new CharacterTextSplitter({  chunkSize: 500,  chunkOverlap: 0,});const documents = await splitter.splitDocuments(rawDocuments);// Create a LangChain VectorStore interface for the HANA database and specify the table (collection) to use in args.const vectorStore = new HanaDB(embeddings, args);await vectorStore.initialize();// Delete already existing documents from the tableawait vectorStore.delete({ filter: {} });// add the loaded document chunksawait vectorStore.addDocuments(documents);// similarity search (default:“Cosine Similarity”, options:["euclidean", "cosine"])const query = "What did the president say about Ketanji Brown Jackson";const docs = await vectorStore.similaritySearch(query, 2);docs.forEach((doc) => {  console.log("-".repeat(80));  console.log(doc.pageContent);});/*  --------------------------------------------------------------------------------  One of the most serious constitutional responsibilities a President has is nominating   someone to serve on the United States Supreme Court.   And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson.   One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.  --------------------------------------------------------------------------------  As I said last year, especially to our younger transgender Americans, I will always have your back as your President,   so you can be yourself and reach your God-given potential.   While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year.   From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice*/// similiarity search using euclidean distance methodconst argsL2d: HanaDBArgs = {  connection: client,  tableName: "test_fromDocs",  distanceStrategy: "euclidean",};const vectorStoreL2d = new HanaDB(embeddings, argsL2d);const docsL2d = await vectorStoreL2d.similaritySearch(query, 2);docsL2d.forEach((docsL2d) => {  console.log("-".repeat(80));  console.log(docsL2d.pageContent);});// Output should be the same as the cosine similarity search method.// Maximal Marginal Relevance Search (MMR)const docsMMR = await vectorStore.maxMarginalRelevanceSearch(query, {  k: 2,  fetchK: 20,});docsMMR.forEach((docsMMR) => {  console.log("-".repeat(80));  console.log(docsMMR.pageContent);});/*  --------------------------------------------------------------------------------  One of the most serious constitutional responsibilities a President has is nominating someone   to serve on the United States Supreme Court.   And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson.   One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.  --------------------------------------------------------------------------------  Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned   soldiers defending their homeland.   In this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.”   The Ukrainian Ambassador to the United States is here tonight.   Let each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world.*/client.disconnect();

#### API Reference:

*   [HanaDB](https://api.js.langchain.com/classes/langchain_community_vectorstores_hanavector.HanaDB.html) from `@langchain/community/vectorstores/hanavector`
*   [HanaDBArgs](https://api.js.langchain.com/interfaces/langchain_community_vectorstores_hanavector.HanaDBArgs.html) from `@langchain/community/vectorstores/hanavector`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [TextLoader](https://api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text`
*   [CharacterTextSplitter](https://api.js.langchain.com/classes/langchain_textsplitters.CharacterTextSplitter.html) from `langchain/text_splitter`

Basic Vectorstore Operations[​](#basic-vectorstore-operations "Direct link to Basic Vectorstore Operations")
------------------------------------------------------------------------------------------------------------

    import { OpenAIEmbeddings } from "@langchain/openai";import hanaClient from "hdb";// or import another node.js driver// import hanaClient from "@sap/haha-client";import { Document } from "@langchain/core/documents";import {  HanaDB,  HanaDBArgs,} from "@langchain/community/vectorstores/hanavector";const connectionParams = {  host: process.env.HANA_HOST,  port: process.env.HANA_PORT,  user: process.env.HANA_UID,  password: process.env.HANA_PWD,  // useCesu8 : false};const client = hanaClient.createClient(connectionParams);// connet to hanaDBawait new Promise<void>((resolve, reject) => {  client.connect((err: Error) => {    // Use arrow function here    if (err) {      reject(err);    } else {      console.log("Connected to SAP HANA successfully.");      resolve();    }  });});const embeddings = new OpenAIEmbeddings();// define instance argsconst args: HanaDBArgs = {  connection: client,  tableName: "testBasics",};// Add documents with metadata.const docs: Document[] = [  {    pageContent: "foo",    metadata: { start: 100, end: 150, docName: "foo.txt", quality: "bad" },  },  {    pageContent: "bar",    metadata: { start: 200, end: 250, docName: "bar.txt", quality: "good" },  },];// Create a LangChain VectorStore interface for the HANA database and specify the table (collection) to use in args.const vectorStore = new HanaDB(embeddings, args);// need to initialize once an instance is created.await vectorStore.initialize();// Delete already existing documents from the tableawait vectorStore.delete({ filter: {} });await vectorStore.addDocuments(docs);// Query documents with specific metadata.const filterMeta = { quality: "bad" };const query = "foobar";// With filtering on {"quality": "bad"}, only one document should be returnedconst results = await vectorStore.similaritySearch(query, 1, filterMeta);console.log(results);/*    [  {        pageContent: "foo",        metadata: { start: 100, end: 150, docName: "foo.txt", quality: "bad" }      }    ]*/// Delete documents with specific metadata.await vectorStore.delete({ filter: filterMeta });// Now the similarity search with the same filter will return no resultsconst resultsAfterFilter = await vectorStore.similaritySearch(  query,  1,  filterMeta);console.log(resultsAfterFilter);/*    []*/client.disconnect();

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`
*   [HanaDB](https://api.js.langchain.com/classes/langchain_community_vectorstores_hanavector.HanaDB.html) from `@langchain/community/vectorstores/hanavector`
*   [HanaDBArgs](https://api.js.langchain.com/interfaces/langchain_community_vectorstores_hanavector.HanaDBArgs.html) from `@langchain/community/vectorstores/hanavector`

Using a VectorStore as a retriever in chains for retrieval augmented generation (RAG)[​](#using-a-vectorstore-as-a-retriever-in-chains-for-retrieval-augmented-generation-rag "Direct link to Using a VectorStore as a retriever in chains for retrieval augmented generation (RAG)")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";import { createRetrievalChain } from "langchain/chains/retrieval";import hanaClient from "hdb";import {  HanaDB,  HanaDBArgs,} from "@langchain/community/vectorstores/hanavector";// Connection parametersconst connectionParams = {  host: process.env.HANA_HOST,  port: process.env.HANA_PORT,  user: process.env.HANA_UID,  password: process.env.HANA_PWD,  // useCesu8 : false};const client = hanaClient.createClient(connectionParams);// connet to hanaDBawait new Promise<void>((resolve, reject) => {  client.connect((err: Error) => {    // Use arrow function here    if (err) {      reject(err);    } else {      console.log("Connected to SAP HANA successfully.");      resolve();    }  });});const embeddings = new OpenAIEmbeddings();const args: HanaDBArgs = {  connection: client,  tableName: "test_fromDocs",};const vectorStore = new HanaDB(embeddings, args);await vectorStore.initialize();// Use the store as part of a chain, under the premise that "test_fromDocs" exists and contains the chunked docs.const model = new ChatOpenAI({ modelName: "gpt-3.5-turbo-1106" });const questionAnsweringPrompt = ChatPromptTemplate.fromMessages([  [    "system",    "You are an expert in state of the union topics. You are provided multiple context items that are related to the prompt you have to answer. Use the following pieces of context to answer the question at the end.\n\n{context}",  ],  ["human", "{input}"],]);const combineDocsChain = await createStuffDocumentsChain({  llm: model,  prompt: questionAnsweringPrompt,});const chain = await createRetrievalChain({  retriever: vectorStore.asRetriever(),  combineDocsChain,});// Ask the first question (and verify how many text chunks have been used).const response = await chain.invoke({  input: "What about Mexico and Guatemala?",});console.log("Chain response:");console.log(response.answer);console.log(  `Number of used source document chunks: ${response.context.length}`);/* The United States has set up joint patrols with Mexico and Guatemala to catch more human traffickers. Number of used source document chunks: 4*/const responseOther = await chain.invoke({  input: "What about other countries?",});console.log("Chain response:");console.log(responseOther.answer);/* Ask another question on the same conversational chain. The answer should relate to the previous answer given.....including members of NATO, the European Union, and other allies such as Canada....*/client.disconnect();

#### API Reference:

*   [ChatPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts`
*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [createStuffDocumentsChain](https://api.js.langchain.com/functions/langchain_chains_combine_documents.createStuffDocumentsChain.html) from `langchain/chains/combine_documents`
*   [createRetrievalChain](https://api.js.langchain.com/functions/langchain_chains_retrieval.createRetrievalChain.html) from `langchain/chains/retrieval`
*   [HanaDB](https://api.js.langchain.com/classes/langchain_community_vectorstores_hanavector.HanaDB.html) from `@langchain/community/vectorstores/hanavector`
*   [HanaDBArgs](https://api.js.langchain.com/interfaces/langchain_community_vectorstores_hanavector.HanaDBArgs.html) from `@langchain/community/vectorstores/hanavector`

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Google Vertex AI Matching Engine

](/v0.1/docs/integrations/vectorstores/googlevertexai/)[

Next

HNSWLib

](/v0.1/docs/integrations/vectorstores/hnswlib/)

*   [Setup](#setup)
*   [Create a new index from texts](#create-a-new-index-from-texts)
*   [Create a new index from a loader and perform similarity searches](#create-a-new-index-from-a-loader-and-perform-similarity-searches)
*   [Basic Vectorstore Operations](#basic-vectorstore-operations)
*   [Using a VectorStore as a retriever in chains for retrieval augmented generation (RAG)](#using-a-vectorstore-as-a-retriever-in-chains-for-retrieval-augmented-generation-rag)

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.