Build a Graph RAG system with LangChain and GraphRetriever (Go)

query_builder 20 min

Graph RAG is an enhancement to retrieval-augmented generation (RAG). Graph RAG uses vector search to find semantically similar documents, and then uses graph traversal to find connected documents through relationships like hyperlinks, citations, or references. This helps find documents that might not be semantically similar but are contextually connected. Similar to RAG, the found documents serve as context for a large language model (LLM).

In this tutorial, you will build a simple graph RAG system. First, you will build a graph from a small set of cross-linked HTML pages. Then, you will use the graph during the retrieval step of RAG to provide extended context to the LLM.

Install dependencies

Install the dependencies used in this tutorial. For example:

go get github.com/datastax/astra-db-go/v2 github.com/tmc/langchaingo

Store your credentials

For this tutorial, store your database’s Data API endpoint, application token, and OpenAI API key in environment variables:

Linux or macOS
export API_ENDPOINT=API_ENDPOINT
export APPLICATION_TOKEN=APPLICATION_TOKEN
export OPENAI_API_KEY=OPENAI_API_KEY
Microsoft Windows
set API_ENDPOINT=API_ENDPOINT
set APPLICATION_TOKEN=APPLICATION_TOKEN
set OPENAI_API_KEY=OPENAI_API_KEY

Build the graph

  1. Download the graph_rag_dataset.json sample dataset. This dataset is a JSON array describing a small set of cross-linked HTML pages.

  2. Copy the following code into a Go file, and replace the PATH_TO_DATA_FILE placeholder with the path to the JSON data file.

    This code processes the raw JSON dataset into a list of documents. Each document incudes a metadata.hyperlink field, which lists the links from that document’s HTML content, and a metadata.url field, which contains the URL of the document. These fields are used to build the graph during retrieval in the next section.

    Then, the code creates a collection that uses Astra DB as the backend and OpenAI as the embedding service. Finally, the code inserts the processed documents into the vector store.

    package main
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"os"
    	"regexp"
    
    	"github.com/datastax/astra-db-go/v2/astra"
    	"github.com/datastax/astra-db-go/v2/astra/filter"
    	"github.com/datastax/astra-db-go/v2/astra/options"
    	"github.com/tmc/langchaingo/embeddings"
    	"github.com/tmc/langchaingo/llms/openai"
    )
    
    // Helper to extract href values from HTML anchor tags
    var hrefRegex = regexp.MustCompile(`(?i)<a\s+(?:[^>]*?\s+)?href="([^"]*)"`)
    
    // Helper to extract href values from an HTML string
    func extractHyperlinks(html string) []string {
    	matches := hrefRegex.FindAllStringSubmatch(html, -1)
    	links := make([]string, 0, len(matches))
    	for _, m := range matches {
    		links = append(links, m[1])
    	}
    	return links
    }
    
    func main() {
    	ctx := context.Background()
    
    	endpoint := os.Getenv("API_ENDPOINT") (1)
    	applicationToken := os.Getenv("APPLICATION_TOKEN")
    	openaiAPIKey := os.Getenv("OPENAI_API_KEY")
    
    	if endpoint == "" || applicationToken == "" || openaiAPIKey == "" {
    		log.Fatal(
    			"Environment variables API_ENDPOINT, APPLICATION_TOKEN, OPENAI_API_KEY must be defined.",
    		)
    	}
    
    	dataFilePath := "PATH_TO_DATA_FILE" (2)
    
    	// Read the JSON file and parse it into a slice of objects
    	raw, err := os.ReadFile(dataFilePath)
    	if err != nil {
    		log.Fatal(err)
    	}
    	var jsonData []struct {
    		HTMLDoc string `json:"html_doc"`
    		URL     string `json:"url"`
    	}
    	if err := json.Unmarshal(raw, &jsonData); err != nil {
    		log.Fatal(err)
    	}
    
    	// Convert the slice into documents with extracted hyperlinks
    	type docRecord struct {
    		content   string
    		url       string
    		hyperlink []string
    	}
    	docs := make([]docRecord, len(jsonData))
    	for i, d := range jsonData {
    		docs[i] = docRecord{
    			content:   d.HTMLDoc,
    			url:       d.URL,
    			hyperlink: extractHyperlinks(d.HTMLDoc),
    		}
    	}
    
    	// Generate embeddings for the documents
    	// using LangChain OpenAI Embeddings
    	fmt.Println("Generating embeddings...")
    	llm, err := openai.New(openai.WithToken(openaiAPIKey))
    	if err != nil {
    		log.Fatal(err)
    	}
    	embedder, err := embeddings.NewEmbedder(llm)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	contents := make([]string, len(docs))
    	for i, d := range docs {
    		contents[i] = d.content
    	}
    	vectors, err := embedder.EmbedDocuments(ctx, contents)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Build the documents with embeddings
    	docsWithEmbeddings := make([]any, len(docs))
    	for i, d := range docs {
    		docsWithEmbeddings[i] = astra.NewDocument{
    			"content": d.content,
    			"metadata": map[string]any{
    				"url":       d.url,
    				"hyperlink": d.hyperlink,
    			},
    			"$vector": vectors[i],
    		}
    	}
    
    	// Initialize the Astra DB Data API client
    	client := astra.NewClient()
    	database := client.Database(endpoint, options.API().SetToken(applicationToken))
    
    	// Create a new collection
    	// (If a collection with the same name already exists,
    	//   that collection is used instead)
    	fmt.Println("Creating collection...")
    	collection, err := database.CreateCollection(ctx, "graph_rag_tutorial",
    		options.CreateCollection().UpdateVector(
    			options.Vector().
    				SetDimension(1536).
    				SetMetric(options.MetricCosine),
    		),
    	)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// In case a collection with this name already existed,
    	// delete any documents in the collection
    	if _, err := collection.DeleteMany(ctx, filter.F{}); err != nil {
    		log.Fatal(err)
    	}
    
    	// Insert the documents into the collection
    	fmt.Println("Inserting documents...")
    	if _, err := collection.InsertMany(
    		ctx,
    		docsWithEmbeddings,
    	); err != nil {
    		log.Fatal(err)
    	}
    }
    1 Store your database’s endpoint, application token, and OpenAI key in environment variables named API_ENDPOINT, APPLICATION_TOKEN, and OPENAI_API_KEY, as instructed in Store your credentials.
    2 Replace PATH_TO_DATA_FILE with the path to the JSON data file.
  3. Execute the code. You should see printed messages indicating embedding generation, collection creation, and document insertion.

