!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

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
        *   [Document loaders](/v0.1/docs/modules/data_connection/document_loaders/)
            
        *   [Text Splitters](/v0.1/docs/modules/data_connection/document_transformers/)
            
        *   [Retrievers](/v0.1/docs/modules/data_connection/retrievers/)
            
            *   [Custom retrievers](/v0.1/docs/modules/data_connection/retrievers/custom/)
            *   [Contextual compression](/v0.1/docs/modules/data_connection/retrievers/contextual_compression/)
            *   [Matryoshka Retriever](/v0.1/docs/modules/data_connection/retrievers/matryoshka_retriever/)
            *   [MultiQuery Retriever](/v0.1/docs/modules/data_connection/retrievers/multi-query-retriever/)
            *   [MultiVector Retriever](/v0.1/docs/modules/data_connection/retrievers/multi-vector-retriever/)
            *   [Parent Document Retriever](/v0.1/docs/modules/data_connection/retrievers/parent-document-retriever/)
            *   [Self-querying](/v0.1/docs/modules/data_connection/retrievers/self_query/)
                
            *   [Similarity Score Threshold](/v0.1/docs/modules/data_connection/retrievers/similarity-score-threshold-retriever/)
            *   [Time-weighted vector store retriever](/v0.1/docs/modules/data_connection/retrievers/time_weighted_vectorstore/)
            *   [Vector store-backed retriever](/v0.1/docs/modules/data_connection/retrievers/vectorstore/)
        *   [Retrieval](/v0.1/docs/modules/data_connection/)
        *   [Text embedding models](/v0.1/docs/modules/data_connection/text_embedding/)
            
        *   [Vector stores](/v0.1/docs/modules/data_connection/vectorstores/)
            
        *   [Indexing](/v0.1/docs/modules/data_connection/indexing/)
        *   [Experimental](/v0.1/docs/modules/data_connection/experimental/multimodal_embeddings/google_vertex_ai/)
            
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   [Retrieval](/v0.1/docs/modules/data_connection/)
*   Retrievers

On this page

Retrievers
==========

A retriever is an interface that returns documents given an unstructured query. It is more general than a vector store. A retriever does not need to be able to store documents, only to return (or retrieve) them. Vector stores can be used as the backbone of a retriever, but there are other types of retrievers as well.

Retrievers accept a string query as input and return a list of `Document`'s as output.

