Certainly! To implement a knowledge graph within your existing code, we'll need to extend your DB class to handle entities (nodes) and relationships (edges) in the knowledge graph. We'll leverage Milvus to store and manage embeddings of the entities, and we'll use additional collections or fields to represent the relationships between entities.
Below is the updated code with knowledge graph functionality integrated:
from pymilvus import (
Collection, CollectionSchema, FieldSchema, DataType,
connections, utility
)
from sentence_transformers import SentenceTransformer
class KnowledgeGraphDB:
def __init__(
self,
node_collection_name="nodes",
edge_collection_name="edges",
host="localhost",
port="19530",
model_name='sentence-transformers/all-MiniLM-L6-v2'
):
# Connect to Milvus server
connections.connect("default", host=host, port=port)
self.node_collection_name = node_collection_name
self.edge_collection_name = edge_collection_name
self.model = SentenceTransformer(model_name)
self.dimension = self.model.get_sentence_embedding_dimension()
# Initialize node collection
if not utility.has_collection(self.node_collection_name):
self._create_node_collection()
else:
self.node_collection = Collection(self.node_collection_name)
self.node_collection.load()
# Initialize edge collection
if not utility.has_collection(self.edge_collection_name):
self._create_edge_collection()
else:
self.edge_collection = Collection(self.edge_collection_name)
self.edge_collection.load()
def _create_node_collection(self):
# Define the fields for the node collection schema
fields = [
FieldSchema(name="node_id", dtype=DataType.INT64, is_primary=True, auto_id=True),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=self.dimension),
FieldSchema(name="name", dtype=DataType.VARCHAR, max_length=256),
FieldSchema(name="attributes", dtype=DataType.JSON) # Additional attributes
]
schema = CollectionSchema(fields=fields, description="Knowledge Graph Nodes")
self.node_collection = Collection(self.node_collection_name, schema=schema)
self.node_collection.create_index(
field_name="vector",
index_params={
"index_type": "IVF_FLAT",
"metric_type": "COSINE",
"params": {"nlist": 128}
}
)
print(f"Node collection '{self.node_collection_name}' created successfully.")
def _create_edge_collection(self):
# Define the fields for the edge collection schema
fields = [
FieldSchema(name="edge_id", dtype=DataType.INT64, is_primary=True, auto_id=True),
FieldSchema(name="source_id", dtype=DataType.INT64),
FieldSchema(name="target_id", dtype=DataType.INT64),
FieldSchema(name="relation", dtype=DataType.VARCHAR, max_length=256),
FieldSchema(name="attributes", dtype=DataType.JSON) # Additional attributes
]
schema = CollectionSchema(fields=fields, description="Knowledge Graph Edges")
self.edge_collection = Collection(self.edge_collection_name, schema=schema)
print(f"Edge collection '{self.edge_collection_name}' created successfully.")
def add_node(self, name, attributes=None):
if attributes is None:
attributes = {}
# Encode the node name into a vector
vector = self.model.encode(name).tolist()
# Prepare data for insertion
data = [
[None], # node_id auto-generated
[vector],
[name],
[attributes]
]
self.node_collection.insert(data)
print(f"Node '{name}' added successfully.")
def add_edge(self, source_id, target_id, relation, attributes=None):
if attributes is None:
attributes = {}
# Prepare data for insertion
data = [
[None], # edge_id auto-generated
[source_id],
[target_id],
[relation],
[attributes]
]
self.edge_collection.insert(data)
print(f"Edge from node {source_id} to node {target_id} with relation '{relation}' added successfully.")
def search_nodes(self, query, limit=10):
# Encode the query into a vector
query_embedding = self.model.encode(query).tolist()
# Define search parameters
search_params = {"metric_type": "COSINE", "params": {"nprobe": 10}}
# Perform search in the collection
results = self.node_collection.search(
[query_embedding],
"vector",
param=search_params,
limit=limit,
output_fields=["node_id", "name", "attributes"]
)
# Parse and return search results
search_results = []
if results:
for result in results[0]:
node_info = {
"node_id": result.entity.get("node_id"),
"name": result.entity.get("name"),
"attributes": result.entity.get("attributes"),
"score": result.distance
}
search_results.append(node_info)
return search_results
def get_node_by_id(self, node_id):
# Retrieve a node by its ID
results = self.node_collection.query(
expr=f"node_id == {node_id}",
output_fields=["node_id", "name", "attributes"]
)
if results:
return results[0]
else:
print(f"No node found with ID {node_id}.")
return None
def get_edges_by_node_id(self, node_id):
# Retrieve edges connected to a node (both incoming and outgoing)
results = self.edge_collection.query(
expr=f"source_id == {node_id} || target_id == {node_id}",
output_fields=["edge_id", "source_id", "target_id", "relation", "attributes"]
)
return results
def delete_node_by_id(self, node_id):
# Delete a node and its associated edges
try:
# First, delete edges connected to the node
self.edge_collection.delete(
expr=f"source_id == {node_id} || target_id == {node_id}"
)
# Then, delete the node itself
self.node_collection.delete(expr=f"node_id == {node_id}")
print(f"Node with ID {node_id} and its edges deleted successfully.")
except Exception as e:
print(f"Error deleting node with ID {node_id}: {str(e)}")
def list_nodes(self):
# List all nodes in the collection
results = self.node_collection.query(
expr="node_id >= 0",
output_fields=["node_id", "name", "attributes"]
)
return results
def list_edges(self):
# List all edges in the collection
results = self.edge_collection.query(
expr="edge_id >= 0",
output_fields=["edge_id", "source_id", "target_id", "relation", "attributes"]
)
return results
def drop_graph(self):
# Drop the node and edge collections
if utility.has_collection(self.node_collection_name):
utility.drop_collection(self.node_collection_name)
print(f"Node collection '{self.node_collection_name}' dropped successfully.")
if utility.has_collection(self.edge_collection_name):
utility.drop_collection(self.edge_collection_name)
print(f"Edge collection '{self.edge_collection_name}' dropped successfully.")
# Additional methods can be added as needed for advanced functionalities
Explanation of the Code Changes
-
Separate Collections for Nodes and Edges: We created two separate collections:
- Nodes Collection (
node_collection): Stores nodes/entities in the knowledge graph.
- Edges Collection (
edge_collection): Stores edges/relationships between nodes.
-
Node Collection Schema:
node_id: Auto-incremented unique identifier for each node (primary key).
vector: Embedding vector of the node's name for similarity search.
name: The name or label of the node.
attributes: A JSON field to store additional properties of the node.
-
Edge Collection Schema:
edge_id: Auto-incremented unique identifier for each edge (primary key).
source_id: The node_id of the source node.
target_id: The node_id of the target node.
relation: The label or type of the relationship.
attributes: A JSON field to store additional properties of the edge.
-
Methods Added/Updated:
add_node: Adds a new node to the graph with optional attributes.
add_edge: Adds a new edge between two nodes with a specified relation and optional attributes.
search_nodes: Searches for nodes similar to a query string based on vector similarity.
get_node_by_id: Retrieves a node's information by its ID.
get_edges_by_node_id: Retrieves all edges connected to a node.
delete_node_by_id: Deletes a node and all its associated edges.
list_nodes and list_edges: Lists all nodes and edges in the graph.
drop_graph: Drops both the node and edge collections, effectively deleting the entire graph.
Usage Example
Here's how you can use the KnowledgeGraphDB class to build and interact with your knowledge graph:
# Initialize the Knowledge Graph database
kg_db = KnowledgeGraphDB()
# Add nodes
kg_db.add_node("Apple Inc.", attributes={"type": "Company", "founded": 1976})
kg_db.add_node("Steve Jobs", attributes={"type": "Person", "born": 1955})
kg_db.add_node("iPhone", attributes={"type": "Product", "released": 2007})
# Retrieve node IDs (assuming auto-generated IDs starting from 1)
apple_id = 1
steve_jobs_id = 2
iphone_id = 3
# Add edges (relationships)
kg_db.add_edge(steve_jobs_id, apple_id, "Founder")
kg_db.add_edge(apple_id, iphone_id, "Manufactures")
# Search for a node
search_results = kg_db.search_nodes("Apple")
print("Search Results:")
for node in search_results:
print(node)
# Get edges connected to a node
edges = kg_db.get_edges_by_node_id(apple_id)
print("Edges connected to Apple Inc.:")
for edge in edges:
print(edge)
Considerations
- Data Consistency: When deleting nodes, associated edges should be deleted to maintain graph integrity. This is handled in the
delete_node_by_id method.
- Indexing: We index the
vector field in the node collection for efficient similarity search.
- Scaling: For large graphs, consider using more advanced indexing and sharding strategies.
- Attributes Schema: The
attributes field is flexible but unstructured. If you require querying based on specific attributes, additional indexing or schema design may be needed.
Extending Functionality
You might want to add more methods to enhance your knowledge graph management, such as:
- Update Node/Edge Attributes: Methods to update the attributes of existing nodes or edges.
- Path Finding/Traversal: Implement algorithms for traversing the graph or finding paths between nodes.
- Advanced Queries: Support for complex queries based on attributes, relationships, and patterns.
Conclusion
By integrating the knowledge graph into your existing code, you can now store and manage entities and their relationships efficiently. Leveraging vector embeddings allows you to perform semantic searches over the nodes, enhancing the capabilities of your knowledge graph. The use of Milvus provides a scalable solution suitable for handling large amounts of data.
If you have any questions or need further assistance with extending the functionality, feel free to ask!