!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](/v0.1/docs/modules/data_connection/retrievers/self_query/)
*   Weaviate Self Query Retriever

On this page

Weaviate Self Query Retriever
=============================

This example shows how to use a self query retriever with a [Weaviate](https://weaviate.io/) vector store.

If you haven't already set up Weaviate, please [follow the instructions here](/v0.1/docs/integrations/vectorstores/weaviate/).

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

This example shows how to intialize a `SelfQueryRetriever` with a vector store:

Weaviate has their own standalone integration package with LangChain, accessible via [`@langchain/weaviate`](https://www.npmjs.com/package/@langchain/weaviate) on NPM!

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

    yarn add @langchain/weaviate @langchain/openai @langchain/community

    pnpm add @langchain/weaviate @langchain/openai @langchain/community

    import weaviate from "weaviate-ts-client";import { AttributeInfo } from "langchain/schema/query_constructor";import { OpenAIEmbeddings, OpenAI } from "@langchain/openai";import { SelfQueryRetriever } from "langchain/retrievers/self_query";import { WeaviateStore } from "@langchain/community/vectorstores/weaviate";import { WeaviateTranslator } from "langchain/retrievers/self_query/weaviate";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. */const embeddings = new OpenAIEmbeddings();const llm = new OpenAI();const documentContents = "Brief summary of a movie";// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst client = (weaviate as any).client({  scheme: process.env.WEAVIATE_SCHEME || "https",  host: process.env.WEAVIATE_HOST || "localhost",  apiKey: process.env.WEAVIATE_API_KEY    ? // eslint-disable-next-line @typescript-eslint/no-explicit-any      new (weaviate as any).ApiKey(process.env.WEAVIATE_API_KEY)    : undefined,});const vectorStore = await WeaviateStore.fromDocuments(docs, embeddings, {  client,  indexName: "Test",  textKey: "text",  metadataKeys: ["year", "director", "rating", "genre"],});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. LangChain provides one here.   */  structuredQueryTranslator: new WeaviateTranslator(),});/** * 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. * * Note that unlike other vector stores, you have to make sure each metadata keys are actually presnt in the database, * meaning that Weaviate will throw an error if the self query chain generate a query with a metadata key that does * not exist in your Weaviate database. */const query1 = await selfQueryRetriever.invoke(  "Which movies are rated higher than 8.5?");const query2 = await selfQueryRetriever.invoke(  "Which movies are directed by Greta Gerwig?");console.log(query1, query2);

#### API Reference:

*   [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`
*   [WeaviateStore](https://api.js.langchain.com/classes/langchain_community_vectorstores_weaviate.WeaviateStore.html) from `@langchain/community/vectorstores/weaviate`
*   [WeaviateTranslator](https://api.js.langchain.com/classes/langchain_retrievers_self_query_weaviate.WeaviateTranslator.html) from `langchain/retrievers/self_query/weaviate`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`

You can also initialize the retriever with default search parameters that apply in addition to the generated query:

    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. LangChain provides one here.   */  structuredQueryTranslator: new WeaviateTranslator(),  searchParams: {    filter: {      where: {        operator: "Equal",        path: ["type"],        valueText: "movie",      },    },    mergeFiltersOperator: "or",  },});

See the [official docs](https://weaviate.io/developers/weaviate/api/graphql/filters) for more on how to construct metadata filters.

* * *

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

[

Previous

Vectara Self Query Retriever

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

Next

Similarity Score Threshold

](/v0.1/docs/modules/data_connection/retrievers/similarity-score-threshold-retriever/)

*   [Usage](#usage)

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.