Define a graph retriever

Copy the following code into a Go file.

This code defines a GraphRetriever that uses vector search to find relevant documents and then uses graph traversal to explore their connections.

The code is imported in the next section.

package graphretriever

import (
	"context"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/filter"
	"github.com/datastax/astra-db-go/v2/astra/options"
	"github.com/datastax/astra-db-go/v2/astra/sort"
	"github.com/tmc/langchaingo/schema"
)

// Interface used by GraphRetriever to generate query embeddings.
// It is satisfied by the result of embeddings.NewEmbedder
// from langchaingo.
type Embedder interface {
	EmbedQuery(ctx context.Context, text string) ([]float32, error)
}

// GraphRetriever first uses vector search to find relevant documents,
// then uses graph traversal to explore their connections via hyperlinks.
type GraphRetriever struct {
	Collection *astra.Collection
	Embedder   Embedder
	// Number of documents to fetch via vector search
	// for starting the traversal
	StartK int
	// Maximum total documents to retrieve during traversal
	SelectK int
	// Maximum traversal depth.
	// A value of 0 only performs vector search,
	// but does not do any graph traversal.
	MaxDepth int
}

// GetRelevantDocuments retrieves documents relevant to the query by
// first running a vector search and then
// traversing document hyperlinks up to MaxDepth.
func (r *GraphRetriever) GetRelevantDocuments(
	ctx context.Context,
	query string,
) ([]schema.Document, error) {
	// Generate an embedding vector for the search query
	queryVector, err := r.Embedder.EmbedQuery(ctx, query)
	if err != nil {
		return nil, err
	}

	// 1. Vector search for initial seed documents
	seedCursor := r.Collection.Find(
		filter.F{},
		options.CollectionFind().
			SetSort(sort.Vector(queryVector)).
			SetLimit(r.StartK),
	)
	defer seedCursor.Close()

	var seedDocs []schema.Document
	for seedCursor.Next(ctx) {
		var doc astra.Document
		if err := seedCursor.Decode(&doc); err != nil {
			return nil, err
		}
		seedDocs = append(seedDocs, docToSchema(doc))
	}
	if err := seedCursor.Err(); err != nil {
		return nil, err
	}

	retrievedDocs := make([]schema.Document, len(seedDocs))
	copy(retrievedDocs, seedDocs)

	retrievedURLs := make(map[string]struct{})
	for _, doc := range retrievedDocs {
		if url, ok := doc.Metadata["url"].(string); ok && url != "" {
			retrievedURLs[url] = struct{}{}
		}
	}

	// 2. Graph traversal
	frontier := seedDocs
	for depth := 0; depth < r.MaxDepth && len(retrievedDocs) < r.SelectK && len(frontier) > 0; depth++ {
		// Collect all unique hyperlinks from the current frontier
		linksToFetch := make(map[string]struct{})
		for _, doc := range frontier {
			if links, ok := doc.Metadata["hyperlink"].([]any); ok {
				for _, l := range links {
					if link, ok := l.(string); ok && link != "" {
						if _, seen := retrievedURLs[link]; !seen {
							linksToFetch[link] = struct{}{}
						}
					}
				}
			}
		}

		if len(linksToFetch) == 0 {
			break
		}

		// Build a slice of URLs for the $in filter
		linksSlice := make([]any, 0, len(linksToFetch))
		for link := range linksToFetch {
			linksSlice = append(linksSlice, link)
		}

		// Fetch documents matching these URLs from Astra DB
		linkCursor := r.Collection.Find(
			filter.F{"metadata.url": filter.F{"$in": linksSlice}},
		)

		var nextFrontier []schema.Document
		for linkCursor.Next(ctx) {
			if len(retrievedDocs) >= r.SelectK {
				break
			}
			var rawDoc astra.Document
			if err := linkCursor.Decode(&rawDoc); err != nil {
				linkCursor.Close()
				return nil, err
			}
			d := docToSchema(rawDoc)
			url, _ := d.Metadata["url"].(string)
			if url == "" {
				continue
			}
			if _, seen := retrievedURLs[url]; seen {
				continue
			}
			retrievedURLs[url] = struct{}{}
			retrievedDocs = append(retrievedDocs, d)
			nextFrontier = append(nextFrontier, d)
		}
		if err := linkCursor.Err(); err != nil {
			return nil, err
		}
		linkCursor.Close()
		frontier = nextFrontier
	}

	return retrievedDocs, nil
}

