!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

*   [Use cases](/v0.1/docs/use_cases/)
    
    *   [SQL](/v0.1/docs/use_cases/sql/)
        
    *   [Chatbots](/v0.1/docs/use_cases/chatbots/)
        
    *   [Extraction](/v0.1/docs/use_cases/extraction/)
        
    *   [Query Analysis](/v0.1/docs/use_cases/query_analysis/)
        
    *   [Q&A with RAG](/v0.1/docs/use_cases/question_answering/)
        
    *   [Tool use](/v0.1/docs/use_cases/tool_use/)
        
    *   [Interacting with APIs](/v0.1/docs/use_cases/api/)
    *   [Tabular Question Answering](/v0.1/docs/use_cases/tabular/)
    *   [Graphs](/v0.1/docs/use_cases/graph/)
        
        *   [Quickstart](/v0.1/docs/use_cases/graph/quickstart/)
        *   [Constructing knowledge graphs](/v0.1/docs/use_cases/graph/construction/)
        *   [Mapping values to database](/v0.1/docs/use_cases/graph/mapping/)
        *   [Semantic layer over graph database](/v0.1/docs/use_cases/graph/semantic/)
        *   [Prompting strategies](/v0.1/docs/use_cases/graph/prompting/)
    *   [Summarization](/v0.1/docs/use_cases/summarization/)
    *   [Agent Simulations](/v0.1/docs/use_cases/agent_simulations/)
        
    *   [Autonomous Agents](/v0.1/docs/use_cases/autonomous_agents/)
        
    *   [Code Understanding](/v0.1/docs/use_cases/code_understanding/)
    *   [Audio/Video Structured Extraction](/v0.1/docs/use_cases/media/)

*   [](/v0.1/)
*   [Use cases](/v0.1/docs/use_cases/)
*   [Graphs](/v0.1/docs/use_cases/graph/)
*   Quickstart

On this page

Quickstart
==========

In this guide we’ll go over the basic ways to create a Q&A chain over a graph database. These systems will allow us to ask a question about the data in a graph database and get back a natural language answer.

