liveBook · Manning

Graph retriever

As explained in Knowledge Graphs and LLMs in Action

A retrieval component that returns relevant knowledge-graph information, such as nodes, relationships, or connecting subgraphs, for a query.

A graph retriever returns query-relevant knowledge-graph context: nodes, typed relationships, or subgraphs. It grounds generation in condensed, traceable, and potentially up-to-date information rather than relying only on vector similarity. section 13.4.3

A practical retrieval pipeline can:

  • Use metadata, properties, and relationships to filter documents or identify communities. section 13.4.3
  • Generate a Cypher query from the user question and graph schema. section 13.4.3
  • Return connecting subgraphs, such as shortest paths between requested entities. section 13.4.3
  • Combine graph context with document retrieval when a question spans structured facts and detailed source text. section 13.4.3

KG-enhanced document selection

A graph query can select only pages that mention every entity in a question, or only pages describing a particular relationship, reducing irrelevant vector-search results. section 13.4.3

Listing 13.5 KG-enhanced document retriever tool for a Graph RAG agent
from pydantic import BaseModel, Field
from langchain_community.graphs import Neo4jGraph


RE_SELECTOR_QUERY = """MATCH (p:Page)-   #1
[:MENTIONS_ENTITY]->(m1:Ent... 
WHERE e1.name = "{e1}" ...
...
RETURN DISTINCT p.id AS id, p.text AS text
"""


graph = Neo4jGraph(   #2
        url=os.environ['NEO4J_URL'],
        username=os.environ['NEO4J_USER'],
        password=os.environ['NEO4J_PWD'],
        database=os.environ['NEO4J_DB']
    )

class REDiarySelectorInput(BaseModel):   #3
    entity_source: str = Field(description="Source entity of the 
    relationship as mentioned in the question.")
    entity_source_class: str = Field(description=
      "Class of the source entity of the relationship. "
      "Available option is only one, 'Person'.")

 entity_target: str = Field(description="Target entity of the 
 relationship as mentioned in the question.")
 entity_target_class: str = Field(description=
      "Class of the target entity of the relationship. "
      "Available options are Person, Organization, Occupation and Title.")

 relationship: str = Field(description=
      "Relationship class between source and target entity. "
      "Available options: TALKED_ABOUT, TALKED_WITH, WORKS_WITH, WORKS_ON, 
      HAS_TITLE")


def kg_doc_selector(entity_source: str, entity_source_class: str, 
entity_target: str, entity_target_class: str, relationship: str) ->
List[AnyStr]:   #4
    query = RE_SELECTOR_QUERY.format(e1=entity_source,     
      e1_class=entity_source_class,
      e2=entity_target, e2_class=entity_target_class,
      rel_class=relationship)
 print(f"kg_doc_selector's query:\n{query}\n")

 try:
     res = graph.query(query)
     print(f"kg_doc_selector found {len(res)} matching documents")
 except Exception as e:
     print(f"Cypher execution exception: {e}")
     return []
    return [x['text'] for x in res[:3]]

The implementation pairs a Neo4j graph, a Cypher selector query, and a typed Pydantic tool input for an agent. section 13.4.3

How Knowledge Graphs and LLMs in Action covers it

How deep it goes
Explains subgraph, query, document, and combined retrieval patterns, then demonstrates a partial Neo4j tool implementation.
Examples
Uses shortest-path entity subgraphs, entity-constrained pages, relationship-focused documents, Neo4j, and Pydantic tool inputs.
What it assumes
Assumes a knowledge-graph schema and linked entities or documents, while illustrating retrieval choices from those structures.
What you can do after
Apply it via graph queries and agent tools to retrieve grounded subgraphs or targeted documents for response generation.
How it connects
Connects knowledge graphs with Graph RAG, Cypher, vector search, document retrieval, and AI agents.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Knowledge Graphs and LLMs in Action. The section links point to the parts of the book it draws on.