RAG & Retrieval

Deep Dive into Indexing Pipeline – Graph RAG

Inside the Graph RAG indexer: entity extraction, knowledge graphs, community detection, and summarization.

Key takeaways

  • The Graph RAG indexer has four stages: document loading and preprocessing, knowledge graph construction (entity extraction → KG triplets → KG build), community detection, and community report generation.
  • Entity extraction is the most consequential step — index quality depends on extractor quality. The extractor is a language model (fine-tuned small/large model or a public LLM) prompted to return entities and relationships as JSON, which are vectorized into a vectorDB and added as nodes/edges to a graph database.
  • Beyond the conventional KG, Dataworkz adds a domain-specific lexical graph that captures a document's hierarchical structure (e.g., the Apple SEC 10-K broken down section → chunk → entity), which improves support for Query Focused Summarisation (QFS).
  • Community detection algorithms (Leiden, Louvain; Hierarchical Leiden is recursive) group strongly connected nodes using a Modularity optimization function (range −½ to 1), then community IDs and members are augmented back into the graph database.
  • The final step uses an LLM to summarize each community from its member nodes; Dataworkz also supports a schema-driven approach, which lets retrieval move from entity-embedding lookups to converting user queries into Cypher queries.
On this pagesections

    A Beginner’s Guide to Retrieval-Augmented Generation with Graphs – The Indexer

    Graph RAG consists of two parts:

    1. Indexer
    2. Retriever

    In this blog, we deep dive into how the indexing pipeline works, and how we can build one from scratch. We further analyse the architectural choice that Dataworkz has used, and how it makes our Graph RAG better than the current available choices.

    Lets Understand the Indexer

    Indexing is the first step towards building a Graph RAG. Let’s have a quick look into the different parts of the indexer and further explore them in the upcoming sections.

    • Document Loading and Preprocessing
      1. Loading
      2. Chunking and Preprocessing
    • Knowledge Graph Construction
      1. Entity Extractor to extract entity and relationships
      2. Building Knowledge Graph (KG) triplets
      3. KG construction
    • Community Detection
      1. Filter set of nodes
      2. Invoke a Community detection algorithm to build hierarchical communities
      3. Enriching the KG with communities and the nodes and building out the hierarchies
    • Generating Community Report
      1. Each identified community is provided with a summary of its individual nodes.
      2. Augmenting all additional information generated back to our KG.

    This is a brief overview of the components of the Indexing pipeline. We will explore each of them in detail in the following sections.

    Document Loading and Preprocessing

    This is the entry point onto the Indexing Pipeline. Dataworkz with its wide array Data Loaders and Connectors enables its users to connect and load data from one of the available sources.

    Once the data is loaded, we then break the data into manageable chunks and perform data preprocessing on it, like Stemming, Feature Scaling, removing Duplicate Entries, Data Wrangling, Data Transformation, Outlier detection, etc.

    These chunks are then converted into vectors through the available list of Embedding Models. The vectorization is crucial when building a hybrid system, which might also include a BM25 (indexer)  to create a lexical representation of the individual chunks.

    Knowledge Graph Construction

    This process can be further broken down into the following sub-components.

    1. Entity Extractor: The Entity Extractor is probably the most important step in building our Graph RAG, as the quality of our index depends on the extractor quality. The Extractor takes in chunks of text and returns the list of nodes (entities) and the edges (relationships) captured between them. Extractors can either be a private LLM, public LLM. To keep it simple an extractor is Language Model, which can be a Fine-tuned small/large Language model, or a public LLM (like OpenAI). Using Prompt Engineering we instruct the Extractor aka LLM/SLM to extract relevant entities and relationships.
    2. Building the KG: Post Entity Extraction, we process the entities through the following sequence. The Extracted Entity is vectorized and we store the vectors in a vectorDB. This step ties in nicely with our Hybrid Retriever (more on this on our Retriever Pipeline blog). Following the vectorization, we add the nodes and edges carefully to a Graph Database (handling duplicate nodes and edges).

    At the end of this step in our Indexing Pipeline, we have with us vectorized entities and a Knowledge Graph.

    This is how conventional Graph RAG systems work, but at Dataworkz, we added another step to the pipeline.

    To enrich our Databases, we add a Lexical Graph alongside our Indexed KG. This Lexical Graph is very domain specific and captures the intricate document structure and relationships amongst chunks.

    How do we build our Lexical Graph?

    The lexical Graph as stated, captures the overall layout of a document and provides a hierarchical overview of the dataset. Let’s take a look at the Apple SEC 10k annual report

    Figure 1

    Here the Apple 10k SEC annual report is broken down section wise, followed by chunk wise, further into different entities identified. Let’s take a closer look at the figure above.

    Figure 2

    We observe that from the chunk above we were able to extract an entity (node) called epic games, and the node also has properties like year, description and date, and the node label (ENTITY_TYPE) is LEGAL_PROCEEDING.

    Let’s take one more example:

    Figure 3

    We were able to extract NET_INCOME based figures from the table that’s part of the chunk, under section-8 in the AAPL 10k.

    Hopefully, we have established what we at Dataworkz are trying to achieve by augmenting the additional info to the existing KG. We have observed that adding a lexical structure of the entire document followed by the entities at each level, gives us a better leeway to achieving Query Focused Summarisation (QFS).

    A quick detour on Query Focused Summarisation:

    Query Focused Summarisation, is a text summarisation technique that aims to extract or generate a summary of an input document that directly answers or is relevant to a given query. We prepare our index in a way that supports QFS. We will explore more on this during our retrieval blog.

    Now that we understand what a lexical graph looks like, let’s understand how Dataworkz builds one.

    1. Defining a Schema of Entities to be extracted that is domain specific. For eg: Financial Domain needs entity_types pertaining to net income, revenue, ebitda, loss, market capital, etc.
    2. Using a Fine-tuned LLM, which is trained on the domain, to extract relevant entities.
    3. Build the Hierarchical representation by our document parser, to generate the Lexical Graph.

    Now one might wonder, how does the other extractor work?

    The Generic Entity Extractor uses a carefully designed prompt to capture all the relevant entities and nodes. The prompt along with the text chunk is passed on to a LLM, to extract a json response, which is then parsed and processed to build the KG.

    Example Prompt: 

    From the document provided below, extract all possible entities, following that capture all the relationships that are stated in the document between these entities you just extracted. Ensure you return a JSON response like below:

    {nodes: [

    {

    entity_type: “<entity_type>”,

    name: “<name of the entity extracted>”,

    description: “<a short description from the document source about the entity”,

    value: “<Applicable to Quantitative entities>”

    },

    {…..}

    ],

    relationships: [

    {

    “from”: “entity_1”

    “to”: “entity_2”,

    “description”: “ description of the relationship”

    }…

    ]

    We observe that at the end of this, we are left with a lexical graph and an Entity KG, which captures all relevant entities and the relationships amongst them, giving us a balanced index capturing an intricate relation between both the entities and between the entities and the chunks independently.

    Time For Community Detection

    Community Detection on the Extracted Graphs, lets us prepare our indexed dataset for QFS. This is one of the key pieces in our indexing pipeline. Community Detection algorithms like Leiden, Louvian, enable us to group together similar nodes into a community or cluster, which in turn allows us to build global summaries over a group of related nodes.

    Hierarchical Leiden is a recursive Leiden Algorithm, which builds hierarchical communities. The difference between having a community detection algorithm and a lexical graph, though both of them capture a tree like structure of the KG, is that Leiden as an algorithm uses an optimisation function called Modularity, which helps us decide what set of nodes have stronger internal network connections compared to their external network counterpart. We won’t go too deep into the algorithm’s functionality. But let’s take a quick look at the definition of Modularity.

    Figure 4

     

    So in short, Modularity tells us the strength of a group of networks aka community strength. It ranges from [-½, 1]. The indexed KG is now subjected to the community detection algorithm, which reverts back to us with community ids and nodes belonging to each community. We then parse the output and augment this data back to our Graph Database.

    Example Communities:

    Figure 5

    Generating Community Summaries

    This is the final step in our Indexing Pipeline. This step is similar to the entity extractor one, here we use a LLM (could be Private, Public, Fine-tuned) to summarize each community.

    Every community has a set of nodes under it. We create a community summary by creating an overall summary of all the nodes representing a community. This can be achieved by a carefully designed prompt, which captures all the commonalities in between identified nodes.

    Successful integration of community summaries, now gives us not only the entities, but communities and their summaries too, along with a lexical layout.

    Sample community summary for the communities mentioned above:

    Community  1:

    The provided text appears to be a financial report or an annual report on Form 10-K, which includes various sections related to the company’s operations and finances for the year ended December 31, 2023.

    Here are some key points extracted from the text:

    1. **Revenue**: Revenue increased by $2.4 billion, or 9%, primarily due to growth in gross bookings.
    2. **Operations and Support**: Operations and support expenses increased by $276 million, or 11%, mainly due to employee headcount costs, driver background checks, and external contractor expenses.
    3. **Sales and Marketing**: Sales and marketing expenses decreased by $400 million, or 8%, primarily due to a decrease in consumer discounts, promotions, credits, and refunds.
    4. **Research and Development**: Research and development expenses increased by $366 million, or 13%, mainly due to employee headcount costs and stock-based compensation.
    5. **General and Administrative**: General and administrative expenses decreased by $454 million, or 14%, primarily due to a decrease in other corporate expenses and legal settlements.
    6. **Depreciation and Amortization**: Depreciation and amortization expenses decreased by $124 million, or 13%, mainly due to the full amortization of acquired Postmates intangible assets.
    7. **Interest Expense**: Interest expense increased by $68 million, or 12%, primarily due to higher LIBOR and SOFR rates.
    8. **Other Income (Expense), Net**: Other income (expense) increased by $8.7 billion, mainly due to a change in the fair value of equity investments.

    **Provision for (Benefit from) Income Taxes**: Provision for income taxes increased by $394 million primarily due to deferred U.S. tax impacts related to investments.

    The pro forma financial information presents what our results would have been had we acquired Drizly and Transplace in the beginning of the applicable comparable prior annual reporting period.

    Community 2:

    Here is a concise summary that highlights the key points and central points

    **Summary:**

    Uber is involved in various legal actions and government investigations, including class action lawsuits in Australia related to driver classification and compliance with transport legislation. The company believes that the resolution of these matters will not have a material adverse effect on its consolidated financial position or liquidity but could be material to its consolidated results of operations.

    **Key Points:**

    1. Uber is party to various legal actions and government investigations.
    2. Class action lawsuits were filed in Australia against Uber entities by an Australian law firm on behalf of participants in the taxi, hire-car, and limousine industries.
    3. The plaintiff alleges that Uber conspired to injure the group members by breaching transport legislation or commissioning offenses against transport legislation.
    4. The claim alleges loss and damage to class representatives and members, including lost income and decreased value of taxi licenses.
    5. Four additional class action lawsuits were filed in 2020 alleging the same claims.

    **Central Points:**

    1. Uber intends to vigorously defend against the lawsuit.
    2. A trial has been scheduled to commence in March 2024.
    3. The company believes that the resolution of these matters will not have a material adverse effect on its consolidated financial position or liquidity but could be material to its consolidated results of operations.

    **Resolving Discrepancy:**

    There is no discrepancy between the texts, as they all describe the same set of legal proceedings and government investigations. The repetition of similar information in different sections is likely due to the formatting requirements of the Annual Report on Form 10-K.

    These points provide an overview of the company’s financial performance and expenses for the year ended December 31, 2023.

    Conclusion

    Designing an Indexing Pipeline and maintaining a Graph RAG system, is challenging and a complicated engineering problem. We at Dataworkz, allow users to not only build unsupervised graph generation, but also a conscious domain specific way to build Knowledge Graph by providing a schema. The schema expands our Query Retrieval step from depending on Entity Embeddings to using Cypher Queries to convert user queries into cypher queries.

    We will learn more on the Retrieval Process in our upcoming blog on Retrieval using Graph RAG.

    Frequently asked questions

    What are the main stages of a Graph RAG indexing pipeline?

    Per the post, the pipeline has four stages: document loading and preprocessing (loading, chunking, embedding, optionally BM25); knowledge graph construction via entity extraction and KG building; community detection to cluster related nodes; and generating community summaries. The output is a vectorized entity store plus an enriched knowledge graph.

    What is the role of the entity extractor in Graph RAG?

    The entity extractor takes chunks of text and returns nodes (entities) and edges (relationships) that form the knowledge graph. The post calls it the most important step because overall index quality depends on extractor quality. It can be a fine-tuned small/large language model or a public LLM, guided by prompt engineering to return a structured JSON of nodes and relationships.

    What is a lexical graph and why does Dataworkz add one?

    A lexical graph captures a document's overall layout and hierarchical structure (for example, an SEC 10-K broken down by section, then chunk, then extracted entity). The post states Dataworkz adds this domain-specific lexical graph alongside the indexed knowledge graph because the hierarchical structure gives better support for Query Focused Summarisation (QFS).

    What is community detection used for in the indexing pipeline?

    Community detection groups similar nodes into communities or clusters so the system can build global summaries over related nodes, which prepares the index for Query Focused Summarisation. The post mentions algorithms such as Leiden and Louvain, and notes Hierarchical Leiden builds hierarchical communities using a Modularity optimization function that measures community connection strength.

    How does a schema-driven knowledge graph change retrieval?

    The post states that providing a domain-specific entity schema lets the retrieval step move beyond depending on entity embeddings, instead converting user queries into Cypher queries to query the graph directly.

    See what your engineers can ship in production

    Dataworkz is the agentic AI platform enterprises trust to put AI agents into production. Teams build production-ready agents in days, every decision stays traceable, and every agent has ROI attached.

    Explore the platform