### Perform Multi-Hop Path Query for Actors via Director Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Answers complex questions by traversing multiple relationships in the knowledge graph. This specific example finds actors who have appeared in other films by the same director as a given movie. ```python engine.actors_via_director("Inception") # "Which actors appear in other films by the same director?" ``` -------------------------------- ### Query with Hybrid Ranking and Print Results Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt This Python code demonstrates how to use the `hybrid_recommend` function to get recommendations for a given query. It then iterates through the results, printing the hybrid score, semantic score, PageRank score, and the title of each recommended item, formatted to three decimal places. ```python # Query with hybrid ranking results = hybrid_recommend("mind-bending reality", top_k=3) for r in results: print(f"hybrid={r['hybrid']:.3f} (sem={r['semantic']:.3f} + pr={r['pagerank']:.3f}) -> {r['title']}") ``` -------------------------------- ### Implement BFS Traversal Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md A Breadth-First Search implementation that explores the graph layer by layer up to a specified number of hops. It returns a dictionary mapping node IDs to their shortest hop distance from the start node. ```python def bfs(self, start: str, max_hops: int = 3) -> dict[str, int]: visited = {start: 0} queue = deque([start]) while queue: node = queue.popleft() depth = visited[node] if depth >= max_hops: continue for neighbour in self.neighbours(node): if neighbour not in visited: visited[neighbour] = depth + 1 queue.append(neighbour) return visited # {node_id: hop_distance} ``` -------------------------------- ### Dijkstra's Shortest Path Algorithm - Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Finds the cheapest path between two nodes in the graph using edge weights. It returns a list of node IDs representing the path, or None if no path exists. Lower edge weights indicate stronger or more direct connections. Requires an initialized KnowledgeGraph object and the start and end node IDs. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Setup graph with different edge weights kg.add_node("m_her", label="Movie", title="Her", year=2013, rating=8.0) kg.add_node("m_2001", label="Movie", title="2001: A Space Odyssey", year=1968, rating=8.3) kg.add_node("g_sci-fi", label="Genre", name="sci-fi") # Genre connections have weight 2.0 (weaker/broader connection) kg.add_edge("m_her", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("g_sci-fi", "m_2001", relation="GENRE_OF", weight=2.0) # Find shortest path between two movies path = kg.shortest_path("m_her", "m_2001") # Returns: ['m_her', 'g_sci-fi', 'm_2001'] ``` -------------------------------- ### Breadth-First Search (BFS) Traversal - Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Explores the graph layer by layer from a starting node, returning all reachable nodes with their hop distances. This is useful for finding all entities within a specified number of hops from a starting point. It requires an initialized KnowledgeGraph object and a starting node ID. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Setup a connected graph kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") kg.add_node("m_interstellar", label="Movie", title="Interstellar", year=2014, rating=8.7) kg.add_node("a_Matthew_McConaughey", label="Actor", name="Matthew McConaughey") kg.add_edge("m_inception", "d_Christopher_Nolan", relation="DIRECTED_BY", weight=1.0) kg.add_edge("d_Christopher_Nolan", "m_interstellar", relation="DIRECTED", weight=1.0) kg.add_edge("m_interstellar", "a_Matthew_McConaughey", relation="STARS", weight=1.5) # BFS with max 2 hops from Inception reachable = kg.bfs("m_inception", max_hops=2) # Returns: { # 'm_inception': 0, # starting node (0 hops) # 'd_Christopher_Nolan': 1, # 1 hop away # 'm_interstellar': 2 # 2 hops away # } # BFS with max 3 hops reaches the actor reachable_3_hops = kg.bfs("m_inception", max_hops=3) # Returns: { # 'm_inception': 0, # 'd_Christopher_Nolan': 1, # 'm_interstellar': 2, # 'a_Matthew_McConaughey': 3 # 3 hops away # } ``` -------------------------------- ### Get Incoming Neighbours - Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Retrieves a list of node IDs that point to the specified node (predecessors). This is useful for finding which entities reference a given node. The function can optionally filter by relation type. It requires an initialized KnowledgeGraph object. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Setup graph with director pointing to multiple movies kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("m_interstellar", label="Movie", title="Interstellar", year=2014, rating=8.7) kg.add_node("m_dark_knight", label="Movie", title="The Dark Knight", year=2008, rating=9.0) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") kg.add_edge("d_Christopher_Nolan", "m_inception", relation="DIRECTED", weight=1.0) kg.add_edge("d_Christopher_Nolan", "m_interstellar", relation="DIRECTED", weight=1.0) kg.add_edge("d_Christopher_Nolan", "m_dark_knight", relation="DIRECTED", weight=1.0) # Find who directed Inception (incoming DIRECTED edges) directors = kg.in_neighbours("m_inception", relation="DIRECTED") # Returns: ['d_Christopher_Nolan'] # Find all nodes pointing to the director referencing_nodes = kg.in_neighbours("d_Christopher_Nolan") # Returns: [] (director has no incoming edges in this example) ``` -------------------------------- ### Get Outgoing Neighbours - Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Retrieves a list of node IDs that a specified node points to. This function can optionally filter the results by relation type to follow only specific edge types. It requires an initialized KnowledgeGraph object. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Setup graph কেজি.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") kg.add_node("a_Leonardo_DiCaprio", label="Actor", name="Leonardo DiCaprio") kg.add_node("g_sci-fi", label="Genre", name="sci-fi") kg.add_edge("m_inception", "d_Christopher_Nolan", relation="DIRECTED_BY", weight=1.0) kg.add_edge("m_inception", "a_Leonardo_DiCaprio", relation="STARS", weight=1.5) kg.add_edge("m_inception", "g_sci-fi", relation="HAS_GENRE", weight=2.0) # Get all outgoing neighbours all_neighbours = kg.neighbours("m_inception") # Returns: ['d_Christopher_Nolan', 'a_Leonardo_DiCaprio', 'g_sci-fi'] # Filter by specific relation type director = kg.neighbours("m_inception", relation="DIRECTED_BY") # Returns: ['d_Christopher_Nolan'] actors = kg.neighbours("m_inception", relation="STARS") # Returns: ['a_Leonardo_DiCaprio'] genres = kg.neighbours("m_inception", relation="HAS_GENRE") # Returns: ['g_sci-fi'] ``` -------------------------------- ### Build a sample knowledge graph with nodes and edges Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Demonstrates how to populate a knowledge graph by adding nodes with attributes and defining directed relationships between them. It also shows how to retrieve and print graph statistics. ```python kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") kg.add_node("a_Leonardo_DiCaprio", label="Actor", name="Leonardo DiCaprio") kg.add_node("g_sci-fi", label="Genre", name="sci-fi") kg.add_edge("m_inception", "d_Christopher_Nolan", relation="DIRECTED_BY", weight=1.0) kg.add_edge("d_Christopher_Nolan", "m_inception", relation="DIRECTED", weight=1.0) kg.add_edge("m_inception", "a_Leonardo_DiCaprio", relation="STARS", weight=1.5) kg.add_edge("a_Leonardo_DiCaprio", "m_inception", relation="ACTED_IN", weight=1.5) kg.add_edge("m_inception", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("g_sci-fi", "m_inception", relation="GENRE_OF", weight=2.0) stats = kg.stats() print(f"Graph has {stats['nodes']} nodes and {stats['edges']} edges") print(f"Relation types: {', '.join(stats['relation_types'])}") ``` -------------------------------- ### Build and Query Movie Recommendation System in Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt This script demonstrates how to initialize a KnowledgeGraph and VectorStore, populate them with movie data, and perform hybrid queries. It includes logic for semantic search, graph traversal by relationships, and shortest path calculation between entities. ```python from core.knowledge_graph import KnowledgeGraph from core.vector_store import VectorStore def build_movie_system(): """Build a complete movie recommendation system.""" kg = KnowledgeGraph(name="MovieKG") vs = VectorStore() # Dataset movies = [ {"id": "m_inception", "title": "Inception", "year": 2010, "rating": 8.8, "director": "Christopher Nolan", "actors": ["Leonardo DiCaprio", "Tom Hardy"], "genres": ["sci-fi", "thriller"], "description": "Dream-sharing technology plants ideas in minds"}, {"id": "m_dark_knight", "title": "The Dark Knight", "year": 2008, "rating": 9.0, "director": "Christopher Nolan", "actors": ["Christian Bale", "Heath Ledger"], "genres": ["action", "thriller"], "description": "Batman faces the Joker's criminal anarchy in Gotham"}, {"id": "m_her", "title": "Her", "year": 2013, "rating": 8.0, "director": "Spike Jonze", "actors": ["Joaquin Phoenix"], "genres": ["sci-fi", "romance"], "description": "A writer falls for an AI operating system"}, ] # Build graph nodes for m in movies: kg.add_node(m["id"], label="Movie", **{k: v for k, v in m.items() if k != "id"}) directors = {m["director"] for m in movies} for d in directors: kg.add_node(f"d_{d.replace(' ', '_')}", label="Director", name=d) actors = {a for m in movies for a in m["actors"]} for a in actors: kg.add_node(f"a_{a.replace(' ', '_')}", label="Actor", name=a) genres = {g for m in movies for g in m["genres"]} for g in genres: kg.add_node(f"g_{g}", label="Genre", name=g) # Build edges (bidirectional) for m in movies: mid = m["id"] d_id = f"d_{m['director'].replace(' ', '_')}" kg.add_edge(mid, d_id, relation="DIRECTED_BY", weight=1.0) kg.add_edge(d_id, mid, relation="DIRECTED", weight=1.0) for genre in m["genres"]: g_id = f"g_{genre}" kg.add_edge(mid, g_id, relation="HAS_GENRE", weight=2.0) kg.add_edge(g_id, mid, relation="GENRE_OF", weight=2.0) for actor in m["actors"]: a_id = f"a_{actor.replace(' ', '_')}" kg.add_edge(mid, a_id, relation="STARS", weight=1.5) kg.add_edge(a_id, mid, relation="ACTED_IN", weight=1.5) # Build vector store docs = [{"id": m["id"], "text": f"{m['title']}. {m['description']}", "metadata": {"title": m["title"], "year": m["year"]}} for m in movies] vs.build(docs) return kg, vs # Build system kg, vs = build_movie_system() # Query 1: Semantic search print("=== Semantic Search ===") for r in vs.query("artificial intelligence consciousness", top_k=2): print(f" [{r['score']:.3f}] {r['metadata']['title']}") # Query 2: Same director traversal print("\n=== Same Director as Inception ===") inception_directors = kg.neighbours("m_inception", relation="DIRECTED_BY") for d_id in inception_directors: for movie_id in kg.neighbours(d_id, relation="DIRECTED"): if movie_id != "m_inception": movie = kg.get_node(movie_id) print(f" {movie['title']} ({movie['year']})") # Query 3: Shortest path print("\n=== Connection Path ===") path = kg.shortest_path("m_inception", "m_her") if path: labels = [kg.get_node(p).get("title") or kg.get_node(p).get("name") for p in path] print(f" {' -> '.join(labels)}") # Query 4: Graph stats stats = kg.stats() print(f"\n=== Graph Stats ===") print(f" Nodes: {stats['nodes']}, Edges: {stats['edges']}") print(f" Relations: {', '.join(stats['relation_types'])}") ``` -------------------------------- ### Visualize and Query Paths in KnowledgeGraph Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Demonstrates how to iterate through a node path to print human-readable labels and how to handle non-existent paths using the shortest_path method. ```python for node_id in path: node = kg.get_node(node_id) name = node.get("title") or node.get("name") print(f"{name} [{node['label']}]", end=" -> " if node_id != path[-1] else "\n") kg.add_node("m_isolated", label="Movie", title="Isolated Movie", year=2020, rating=5.0) no_path = kg.shortest_path("m_her", "m_isolated") ``` -------------------------------- ### Add Nodes and Edges to Knowledge Graph Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Demonstrates how to add nodes with metadata properties and directed edges with relationship types and weights to the KnowledgeGraph instance. ```python # Adding a movie node with properties kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) # Adding a directed edge with a relation type and weight kg.add_edge("m_inception", "d_Christopher_Nolan", relation="DIRECTED_BY", weight=1.0) ``` -------------------------------- ### Build Vector Store from Documents Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt This Python code snippet illustrates how to initialize and build a vector store. It takes a list of dictionaries, where each dictionary represents a document with an ID, text content, and associated metadata, and populates the vector store for semantic search. ```python vs = VectorStore() docs = [ {"id": "m_inception", "text": "Dream-sharing technology bends reality", "metadata": {"title": "Inception"}}, {"id": "m_matrix", "text": "Reality is a simulation by machines", "metadata": {"title": "The Matrix"}}, {"id": "m_her", "text": "AI operating system explores consciousness", "metadata": {"title": "Her"}} ] vs.build(docs) ``` -------------------------------- ### Calculate Shortest Path with Dijkstra Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Finds the cheapest path between two nodes in a weighted graph using a min-heap. It reconstructs the path by tracking parent pointers and selecting the minimum weight for parallel edges. ```python def shortest_path(self, src: str, dst: str) -> list[str] | None: dist = {src: 0.0} prev = {src: None} heap = [(0.0, src)] while heap: d, node = heapq.heappop(heap) if node == dst: # reconstruct path by following prev pointers ... for neighbour, edges in self._adj[node].items(): w = min(e["weight"] for e in edges) new_dist = d + w if new_dist < dist.get(neighbour, float("inf")): dist[neighbour] = new_dist prev[neighbour] = node heapq.heappush(heap, (new_dist, neighbour)) ``` -------------------------------- ### Initialize Knowledge Graph in Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Creates a new directed weighted property graph instance. Supports nodes with arbitrary properties, directed edges with relation types and weights, and bidirectional adjacency storage for efficient traversal. ```python from core.knowledge_graph import KnowledgeGraph # Create a new knowledge graph kg = KnowledgeGraph(name="MovieKG") # The graph stores: # - _nodes: dict mapping node_id to properties # - _adj: forward adjacency (src → {dst → [edge_dicts]}) # - _radj: reverse adjacency (dst → {src → [edge_dicts]}) ``` -------------------------------- ### Initialize in-memory vector database Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Initializes a VectorStore instance which uses TF-IDF for text embedding. This store manages internal mappings for vectors, metadata, and raw text. ```python from core.vector_store import VectorStore # Create a new vector store vs = VectorStore() ``` -------------------------------- ### Fit and Transform Text with TF-IDF Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Learns vocabulary and IDF weights from a corpus to transform text into sparse TF-IDF vectors. Useful for converting natural language queries into numerical representations. ```python from core.vector_store import TFIDFVectoriser vectoriser = TFIDFVectoriser() corpus = ["A thief steals secrets", "A hacker discovers reality"] vectoriser.fit(corpus) query = "AI consciousness" query_vector = vectoriser.transform(query) ``` -------------------------------- ### Tokenize and Preprocess Text Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt A utility function to normalize text by lowercasing, stripping punctuation, and removing stop words. Useful for preparing raw text for vectorization. ```python from core.vector_store import tokenise text = "A thief who steals corporate secrets through dream-sharing technology" tokens = tokenise(text) # Returns: ['thief', 'steals', 'corporate', 'secrets', 'through', 'dreamsharing', 'technology'] ``` -------------------------------- ### Index documents with TF-IDF Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Fits the TF-IDF vectorizer on a provided corpus of documents and indexes them. Each document must contain an ID, text content, and optional metadata. ```python from core.vector_store import VectorStore vs = VectorStore() documents = [ {"id": "m_inception", "text": "Inception...", "metadata": {"title": "Inception", "year": 2010}}, {"id": "m_matrix", "text": "The Matrix...", "metadata": {"title": "The Matrix", "year": 1999}} ] vs.build(documents) ``` -------------------------------- ### Find Shortest Path Between Two Items Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Determines the shortest connection path between any two items in the knowledge graph. It uses Dijkstra's algorithm, prioritizing direct links over broader category links. ```python engine.connection_path("Her", "2001: A Space Odyssey") # Her [Movie] → sci-fi [Genre] → 2001: A Space Odyssey [Movie] ``` -------------------------------- ### Perform Hybrid Recommendation Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Combines semantic relevance from a vector store with graph centrality (PageRank) for enhanced rankings. This approach aims for smarter recommendations by considering both meaning and connectivity. ```python engine.hybrid_recommend("mind-bending reality twisting thriller", top_k=4) ``` -------------------------------- ### Implement Hybrid Recommendation Function Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt This Python function, `hybrid_recommend`, combines semantic search results from a vector store with graph centrality scores (PageRank) from a knowledge graph. It calculates a hybrid score by weighting semantic similarity and PageRank, then returns the top K ranked recommendations. ```python def hybrid_recommend(query: str, top_k: int = 3): # Get semantic candidates candidates = vs.query(query, top_k=top_k * 2) # Compute PageRank pagerank = kg.pagerank() pr_vals = list(pagerank.values()) pr_min, pr_max = min(pr_vals), max(pr_vals) pr_range = pr_max - pr_min or 1 # Combine scores: 60% semantic + 40% graph centrality results = [] for r in candidates: pr_raw = pagerank.get(r["id"], 0) pr_norm = (pr_raw - pr_min) / pr_range hybrid = 0.6 * r["score"] + 0.4 * pr_norm results.append({ "title": r["metadata"]["title"], "semantic": round(r["score"], 4), "pagerank": round(pr_norm, 4), "hybrid": round(hybrid, 4) }) return sorted(results, key=lambda x: x["hybrid"], reverse=True)[:top_k] ``` -------------------------------- ### Retrieve Document by ID Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Fetches a full document record including ID, text, and metadata from the vector store. Returns None if the requested ID does not exist. ```python from core.vector_store import VectorStore vs = VectorStore() doc = vs.get("m_inception") if doc: print(f"Title: {doc['metadata']['title']}") print(f"Original text: {doc['text']}") missing = vs.get("m_nonexistent") ``` -------------------------------- ### Add Nodes and Edges to Knowledge Graph Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt This Python code snippet demonstrates how to add nodes (movies and genres) and edges (relationships like HAS_GENRE) to a knowledge graph. It initializes a graph and populates it with specific movie and genre data, including attributes like title, year, rating, and relation weights. ```python kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("m_matrix", label="Movie", title="The Matrix", year=1999, rating=8.7) kg.add_node("m_her", label="Movie", title="Her", year=2013, rating=8.0) kg.add_node("g_sci-fi", label="Genre", name="sci-fi") kg.add_edge("m_inception", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("m_matrix", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("m_her", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("g_sci-fi", "m_inception", relation="GENRE_OF", weight=2.0) kg.add_edge("g_sci-fi", "m_matrix", relation="GENRE_OF", weight=2.0) kg.add_edge("g_sci-fi", "m_her", relation="GENRE_OF", weight=2.0) ``` -------------------------------- ### Perform Semantic Search with Vector Store Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Executes a semantic search query against a vector store to find items based on the meaning of their descriptions. The query is converted to a TF-IDF vector, and results are ranked by cosine similarity. ```python engine.semantic_search("AI consciousness and what makes us human", top_k=4) ``` -------------------------------- ### Perform Multi-Hop Graph Queries Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Traverses a graph by following a specific sequence of relationship types. It maintains a list of valid paths and filters out cycles to ensure unique traversal results. ```python def multi_hop_paths(self, start: str, relation_chain: list[str]) -> list[list[str]]: current_paths = [[start]] for relation in relation_chain: next_paths = [] for path in current_paths: tail = path[-1] for nbr in self.neighbours(tail, relation=relation): if nbr not in path: next_paths.append(path + [nbr]) current_paths = next_paths return current_paths ``` -------------------------------- ### Retrieve Graph Statistics Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Retrieves high-level metadata about the graph, including total node counts, edge counts, and a list of unique relation types present in the instance. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") stats = kg.stats() ``` -------------------------------- ### Tokenize Text for Vectorization Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Cleans raw text by removing punctuation and filtering out common stop words. This prepares the input for conversion into a sparse vector format. ```python STOP_WORDS = {"a", "an", "the", "is", "in", "it", "of", "to", "and"} def tokenise(text: str) -> list[str]: tokens = [] for word in text.lower().split(): word = "".join(c for c in word if c.isalnum()) if word and word not in STOP_WORDS: tokens.append(word) return tokens ``` -------------------------------- ### Perform Graph Traversal for Same Director Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Finds other movies directed by the same director as a given movie using a 2-hop graph traversal. This leverages the relationships within the knowledge graph to discover connected items. ```python engine.same_director("Inception") ``` -------------------------------- ### Perform Semantic Search and Filter Results Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Executes a semantic query against the vector store to find relevant documents. Supports limiting results and excluding specific document IDs from the output. ```python results = vs.query("AI consciousness and what makes us human", top_k=4) for r in results: print(f"[{r['score']:.3f}] {r['metadata']['title']} ({r['metadata']['year']})") results_filtered = vs.query("AI consciousness", top_k=3, exclude_ids={"m_her"}) ``` -------------------------------- ### Compute Node Centrality with PageRank Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Calculates PageRank scores for all nodes in the graph using the iterative power method. This identifies influential nodes based on incoming connection weight and frequency. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # ... (graph population omitted) ... pagerank = kg.pagerank(damping=0.85, iterations=30) for node_id, score in list(pagerank.items())[:5]: node = kg.get_node(node_id) name = node.get("title") or node.get("name") print(f"{score:.4f} {name} [{node['label']}]") ``` -------------------------------- ### Retrieve Node Properties from Knowledge Graph in Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Returns the property dictionary for a node, or None if the node doesn't exist. Useful for looking up metadata like titles, names, years, or ratings. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") # Retrieve node properties movie = kg.get_node("m_inception") # Returns: {'label': 'Movie', 'title': 'Inception', 'year': 2010, 'rating': 8.8} print(f"{movie['title']} ({movie['year']}) - Rating: {movie['rating']}") # Output: Inception (2010) - Rating: 8.8 director = kg.get_node("d_Christopher_Nolan") print(f"Director: {director['name']}") # Output: Director: Christopher Nolan # Returns None for non-existent nodes missing = kg.get_node("m_nonexistent") # Returns: None ``` -------------------------------- ### Perform semantic similarity search Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Queries the indexed document store to find the most similar items based on cosine similarity of TF-IDF vectors. Returns results sorted by relevance. ```python from core.vector_store import VectorStore vs = VectorStore() # ... build index ... results = vs.query("AI and consciousness") ``` -------------------------------- ### Add Edge to Knowledge Graph in Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Creates a directed edge from source to destination with a relation type, optional weight (default 1.0), and arbitrary properties. Both nodes must exist before adding an edge. For bidirectional relationships, add two edges with inverse relation types. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Add nodes first kg.add_node("m_inception", label="Movie", title="Inception", year=2010, rating=8.8) kg.add_node("d_Christopher_Nolan", label="Director", name="Christopher Nolan") kg.add_node("a_Leonardo_DiCaprio", label="Actor", name="Leonardo DiCaprio") kg.add_node("g_sci-fi", label="Genre", name="sci-fi") # Create bidirectional director relationship (weight=1.0 for strong connection) kg.add_edge("m_inception", "d_Christopher_Nolan", relation="DIRECTED_BY", weight=1.0) kg.add_edge("d_Christopher_Nolan", "m_inception", relation="DIRECTED", weight=1.0) # Create bidirectional actor relationship (weight=1.5) kg.add_edge("m_inception", "a_Leonardo_DiCaprio", relation="STARS", weight=1.5) kg.add_edge("a_Leonardo_DiCaprio", "m_inception", relation="ACTED_IN", weight=1.5) # Create bidirectional genre relationship (weight=2.0 for looser connection) kg.add_edge("m_inception", "g_sci-fi", relation="HAS_GENRE", weight=2.0) kg.add_edge("g_sci-fi", "m_inception", relation="GENRE_OF", weight=2.0) ``` -------------------------------- ### Perform Multi-hop Path Traversal Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Traverses the graph following a specific sequence of relation types. This is used to extract complex relationships, such as finding actors associated with films directed by a specific director. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # ... (node and edge setup omitted for brevity) ... relation_chain = ["DIRECTED_BY", "DIRECTED", "STARS"] paths = kg.multi_hop_paths("m_inception", relation_chain) for path in paths: actor = kg.get_node(path[-1])["name"] movie = kg.get_node(path[-2])["title"] print(f"{actor} (in {movie})") ``` -------------------------------- ### Add Node to Knowledge Graph in Python Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Adds a node to the graph with a unique identifier, an optional label (type), and arbitrary key-value properties. Nodes must be added before they can be connected with edges. ```python from core.knowledge_graph import KnowledgeGraph kg = KnowledgeGraph(name="MovieKG") # Add a movie node with properties kg.add_node( "m_inception", label="Movie", title="Inception", year=2010, rating=8.8, genres=["sci-fi", "thriller", "action"] ) # Add a director node kg.add_node( "d_Christopher_Nolan", label="Director", name="Christopher Nolan" ) # Add actor nodes kg.add_node("a_Leonardo_DiCaprio", label="Actor", name="Leonardo DiCaprio") kg.add_node("a_Tom_Hardy", label="Actor", name="Tom Hardy") # Add genre nodes kg.add_node("g_sci-fi", label="Genre", name="sci-fi") kg.add_node("g_thriller", label="Genre", name="thriller") ``` -------------------------------- ### Compute Cosine Similarity Source: https://context7.com/orco82/learn-graph-vector-python/llms.txt Calculates the cosine similarity between two L2-normalized sparse vectors. Returns a float between 0 and 1 representing the degree of similarity. ```python from core.vector_store import cosine_similarity, _l2_normalise vec_a = {"dreams": 0.5, "reality": 0.3, "technology": 0.4} vec_b = {"dreams": 0.6, "consciousness": 0.4, "technology": 0.3} vec_a_norm = _l2_normalise(vec_a) vec_b_norm = _l2_normalise(vec_b) similarity = cosine_similarity(vec_a_norm, vec_b_norm) print(f"Similarity: {similarity:.4f}") ``` -------------------------------- ### Calculate Cosine Similarity for Vectors Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Computes the cosine similarity between two vectors represented as dictionaries. This is used to find similar documents by measuring the angle between their vector representations. Assumes vectors are L2-normalized, where the dot product equals cosine similarity. ```python def cosine_similarity(a: dict, b: dict) -> float: return sum(a.get(term, 0) * b.get(term, 0) for term in b) ``` -------------------------------- ### Compute PageRank Centrality Source: https://github.com/orco82/learn-graph-vector-python/blob/main/README.md Calculates node importance based on incoming connections using an iterative approach. It distributes rank scores across neighbors, converging on a stable ranking after multiple iterations. ```python def pagerank(self, damping: float = 0.85, iterations: int = 30) -> dict[str, float]: n = len(self._nodes) rank = {node: 1.0 / n for node in self._nodes} for _ in range(iterations): new_rank = {} for node in self._nodes: in_score = sum( rank[src] / max(len(self._adj[src]), 1) for src in self.in_neighbours(node) ) new_rank[node] = (1 - damping) / n + damping * in_score rank = new_rank return dict(sorted(rank.items(), key=lambda x: x[1], reverse=True)) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.