Indexing
Overview
Section titled “Overview”Indexing in byokg-rag enables efficient entity linking by mapping natural language mentions to knowledge graph nodes. The system supports three complementary index types that work together to match entities from user queries to graph entities with varying degrees of precision and semantic understanding.
Entity linking is a critical step in Knowledge Graph Question Answering (KGQA). When a user asks a question, the system must identify which entities in the knowledge graph are relevant. Indexes provide fast lookup mechanisms to find candidate entities based on string similarity, semantic meaning, or direct graph storage.
This document covers:
- Dense indexes for semantic similarity matching
- Fuzzy string indexes for approximate string matching
- Graph-store indexes for embedding-based retrieval directly from Neptune Analytics
- A hybrid entity matcher that fuses fuzzy and embedding candidates
- Graph embeddings: node and relation embeddings computed once per graph and cached on disk
- Guidance on selecting the appropriate index for your use case
Dense Index
Section titled “Dense Index”Purpose
Section titled “Purpose”Dense indexes use embeddings to find entities based on semantic similarity rather than exact string matches. This approach captures meaning and context, allowing the system to link entities even when the query uses different wording than the entity labels in the graph.
Architecture
Section titled “Architecture”The dense index stores vector embeddings of entity labels and uses similarity search to find the closest matches to a query embedding. The system supports local FAISS-based indexes for development and testing.
LocalFaissDenseIndex provides an in-memory vector index using FAISS (Facebook AI Similarity Search). It computes embeddings for entity labels and stores them in a FAISS index structure that enables fast approximate nearest neighbor search.
AWS Services
Section titled “AWS Services”Dense indexes require an embedding model to generate vector representations. The system integrates with:
- Amazon Bedrock - Provides access to foundation models for generating embeddings
IAM Permissions
Section titled “IAM Permissions”To use dense indexes with Amazon Bedrock embeddings, you need the following IAM permissions:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "bedrock:InvokeModel" ], "Resource": "arn:aws:bedrock:<region>::foundation-model/*" } ]}NOTE: Replace <region> with your AWS region (e.g., us-east-1).
Configuration
Section titled “Configuration”Configure a local FAISS dense index:
from graphrag_toolkit.byokg_rag.indexing import LocalFaissDenseIndex, LangChainEmbeddingfrom langchain_aws import BedrockEmbeddings
# Set up embedding modelbedrock_embeddings = BedrockEmbeddings( model_id="amazon.titan-embed-text-v2:0", region_name="<region>")embedding = LangChainEmbedding(bedrock_embeddings)
# Create dense indexdense_index = LocalFaissDenseIndex( embedding=embedding, distance_type="l2", # Options: "l2", "cosine" embedding_dim=1024 # Must match embedding model dimension)
# Add entities to indexentities = ["Albert Einstein", "Marie Curie", "Isaac Newton"]dense_index.add(entities)
# Query the indexresults = dense_index.query("physicist who developed relativity", topk=3)Parameters:
embedding- Embedding instance that generates vector representationsdistance_type- Distance metric for similarity (“l2” or “cosine”)embedding_dim- Dimension of embedding vectors (must match model output)
Fuzzy String Index
Section titled “Fuzzy String Index”Purpose
Section titled “Purpose”Fuzzy string indexes handle variations in entity names through approximate string matching. This approach is effective for typos, abbreviations, and minor spelling differences without requiring embeddings or semantic understanding.
Architecture
Section titled “Architecture”The fuzzy string index uses the thefuzz library to compute string similarity scores between query text and entity labels. It supports configurable matching thresholds and can filter candidates based on string length differences.
FuzzyStringIndex provides fast approximate string matching using Levenshtein distance and other string similarity algorithms. It maintains an in-memory mapping of entity labels and returns matches ranked by similarity score.
Configuration
Section titled “Configuration”Configure a fuzzy string index:
from graphrag_toolkit.byokg_rag.indexing import FuzzyStringIndex
# Create fuzzy string indexfuzzy_index = FuzzyStringIndex()
# Add entities to indexentities = ["Albert Einstein", "Marie Curie", "Isaac Newton"]fuzzy_index.add(entities)
# Query with fuzzy matchingresults = fuzzy_index.match( inputs=["Albert Einstien", "Mary Curie"], # Note: typos topk=1, max_len_difference=4)Parameters:
topk- Number of top matches to return per querymax_len_difference- A candidate more than this many characters shorter than the query is droppedid_selector- Optional function to filter candidates before matching
An LLM often lists several entities on one line (“Buffyverse, Australia, language”), or
adds words to a name (“the Galapagos Islands boat tours”). Each name is then much shorter
than the query, so the length filter drops every candidate and nothing links. With
keep_verbatim_names=True (constructor, off by default), a query left with no candidate
links the names written in it instead: names whose words occur in it as a run of whole
words, ignoring case and accents, up to topk. The longest run comes first. A name inside a
longer matching name is skipped, and so are one-character names and names that can’t name an
entity alone, such as “1982” or “Jr.”. Of names with the same words (“Paris”, “PARIS”), the
spelling written in the query comes first, and one name’s variants never crowd out another
name. match_score is then the share of the query’s words the name covers (0–100). Queries
that fuzzy matching already links are unchanged. The option applies to everything the index
matches, so in ByoKGQueryEngine it also links draft answers:
from graphrag_toolkit.byokg_rag.graph_retrievers import EntityLinkerfrom graphrag_toolkit.byokg_rag.indexing import FuzzyStringIndex
fuzzy_index = FuzzyStringIndex(keep_verbatim_names=True)fuzzy_index.add(["Australia", "Buffyverse", "Galápagos Islands", "Islands"])fuzzy_index.match(inputs=["Buffyverse, Australia, language"], topk=3)# Buffyverse and Australia; the default index returns nothingfuzzy_index.match(inputs=["the galapagos islands boat tours"], topk=3)# Galápagos Islands (Islands is inside it)
entity_linker = EntityLinker(fuzzy_index.as_entity_matcher()) # pass to ByoKGQueryEngineTIP: Fuzzy string matching works best for entity names with consistent structure. For highly variable entity descriptions, consider using dense indexes instead.
Graph Store Index
Section titled “Graph Store Index”Purpose
Section titled “Purpose”Graph-store indexes store embeddings directly in the graph database, eliminating the need for separate index infrastructure. This approach is available for Amazon Neptune Analytics, which supports vector storage and similarity search natively.
Architecture
Section titled “Architecture”NeptuneAnalyticsGraphStoreIndex stores entity embeddings as node properties in Neptune Analytics and uses the graph database’s built-in vector search capabilities. This provides a unified storage layer for both graph structure and semantic embeddings.
AWS Services
Section titled “AWS Services”Graph-store indexes require:
- Amazon Neptune Analytics - Graph database with native vector search support
- Amazon Bedrock - Embedding model for generating vectors
- Amazon S3 - Storage for embedding data during bulk loading
IAM Permissions
Section titled “IAM Permissions”To use graph-store indexes with Neptune Analytics, you need:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "neptune-graph:ReadDataViaQuery", "neptune-graph:GetGraph" ], "Resource": "arn:aws:neptune-graph:<region>:<account-id>:graph/<graph-id>" }, { "Effect": "Allow", "Action": [ "bedrock:InvokeModel" ], "Resource": "arn:aws:bedrock:<region>::foundation-model/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": "arn:aws:s3:::<bucket-name>/*" } ]}NOTE: Replace <region>, <account-id>, <graph-id>, and <bucket-name> with your specific values.
Configuration
Section titled “Configuration”Configure a Neptune Analytics graph-store index:
from graphrag_toolkit.byokg_rag.graphstore import NeptuneAnalyticsGraphStorefrom graphrag_toolkit.byokg_rag.indexing import NeptuneAnalyticsGraphStoreIndex, LangChainEmbeddingfrom langchain_aws import BedrockEmbeddings
# Set up graph storegraph_store = NeptuneAnalyticsGraphStore( graph_identifier="<graph-id>", region="<region>")
# Set up embedding modelbedrock_embeddings = BedrockEmbeddings( model_id="amazon.titan-embed-text-v2:0", region_name="<region>")embedding = LangChainEmbedding(bedrock_embeddings)
# Create graph-store indexgraph_index = NeptuneAnalyticsGraphStoreIndex( graphstore=graph_store, embedding=embedding, distance_type="l2", embedding_s3_save_path="s3://<bucket-name>/embeddings/")
# Query the indexresults = graph_index.query("physicist who developed relativity", topk=3)Parameters:
graphstore- NeptuneAnalyticsGraphStore instanceembedding- Embedding instance for generating vectorsdistance_type- Distance metric for similarity (“l2” or “cosine”)embedding_s3_save_path- S3 path for storing embeddings during bulk operations
Hybrid Entity Matcher
Section titled “Hybrid Entity Matcher”Purpose
Section titled “Purpose”HybridEntityMatcher links a mention by combining fuzzy string matching with embedding
similarity, so a paraphrase that fuzzy matching drops can still link, while exact names stay
stable.
Architecture
Section titled “Architecture”For each mention, each matcher contributes its top candidate_depth nodes (at least the
requested topk), and the candidates are fused by reciprocal rank: score = sum of
1 / (rrf_k + rank) over the matchers that returned the node. Ranks are used because fuzzy
scores (0–100) and cosine similarities aren’t comparable. Equal scores go to the better fuzzy
rank, so fuzzy’s first choice is displaced only by a node both matchers return, or when
fuzzy returns nothing, and at a fixed topk embedding candidates can take the place of
fuzzy’s lower-ranked ones. A node in the fuzzy index whose name equals the mention always
ranks first (verbatim, else case-insensitively). Dense search is an exact cosine scan in
numpy over the node embeddings, restricted to the nodes in the fuzzy index, so both
matchers draw from one node set: a node the table embeds but the fuzzy index lacks (a
destination-only node, while LocalKGStore.nodes() lists source nodes only) is never a
dense candidate. Mentions are embedded once each and cached (the cache_size most recent),
since they repeat across questions and iterations. A graph whose nodes are all opaque ids
has no node embeddings, and links by fuzzy matching alone.
Configuration
Section titled “Configuration”The graph store must provide get_triplets(), e.g. LocalKGStore:
from graphrag_toolkit.byokg_rag.config import ByoKGConfigfrom graphrag_toolkit.byokg_rag.graph_retrievers import EntityLinkerfrom graphrag_toolkit.byokg_rag.graphstore import LocalKGStorefrom graphrag_toolkit.byokg_rag.indexing import GraphEmbeddings, HybridEntityMatcher
graph_store = LocalKGStore(graph) # graph: {head: {relation: {"triplets": [[head, relation, tail], ...]}}}embedding = ByoKGConfig.to_embedding()graph_embeddings = GraphEmbeddings.build( graph_store.get_triplets(), embedding, cache_dir='embeddings/my-graph', extra_nodes=graph_store.nodes(), model_id=ByoKGConfig.embed_model)matcher = HybridEntityMatcher.from_nodes(graph_store.nodes(), embedding, graph_embeddings.nodes)entity_linker = EntityLinker(matcher) # works with group_by_mention / single_best_matchParameters:
node_ids- The nodes fuzzy matching and the exact-name rule cover, e.g.graph_store.nodes(); node ids are used as their names, as inLocalKGStoreembedding- Embedding instance; mentions are embedded as documents, like node namesnode_table- Thenodestable of aGraphEmbeddingsfor the same graphrrf_k- Reciprocal-rank constant, a positive number (default 60)candidate_depth- Candidates each matcher contributes before fusion (default 20)cache_size- Mention embeddings kept, least recently used dropped first;0disables the cache (default 10,000)
retrieve() forwards max_len_difference to the fuzzy index and, like it, rejects
id_selector; any other argument raises TypeError.
To fuse a configured fuzzy index instead, such as one with keep_verbatim_names=True, pass
it to the constructor: HybridEntityMatcher(fuzzy_index, graph_embeddings.nodes, embedding).
Graph Embeddings
Section titled “Graph Embeddings”GraphEmbeddings.build(triplets, embedding, cache_dir=None, extra_nodes=(), model_id=None)
embeds every named node and relation label of a graph once. Pass model_id so the cache
records the model and refuses to be reused with another one. Opaque Freebase ids are skipped,
and texts are cut to 2,048 characters, the Cohere Embed v3 limit on Bedrock. Graph texts go
through batch_embed; questions go through Embedding.embed_query, which asymmetric models
such as Cohere v3 encode differently (search_query vs search_document).
With cache_dir, each table is saved as texts.json, meta.json (model id and dimension)
and vectors.npy, which is written last and marks the table complete. Finished chunks are
checkpointed under partial/, so a build interrupted by throttling resumes instead of
starting over. A cache whose texts, model, dimension or vector norms don’t match raises
rather than being reused; delete it to rebuild.
A graph whose nodes are all opaque ids gets an empty node table and is ranked by its relation labels alone; an empty graph embeds nothing, and text retrieval over it returns no triplets.
Index Selection Guide
Section titled “Index Selection Guide”Choose the appropriate index type based on your requirements:
| Index Type | Best For | Pros | Cons |
|---|---|---|---|
| Dense Index | Semantic matching, paraphrases, synonyms | Captures meaning, handles varied wording | Requires embedding model, higher latency |
| Fuzzy String Index | Typos, abbreviations, exact name variations | Fast, no external dependencies | Limited to string similarity, no semantic understanding |
| Hybrid Entity Matcher | Paraphrased or reworded mentions, on top of fuzzy matching | Keeps the exact match first, adds semantic candidates | Embeds every graph node once (cache it) and each lookup’s mentions; semantic candidates can outrank fuzzy’s, even its first when both matchers return another node; needs node ids that are names |
| Graph Store Index | Neptune Analytics deployments, unified storage | No separate index infrastructure, integrated with graph | Requires Neptune Analytics, S3 for bulk loading |
Recommendations:
- Use fuzzy string index as the default for most applications. It provides good performance with minimal setup.
- Add dense index when queries use varied terminology or when entity labels are inconsistent.
- Use graph-store index when deploying on Neptune Analytics to simplify infrastructure.
- Combine multiple indexes for comprehensive coverage. The entity linker can use multiple indexes in sequence.
TIP: Start with fuzzy string matching and add semantic indexes only if you observe poor entity linking performance in testing.