!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/)
                
                *   [Chroma Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/chroma-self-query/)
                *   [HNSWLib Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/hnswlib-self-query/)
                *   [Memory Vector Store Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/memory-self-query/)
                *   [Pinecone Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/pinecone-self-query/)
                *   [Qdrant Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/qdrant-self-query/)
                *   [Supabase Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/supabase-self-query/)
                *   [Vectara Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/vectara-self-query/)
                *   [Weaviate Self Query Retriever](/v0.1/docs/modules/data_connection/retrievers/self_query/weaviate-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](/v0.1/docs/modules/data_connection/retrievers/)
*   Self-querying

On this page

Self-querying
=============

A self-querying retriever is one that, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses a query-constructing LLM chain to write a structured query and then applies that structured query to it's underlying VectorStore. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documented, but to also extract filters from the user query on the metadata of stored documents and to execute those filters.

![](https://drive.google.com/uc?id=1OQUN-0MJcDUxmPXofgS7MqReEs720pqS)

All Self Query retrievers require `peggy` as a peer dependency:

*   npm
*   Yarn
*   pnpm

    npm install -S peggy

    yarn add peggy

    pnpm add peggy

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

Here's a basic example with an in-memory, unoptimized vector store:

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

    yarn add @langchain/openai

    pnpm add @langchain/openai

    import { MemoryVectorStore } from "langchain/vectorstores/memory";import { AttributeInfo } from "langchain/schema/query_constructor";import { OpenAIEmbeddings, OpenAI } from "@langchain/openai";import { SelfQueryRetriever } from "langchain/retrievers/self_query";import { FunctionalTranslator } from "langchain/retrievers/self_query/functional";import { Document } from "@langchain/core/documents";/** * First, we create a bunch of documents. You can load your own documents here instead. * Each document has a pageContent and a metadata field. Make sure your metadata matches the AttributeInfo below. */const docs = [  new Document({    pageContent:      "A bunch of scientists bring back dinosaurs and mayhem breaks loose",    metadata: { year: 1993, rating: 7.7, genre: "science fiction" },  }),  new Document({    pageContent:      "Leo DiCaprio gets lost in a dream within a dream within a dream within a ...",    metadata: { year: 2010, director: "Christopher Nolan", rating: 8.2 },  }),  new Document({    pageContent:      "A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea",    metadata: { year: 2006, director: "Satoshi Kon", rating: 8.6 },  }),  new Document({    pageContent:      "A bunch of normal-sized women are supremely wholesome and some men pine after them",    metadata: { year: 2019, director: "Greta Gerwig", rating: 8.3 },  }),  new Document({    pageContent: "Toys come alive and have a blast doing so",    metadata: { year: 1995, genre: "animated" },  }),  new Document({    pageContent: "Three men walk into the Zone, three men walk out of the Zone",    metadata: {      year: 1979,      director: "Andrei Tarkovsky",      genre: "science fiction",      rating: 9.9,    },  }),];/** * Next, we define the attributes we want to be able to query on. * in this case, we want to be able to query on the genre, year, director, rating, and length of the movie. * We also provide a description of each attribute and the type of the attribute. * This is used to generate the query prompts. */const attributeInfo: AttributeInfo[] = [  {    name: "genre",    description: "The genre of the movie",    type: "string or array of strings",  },  {    name: "year",    description: "The year the movie was released",    type: "number",  },  {    name: "director",    description: "The director of the movie",    type: "string",  },  {    name: "rating",    description: "The rating of the movie (1-10)",    type: "number",  },  {    name: "length",    description: "The length of the movie in minutes",    type: "number",  },];/** * Next, we instantiate a vector store. This is where we store the embeddings of the documents. * We also need to provide an embeddings object. This is used to embed the documents. */const embeddings = new OpenAIEmbeddings();const llm = new OpenAI();const documentContents = "Brief summary of a movie";const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings);const selfQueryRetriever = SelfQueryRetriever.fromLLM({  llm,  vectorStore,  documentContents,  attributeInfo,  /**   * We need to use a translator that translates the queries into a   * filter format that the vector store can understand. We provide a basic translator   * translator here, but you can create your own translator by extending BaseTranslator   * abstract class. Note that the vector store needs to support filtering on the metadata   * attributes you want to query on.   */  structuredQueryTranslator: new FunctionalTranslator(),});/** * Now we can query the vector store. * We can ask questions like "Which movies are less than 90 minutes?" or "Which movies are rated higher than 8.5?". * We can also ask questions like "Which movies are either comedy or drama and are less than 90 minutes?". * The retriever will automatically convert these questions into queries that can be used to retrieve documents. */const query1 = await selfQueryRetriever.invoke(  "Which movies are less than 90 minutes?");const query2 = await selfQueryRetriever.invoke(  "Which movies are rated higher than 8.5?");const query3 = await selfQueryRetriever.invoke(  "Which movies are directed by Greta Gerwig?");const query4 = await selfQueryRetriever.invoke(  "Which movies are either comedy or drama and are less than 90 minutes?");console.log(query1, query2, query3, query4);

#### API Reference:

*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [AttributeInfo](https://api.js.langchain.com/classes/langchain_schema_query_constructor.AttributeInfo.html) from `langchain/schema/query_constructor`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [OpenAI](https://api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai`
*   [SelfQueryRetriever](https://api.js.langchain.com/classes/langchain_retrievers_self_query.SelfQueryRetriever.html) from `langchain/retrievers/self_query`
*   [FunctionalTranslator](https://api.js.langchain.com/classes/langchain_core_structured_query.FunctionalTranslator.html) from `langchain/retrievers/self_query/functional`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`

Setting default search params[​](#setting-default-search-params "Direct link to Setting default search params")
---------------------------------------------------------------------------------------------------------------

You can also pass in a default filter when initializing the self-query retriever that will be used in combination with or as a fallback to the generated query. For example, if you wanted to ensure that your query documents tagged as `genre: "animated"`, you could initialize the above retriever as follows:

    const selfQueryRetriever = SelfQueryRetriever.fromLLM({  llm,  vectorStore,  documentContents,  attributeInfo,  structuredQueryTranslator: new FunctionalTranslator(),  searchParams: {    filter: (doc: Document) =>      doc.metadata && doc.metadata.genre === "animated",    mergeFiltersOperator: "and",  },});

The type of filter required will depend on the specific translator used for the retriever. See the individual pages for examples.

Other supported values for `mergeFiltersOperator` are `"or"` or `"replace"`.

* * *

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

[

Previous

Parent Document Retriever

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

Next

Chroma Self Query Retriever

](/v0.1/docs/modules/data_connection/retrievers/self_query/chroma-self-query/)

*   [Usage](#usage)
*   [Setting default search params](#setting-default-search-params)

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.