⚠️ Security note ⚠️[​](#security-note "Direct link to ⚠️ Security note ⚠️")
---------------------------------------------------------------------------

Building Q&A systems of graph databases requires executing model-generated graph queries. There are inherent risks in doing this. Make sure that your database connection permissions are always scoped as narrowly as possible for your chain/agent’s needs. This will mitigate though not eliminate the risks of building a model-driven system. For more on general security best practices, [see here](/v0.1/docs/security/).

Architecture[​](#architecture "Direct link to Architecture")
------------------------------------------------------------

At a high-level, the steps of most graph chains are:

1.  **Convert question to a graph database query**: Model converts user input to a graph database query (e.g. Cypher).
2.  **Execute graph database query**: Execute the graph database query.
3.  **Answer the question**: Model responds to user input using the query results.

![SQL Use Case Diagram](/v0.1/assets/images/graph_usecase-34d891523e6284bb6230b38c5f8392e5.png)

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

First, get required packages and set environment variables. In this example, we will be using Neo4j graph database.

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

#### Install dependencies[​](#install-dependencies "Direct link to Install dependencies")

tip

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

*   npm
*   yarn
*   pnpm

    npm i langchain @langchain/community @langchain/openai neo4j-driver

    yarn add langchain @langchain/community @langchain/openai neo4j-driver

    pnpm add langchain @langchain/community @langchain/openai neo4j-driver

#### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables")

We’ll use OpenAI in this example:

    OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true

Next, we need to define Neo4j credentials. Follow [these installation steps](https://neo4j.com/docs/operations-manual/current/installation/) to set up a Neo4j database.

    NEO4J_URI="bolt://localhost:7687"NEO4J_USERNAME="neo4j"NEO4J_PASSWORD="password"

The below example will create a connection with a Neo4j database and will populate it with example data about movies and their actors.

    import "neo4j-driver";import { Neo4jGraph } from "@langchain/community/graphs/neo4j_graph";const url = Deno.env.get("NEO4J_URI");const username = Deno.env.get("NEO4J_USER");const password = Deno.env.get("NEO4J_PASSWORD");const graph = await Neo4jGraph.initialize({ url, username, password });// Import movie informationconst moviesQuery = `LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'AS rowMERGE (m:Movie {id:row.movieId})SET m.released = date(row.released),    m.title = row.title,    m.imdbRating = toFloat(row.imdbRating)FOREACH (director in split(row.director, '|') |     MERGE (p:Person {name:trim(director)})    MERGE (p)-[:DIRECTED]->(m))FOREACH (actor in split(row.actors, '|') |     MERGE (p:Person {name:trim(actor)})    MERGE (p)-[:ACTED_IN]->(m))FOREACH (genre in split(row.genres, '|') |     MERGE (g:Genre {name:trim(genre)})    MERGE (m)-[:IN_GENRE]->(g))`;await graph.query(moviesQuery);

    Schema refreshed successfully.

    []

Graph schema[​](#graph-schema "Direct link to Graph schema")
------------------------------------------------------------

In order for an LLM to be able to generate a Cypher statement, it needs information about the graph schema. When you instantiate a graph object, it retrieves the information about the graph schema. If you later make any changes to the graph, you can run the `refreshSchema` method to refresh the schema information.

    await graph.refreshSchema();console.log(graph.schema);

    Node properties are the following:Movie {imdbRating: FLOAT, id: STRING, released: DATE, title: STRING}, Person {name: STRING}, Genre {name: STRING}Relationship properties are the following:The relationships are the following:(:Movie)-[:IN_GENRE]->(:Genre), (:Person)-[:DIRECTED]->(:Movie), (:Person)-[:ACTED_IN]->(:Movie)

Great! We’ve got a graph database that we can query. Now let’s try hooking it up to an LLM.

Chain[​](#chain "Direct link to Chain")
---------------------------------------

Let’s use a simple chain that takes a question, turns it into a Cypher query, executes the query, and uses the result to answer the original question.

![graph_chain.webp](/v0.1/assets/images/graph_chain-6379941793e0fa985e51e4bda0329403.webp)

LangChain comes with a built-in chain for this workflow that is designed to work with Neo4j: [GraphCypherQAChain](https://python.langchain.com/docs/use_cases/graph/graph_cypher_qa)

    import { GraphCypherQAChain } from "langchain/chains/graph_qa/cypher";import { ChatOpenAI } from "@langchain/openai";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const chain = GraphCypherQAChain.fromLLM({  llm,  graph,});const response = await chain.invoke({  query: "What was the cast of the Casino?",});response;

    { result: "James Woods, Joe Pesci, Robert De Niro, Sharon Stone" }

### Next steps[​](#next-steps "Direct link to Next steps")

For more complex query-generation, we may want to create few-shot prompts or add query-checking steps. For advanced techniques like this and more check out:

*   [Prompting strategies](/v0.1/docs/use_cases/graph/prompting/): Advanced prompt engineering techniques.
*   [Mapping values](/v0.1/docs/use_cases/graph/mapping/): Techniques for mapping values from questions to database.
*   [Semantic layer](/v0.1/docs/use_cases/graph/semantic/): Techniques for working implementing semantic layers.
*   [Constructing graphs](/v0.1/docs/use_cases/graph/construction/): Techniques for constructing knowledge graphs.

* * *

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

[

Previous

Graphs

](/v0.1/docs/use_cases/graph/)[

Next

Constructing knowledge graphs

](/v0.1/docs/use_cases/graph/construction/)

*   [⚠️ Security note ⚠️](#security-note)
*   [Architecture](#architecture)
*   [Setup](#setup)
*   [Setup](#setup-1)
*   [Graph schema](#graph-schema)
*   [Chain](#chain)
    *   [Next steps](#next-steps)

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.