Advanced Retrieval Types[​](#advanced-retrieval-types "Direct link to Advanced Retrieval Types")
------------------------------------------------------------------------------------------------

LangChain provides several advanced retrieval types. A full list is below, along with the following information:

**Name**: Name of the retrieval algorithm.

**Index Type**: Which index type (if any) this relies on.

**Uses an LLM**: Whether this retrieval method uses an LLM.

**When to Use**: Our commentary on when you should considering using this retrieval method.

**Description**: Description of what this retrieval algorithm is doing.

Name

Index Type

Uses an LLM

When to Use

Description

[Vectorstore](/v0.1/docs/modules/data_connection/retrievers/vectorstore/)

Vectorstore

No

If you are just getting started and looking for something quick and easy.

This is the simplest method and the one that is easiest to get started with. It involves creating embeddings for each piece of text.

[ParentDocument](/v0.1/docs/modules/data_connection/retrievers/parent-document-retriever/)

Vectorstore + Document Store

No

If your pages have lots of smaller pieces of distinct information that are best indexed by themselves, but best retrieved all together.

This involves indexing multiple chunks for each document. Then you find the chunks that are most similar in embedding space, but you retrieve the whole parent document and return that (rather than individual chunks).

[Multi Vector](/v0.1/docs/modules/data_connection/retrievers/multi-vector-retriever/)

Vectorstore + Document Store

Sometimes during indexing

If you are able to extract information from documents that you think is more relevant to index than the text itself.

This involves creating multiple vectors for each document. Each vector could be created in a myriad of ways - examples include summaries of the text and hypothetical questions.

[Self Query](/v0.1/docs/modules/data_connection/retrievers/self_query/)

Vectorstore

Yes

If users are asking questions that are better answered by fetching documents based on metadata rather than similarity with the text.

This uses an LLM to transform user input into two things: (1) a string to look up semantically, (2) a metadata filter to go along with it. This is useful because oftentimes questions are about the METADATA of documents (not the content itself).

[Contextual Compression](/v0.1/docs/modules/data_connection/retrievers/contextual_compression/)

Any

Sometimes

If you are finding that your retrieved documents contain too much irrelevant information and are distracting the LLM.

This puts a post-processing step on top of another retriever and extracts only the most relevant information from retrieved documents. This can be done with embeddings or an LLM.

[Time-Weighted Vectorstore](/v0.1/docs/modules/data_connection/retrievers/time_weighted_vectorstore/)

Vectorstore

No

If you have timestamps associated with your documents, and you want to retrieve the most recent ones

This fetches documents based on a combination of semantic similarity (as in normal vector retrieval) and recency (looking at timestamps of indexed documents)

[Multi-Query Retriever](/v0.1/docs/modules/data_connection/retrievers/multi-query-retriever/)

Any

Yes

If users are asking questions that are complex and require multiple pieces of distinct information to respond

This uses an LLM to generate multiple queries from the original one. This is useful when the original query needs pieces of information about multiple topics to be properly answered. By generating multiple queries, we can then fetch documents for each of them.

[Third Party Integrations](/v0.1/docs/integrations/retrievers/)[​](#third-party-integrations "Direct link to third-party-integrations")
---------------------------------------------------------------------------------------------------------------------------------------

LangChain also integrates with many third-party retrieval services. For a full list of these, check out [this list](/v0.1/docs/integrations/retrievers/) of all integrations.

Get started[​](#get-started "Direct link to Get started")
---------------------------------------------------------

The public API of the `BaseRetriever` class in LangChain.js is as follows:

    export abstract class BaseRetriever {  abstract getRelevantDocuments(query: string): Promise<Document[]>;}

It's that simple! You can call `getRelevantDocuments` to retrieve documents relevant to a query, where "relevance" is defined by the specific retriever object you are calling.

Of course, we also help construct what we think useful Retrievers are. The main type of Retriever in LangChain is a vector store retriever. We will focus on that here.

**Note:** Before reading, it's important to understand [what a vector store is](/v0.1/docs/modules/data_connection/vectorstores/).

This example showcases question answering over documents. We have chosen this as the example for getting started because it nicely combines a lot of different elements (Text splitters, embeddings, vectorstores) and then also shows how to use them in a chain.

Question answering over documents consists of four steps:

1.  Create an index
2.  Create a Retriever from that index
3.  Create a question answering chain
4.  Ask questions!

Each of the steps has multiple sub steps and potential configurations, but we'll go through one common flow using HNSWLib, a local vector store. This assumes you're using Node, but you can swap in another integration if necessary.

First, install the required dependency:

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 @langchain/openai hnswlib-node @langchain/community

    yarn add @langchain/openai hnswlib-node @langchain/community

    pnpm add @langchain/openai hnswlib-node @langchain/community

You can download the `state_of_the_union.txt` file [here](https://github.com/langchain-ai/langchain/blob/master/docs/docs/modules/state_of_the_union.txt).

    import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import * as fs from "fs";import { formatDocumentsAsString } from "langchain/util/document";import {  RunnablePassthrough,  RunnableSequence,} from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";import {  ChatPromptTemplate,  HumanMessagePromptTemplate,  SystemMessagePromptTemplate,} from "@langchain/core/prompts";// Initialize the LLM to use to answer the question.const model = new ChatOpenAI({});const text = fs.readFileSync("state_of_the_union.txt", "utf8");const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000 });const docs = await textSplitter.createDocuments([text]);// Create a vector store from the documents.const vectorStore = await HNSWLib.fromDocuments(docs, new OpenAIEmbeddings());// Initialize a retriever wrapper around the vector storeconst vectorStoreRetriever = vectorStore.asRetriever();// Create a system & human prompt for the chat modelconst SYSTEM_TEMPLATE = `Use the following pieces of context to answer the question at the end.If you don't know the answer, just say that you don't know, don't try to make up an answer.----------------{context}`;const messages = [  SystemMessagePromptTemplate.fromTemplate(SYSTEM_TEMPLATE),  HumanMessagePromptTemplate.fromTemplate("{question}"),];const prompt = ChatPromptTemplate.fromMessages(messages);const chain = RunnableSequence.from([  {    context: vectorStoreRetriever.pipe(formatDocumentsAsString),    question: new RunnablePassthrough(),  },  prompt,  model,  new StringOutputParser(),]);const answer = await chain.invoke(  "What did the president say about Justice Breyer?");console.log({ answer });/*{  answer: 'The president thanked Justice Stephen Breyer for his service and honored him for his dedication to the country.'}*/

#### API Reference:

*   [HNSWLib](https://api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [RecursiveCharacterTextSplitter](https://api.js.langchain.com/classes/langchain_textsplitters.RecursiveCharacterTextSplitter.html) from `langchain/text_splitter`
*   [formatDocumentsAsString](https://api.js.langchain.com/functions/langchain_util_document.formatDocumentsAsString.html) from `langchain/util/document`
*   [RunnablePassthrough](https://api.js.langchain.com/classes/langchain_core_runnables.RunnablePassthrough.html) from `@langchain/core/runnables`
*   [RunnableSequence](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables`
*   [StringOutputParser](https://api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers`
*   [ChatPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts`
*   [HumanMessagePromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.HumanMessagePromptTemplate.html) from `@langchain/core/prompts`
*   [SystemMessagePromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.SystemMessagePromptTemplate.html) from `@langchain/core/prompts`

Let's walk through what's happening here.

1.  We first load a long text and split it into smaller documents using a text splitter. We then load those documents (which also embeds the documents using the passed `OpenAIEmbeddings` instance) into HNSWLib, our vector store, creating our index.
    
2.  Though we can query the vector store directly, we convert the vector store into a retriever to return retrieved documents in the right format for the question answering chain.
    
3.  We initialize a retrieval chain, which we'll call later in step 4.
    
4.  We ask questions!
    

See the individual sections for deeper dives on specific retrievers, or this section to learn how to [create your own custom retriever over any data source](/v0.1/docs/modules/data_connection/retrievers/custom/).

* * *

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

[

Previous

TokenTextSplitter

](/v0.1/docs/modules/data_connection/document_transformers/token_splitter/)[

Next

Custom retrievers

](/v0.1/docs/modules/data_connection/retrievers/custom/)

*   [Advanced Retrieval Types](#advanced-retrieval-types)
*   [Third Party Integrations](#third-party-integrations)
*   [Get started](#get-started)

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.