// Helper to convert an astra.Document into a schema.Document
func docToSchema(doc astra.Document) schema.Document {
	rawContent, _ := doc.Get("content")
	content, _ := rawContent.(string)
	rawMetadata, _ := doc.Get("metadata")
	metadata, _ := rawMetadata.(map[string]any)
	if metadata == nil {
		metadata = map[string]any{}
	}
	return schema.Document{
		PageContent: content,
		Metadata:    metadata,
	}
}

Use the graph for retrieval and generation

  1. Copy the following code into a Go file.

    This code uses the graph retriever from the previous section to perform a vector search to find the documents that are most similar to a given string, then traverses the graph to find connected documents. The documents found by the graph retriever are passed along with the original question to the LLM.

    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    	"os"
    	"strings"
    
    	"github.com/datastax/astra-db-go/v2/astra"
    	"github.com/datastax/astra-db-go/v2/astra/options"
    	"github.com/tmc/langchaingo/embeddings"
    	"github.com/tmc/langchaingo/llms/openai"
    	"github.com/tmc/langchaingo/schema"
    
    	"tutorial-graph-rag/graphretriever" (1)
    )
    
    func main() {
    	ctx := context.Background()
    
    	endpoint := os.Getenv("API_ENDPOINT") (2)
    	applicationToken := os.Getenv("APPLICATION_TOKEN")
    	openaiAPIKey := os.Getenv("OPENAI_API_KEY")
    
    	if endpoint == "" || applicationToken == "" || openaiAPIKey == "" {
    		log.Fatal(
    			"Environment variables API_ENDPOINT, APPLICATION_TOKEN, OPENAI_API_KEY must be defined.",
    		)
    	}
    
    	// Initialize the Astra DB Data API client and get the collection
    	client := astra.NewClient()
    	database := client.Database(endpoint, options.API().SetToken(applicationToken))
    	collection := database.Collection("graph_rag_tutorial")
    
    	// Initialize LangChain OpenAI LLM
    	llm, err := openai.New(
    		openai.WithToken(openaiAPIKey),
    		openai.WithModel("gpt-4o"),
    	)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Initialize LangChain Embeddings
    	embedder, err := embeddings.NewEmbedder(llm)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Initialize GraphRetriever.
    	// This retriever first uses vector search to find relevant documents,
    	// then uses graph traversal to explore their connections.
    	retriever := &graphretriever.GraphRetriever{
    		Collection: collection,
    		Embedder:   embedder,
    		// Number of documents to fetch via vector search
    		// for starting the traversal
    		StartK: 3,
    		// Maximum total documents to retrieve during traversal
    		SelectK: 10,
    		// Maximum traversal depth.
    		// A value of 0 only performs vector search,
    		// but does not do any graph traversal.
    		MaxDepth: 1,
    	}
    
    	// Define the prompt template
    	const promptTemplate = `Answer the question based only on the following context:
    
    %s
    
    Question: %s`
    
    	// Try these questions to explore the knowledge graph:
    	const question = "What is close to the Space Needle?"
    	// Alternative questions:
    	// - "What is in the Lower Queen Anne neighborhood?"
    	// - "What is in the same neighborhood as the Space Needle?"
    	// - "What connects the 1962 World's Fair to modern Seattle?"
    	// - "Where is Chihuly Garden and Glass?"
    
    	fmt.Printf("\nQuestion: %s\n\n", question)
    
    	// Build the RAG chain:
    	// 1. Retrieve relevant documents via vector search and graph traversal
    	docs, err := retriever.GetRelevantDocuments(ctx, question)
    	if err != nil {
    		log.Fatalf("Error during retrieval: %v", err)
    	}
    
    	// 2. Format the retrieved documents into a single context string
    	ctx2 := formatDocs(docs)
    
    	// 3. Inject the context and question into the prompt template
    	prompt := fmt.Sprintf(promptTemplate, ctx2, question)
    
    	// 4. Pass the formatted prompt to the LLM and print the response
    	response, err := llm.Call(ctx, prompt)
    	if err != nil {
    		log.Fatalf("Error during RAG query: %v", err)
    	}
    
    	fmt.Println("Answer:")
    	fmt.Println(response)
    }
    
    // Helper to concatenate content for use as LLM context
    func formatDocs(docs []schema.Document) string {
    	parts := make([]string, len(docs))
    	for i, doc := range docs {
    		parts[i] = doc.PageContent
    	}
    	return strings.Join(parts, "\n\n")
    }
    1 This is the GraphRetriever defined in the previous section. Update the import path as needed.
    2 Store your database’s endpoint, application token, and OpenAI key in environment variables named API_ENDPOINT, APPLICATION_TOKEN, and OPENAI_API_KEY, as instructed in Store your credentials.
  2. Execute the code. You should see the question print to the console, followed by the answer from the LLM.

Next steps

  • Ask different questions to see how the graph retriever performs.

  • Tune the StartK, SelectK, and MaxDepth parameters to see how this affects the results. Note that increasing these values will increase the number of documents retrieved and passed to the LLM, which will increase the cost of the operation.

    • StartK is the number of documents to retrieve via vector search for starting the graph traversal.

      Increasing StartK can help with questions that might match multiple documents.

    • SelectK is the number of documents to retrieve during graph traversal.

      Increasing SelectK can help with questions that require broad context.

    • MaxDepth is the maximum traversal depth.

      Increasing MaxDepth can help with questions that require more distant connections, but might also retrieve too many loosely related documents.

  • Try using a larger dataset.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM