tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Generative AI > Graph RAG > Natural Language Q and A over Employee Graph using LangChain and Neo4j

Natural Language Q and A over Employee Graph using LangChain and Neo4j

Author: Venkata Sudhakar

ShopMax India HR managers want to query the employee graph using plain English - questions like 'Who are all the engineers in Bangalore?' or 'Which employees report to Priya Nair?' without writing Cypher. LangChain's GraphCypherQAChain connects an LLM to a Neo4j database: it converts a natural language question into a Cypher query, executes it, and then uses the LLM to compose a readable answer from the results. This turns the employee graph into a conversational HR assistant that any manager can use.

GraphCypherQAChain works in two LLM calls. The first call takes the user question plus the Neo4j schema (node labels, relationship types, properties) and generates a valid Cypher query. The second call takes the raw query result and the original question and writes a natural language answer. The Neo4jGraph class from langchain-community handles schema introspection and query execution automatically. The chain needs OPENAI_API_KEY (or any supported LLM) and a running Neo4j instance with the employee data loaded.

The example below loads the ShopMax India employee org chart into Neo4j, then runs GraphCypherQAChain to answer three HR questions in plain English: who reports to the CTO, which city has the most engineers, and what role does Divya Pillai hold.


It gives the following output,

Q: Who reports directly to Arjun Sharma?
Generated Cypher: MATCH (emp:Employee)-[:REPORTS_TO]->(cto:Employee {name: 'Arjun Sharma'}) RETURN emp.name, emp.role
A: Priya Nair (VP Engineering) and Rahul Mehta (VP Products) report directly to Arjun Sharma.

Q: Which city has the most employees?
Generated Cypher: MATCH (emp:Employee) RETURN emp.city, count(*) AS count ORDER BY count DESC LIMIT 1
A: Bangalore has the most employees with 4 staff members.

Q: What role does Divya Pillai hold?
Generated Cypher: MATCH (emp:Employee {name: 'Divya Pillai'}) RETURN emp.role
A: Divya Pillai holds the role of Developer.

In production, pass few-shot Cypher examples to the chain via the cypher_prompt parameter so the LLM generates more accurate queries for your schema. Validate generated Cypher with a EXPLAIN prefix before execution to catch syntax errors without running the query. Restrict the schema exposed to the LLM to only the labels and properties relevant to HR queries - this reduces hallucinations on large graphs with many node types. For ShopMax India, cache common question patterns and their Cypher templates so repeated queries bypass the LLM generation step entirely and return results faster.


 
  


  
bl  br