
Learn by Example Real-World RudraDB Tutorials
Master relationship-aware vector search through comprehensive, hands-on examples. From beginner tutorials to advanced use cases - everything you need to build the future of AI.
ā” 30-Second Quick Start
Zero configuration, maximum intelligence
Install
pip install rudradb-opin
Create & Add
import rudradb
import numpy as np
# Auto-detects dimensions!
db = rudradb.RudraDB()
# Add vectors with any embedding model
embedding = np.random.rand(384).astype(np.float32)
db.add_vector("doc1", embedding, {"title": "AI Guide"})
Search with Relationships
# Add relationships and search
db.add_relationship("doc1", "doc2", "semantic", 0.8)
# Relationship-aware search
params = rudradb.SearchParams(
include_relationships=True, # š„ The magic!
max_hops=2
)
results = db.search(query_embedding, params)
šÆ Comprehensive Examples
Master relationship-aware vector search through real-world scenarios
š Auto-Dimension Detection
BeginnerLearn how RudraDB-Opin automatically detects embedding dimensions from any ML model.
import rudradb
import numpy as np
# Zero configuration needed!
db = rudradb.RudraDB()
# Works with any dimension
embedding_384 = np.random.rand(384).astype(np.float32)
db.add_vector('doc1', embedding_384)
print(f"Auto-detected: {db.dimension()}D") # 384
# Different database, different dimension
db2 = rudradb.RudraDB()
embedding_768 = np.random.rand(768).astype(np.float32)
db2.add_vector('doc1', embedding_768)
print(f"Auto-detected: {db2.dimension()}D") # 768
š Building Relationships
BeginnerUnderstand the 5 relationship types and how to build intelligent connections.
import rudradb
import numpy as np
db = rudradb.RudraDB()
# Add documents
docs = {
'ai_intro': 'Introduction to Artificial Intelligence',
'ml_basics': 'Machine Learning Fundamentals',
'dl_advanced': 'Deep Learning Neural Networks'
}
for doc_id, content in docs.items():
embedding = np.random.rand(384).astype(np.float32)
db.add_vector(doc_id, embedding, {'content': content})
# Build intelligent relationships
db.add_relationship('ai_intro', 'ml_basics', 'hierarchical', 0.9) # Parent-child
db.add_relationship('ml_basics', 'dl_advanced', 'temporal', 0.8) # Learning sequence
db.add_relationship('ai_intro', 'dl_advanced', 'semantic', 0.7) # Related topics
print(f"Built {db.relationship_count()} intelligent connections!")
š Educational RAG System
IntermediateBuild a learning-focused RAG system with automatic relationship detection.
from sentence_transformers import SentenceTransformer
import rudradb
import numpy as np
class EducationalRAG:
def __init__(self):
self.model = SentenceTransformer('all-MiniLM-L6-v2')
self.db = rudradb.RudraDB() # Auto-detects 384D
def add_lesson(self, lesson_id, content, difficulty, topic):
embedding = self.model.encode([content])[0].astype(np.float32)
metadata = {
'content': content,
'difficulty': difficulty,
'topic': topic,
'type': 'lesson'
}
self.db.add_vector(lesson_id, embedding, metadata)
# Auto-build learning relationships
self._build_learning_relationships(lesson_id, metadata)
def _build_learning_relationships(self, lesson_id, metadata):
"""Automatically build educational relationships"""
for existing_id in self.db.list_vectors():
if existing_id == lesson_id:
continue
existing = self.db.get_vector(existing_id)
existing_meta = existing['metadata']
# Same topic ā semantic relationship
if metadata['topic'] == existing_meta['topic']:
self.db.add_relationship(lesson_id, existing_id, 'semantic', 0.8)
# Learning progression ā temporal relationship
difficulties = {'beginner': 1, 'intermediate': 2, 'advanced': 3}
if (difficulties.get(existing_meta['difficulty'], 2) -
difficulties.get(metadata['difficulty'], 2) == -1):
self.db.add_relationship(existing_id, lesson_id, 'temporal', 0.9)
def smart_search(self, query, learning_style='comprehensive'):
query_emb = self.model.encode([query])[0].astype(np.float32)
params = rudradb.SearchParams(
top_k=8,
include_relationships=True,
max_hops=2,
relationship_types=['temporal', 'hierarchical', 'semantic']
)
return self.db.search(query_emb, params)
# Usage
rag = EducationalRAG()
rag.add_lesson('ai_intro', 'AI basics and concepts', 'beginner', 'ai')
rag.add_lesson('ml_fundamentals', 'ML algorithms', 'intermediate', 'ai')
results = rag.smart_search('learn machine learning')
print(f"Found {len(results)} educational resources!")
š¤ OpenAI Integration
IntermediateSeamlessly integrate with OpenAI embeddings with auto-dimension detection.
import openai
import rudradb
import numpy as np
class OpenAI_RudraDB:
def __init__(self, api_key):
openai.api_key = api_key
# Auto-detects OpenAI's 1536 dimensions
self.db = rudradb.RudraDB()
def add_document(self, doc_id, text, metadata=None):
# Get OpenAI embedding
response = openai.Embedding.create(
model="text-embedding-ada-002",
input=text
)
embedding = np.array(response['data'][0]['embedding'], dtype=np.float32)
# Add with auto-dimension detection
doc_metadata = {
'text': text[:500],
'model': 'ada-002',
'tokens': len(text.split()),
**(metadata or {})
}
self.db.add_vector(doc_id, embedding, doc_metadata)
print(f"Auto-detected dimension: {self.db.dimension()}") # 1536
def intelligent_search(self, question, include_relationships=True):
# Get question embedding
response = openai.Embedding.create(
model="text-embedding-ada-002",
input=question
)
query_embedding = np.array(response['data'][0]['embedding'], dtype=np.float32)
# Search with relationship awareness
params = rudradb.SearchParams(
top_k=5,
include_relationships=include_relationships,
max_hops=2,
relationship_weight=0.3
)
return self.db.search(query_embedding, params)
# Usage
# ai_db = OpenAI_RudraDB("your-api-key")
# ai_db.add_document("doc1", "AI transforms industries")
# results = ai_db.intelligent_search("artificial intelligence impact")
š¤ HuggingFace Integration
IntermediateMulti-model support with automatic dimension detection for any HuggingFace model.
from sentence_transformers import SentenceTransformer
import rudradb
import numpy as np
class MultiModel_RudraDB:
def __init__(self):
self.models = {}
self.databases = {}
def add_model(self, model_name):
"""Add any HuggingFace model with auto-dimension detection"""
model = SentenceTransformer(model_name)
self.models[model_name] = model
# Create database with auto-dimension detection
self.databases[model_name] = rudradb.RudraDB()
expected_dim = model.get_sentence_embedding_dimension()
print(f"Added {model_name} (expected: {expected_dim}D)")
def add_document(self, model_name, doc_id, text, metadata=None):
"""Add document using specified model"""
model = self.models[model_name]
db = self.databases[model_name]
# Encode with the specific model
embedding = model.encode([text])[0].astype(np.float32)
# Add to database - auto-detection in action
enhanced_metadata = {
'text': text[:500],
'model': model_name,
'expected_dim': model.get_sentence_embedding_dimension(),
**(metadata or {})
}
db.add_vector(doc_id, embedding, enhanced_metadata)
# Verify auto-detection
detected_dim = db.dimension()
expected_dim = model.get_sentence_embedding_dimension()
print(f"Model: {model_name}")
print(f" Expected: {expected_dim}D ā Detected: {detected_dim}D")
print(f" Match: {'ā
' if detected_dim == expected_dim else 'ā ļø'}")
# Usage - works with any models!
multi_db = MultiModel_RudraDB()
# Add different models - each gets auto-dimension detection
multi_db.add_model('all-MiniLM-L6-v2') # 384D
multi_db.add_model('all-mpnet-base-v2') # 768D
# Add documents to both models
multi_db.add_document('all-MiniLM-L6-v2', 'doc1', 'AI and machine learning')
multi_db.add_document('all-mpnet-base-v2', 'doc1', 'AI and machine learning')
print("ā
Multi-model auto-dimension detection successful!")
š§ Auto-Relationship Intelligence
AdvancedAdvanced auto-relationship detection with intelligent connection building.
import rudradb
import numpy as np
from sentence_transformers import SentenceTransformer
class IntelligentKnowledgeBase:
def __init__(self):
self.model = SentenceTransformer('all-MiniLM-L6-v2')
self.db = rudradb.RudraDB() # Auto-dimension detection
def add_document_with_intelligence(self, doc_id, text, metadata):
"""Add document with full auto-intelligence"""
# 1. Auto-dimension detection handles any model
embedding = self.model.encode([text])[0].astype(np.float32)
# 2. Add vector - dimension auto-detected on first vector
self.db.add_vector(doc_id, embedding, metadata)
# 3. Auto-relationship detection analyzes content and metadata
relationships_found = self._auto_build_smart_relationships(doc_id, metadata)
return relationships_found
def _auto_build_smart_relationships(self, new_doc_id, metadata):
"""Advanced auto-relationship detection"""
relationships_created = 0
# Analyze all existing vectors for intelligent connections
for existing_id in self.db.list_vectors():
if existing_id == new_doc_id:
continue
existing_vector = self.db.get_vector(existing_id)
existing_meta = existing_vector['metadata']
# SEMANTIC ANALYSIS: Content similarity detection
if metadata.get('category') == existing_meta.get('category'):
self.db.add_relationship(new_doc_id, existing_id, 'semantic', 0.8)
relationships_created += 1
print(f" š Semantic: {new_doc_id} ā {existing_id}")
# HIERARCHICAL ANALYSIS: Parent-child detection
if (metadata.get('type') == 'concept' and
existing_meta.get('type') == 'example'):
self.db.add_relationship(new_doc_id, existing_id, 'hierarchical', 0.9)
relationships_created += 1
print(f" š Hierarchical: {new_doc_id} ā {existing_id}")
# TEMPORAL ANALYSIS: Learning sequence detection
difficulties = {'beginner': 1, 'intermediate': 2, 'advanced': 3}
current_level = difficulties.get(metadata.get('difficulty', 'intermediate'), 2)
existing_level = difficulties.get(existing_meta.get('difficulty', 'intermediate'), 2)
if (abs(current_level - existing_level) == 1 and
metadata.get('topic') == existing_meta.get('topic')):
self.db.add_relationship(new_doc_id, existing_id, 'temporal', 0.85)
relationships_created += 1
print(f" ā° Temporal: {new_doc_id} ā {existing_id}")
return relationships_created
# Demo: Building Knowledge Base with Auto-Intelligence
print("š¤ Building AI Knowledge Base with Auto-Intelligence")
kb = IntelligentKnowledgeBase()
# Add documents - watch auto-relationship detection work!
documents = [
{
'id': 'ai_basics',
'text': 'Artificial Intelligence fundamentals',
'metadata': {'category': 'AI', 'difficulty': 'beginner', 'type': 'concept'}
},
{
'id': 'ml_intro',
'text': 'Machine Learning introduction',
'metadata': {'category': 'AI', 'difficulty': 'intermediate', 'type': 'concept'}
}
]
for doc in documents:
relationships = kb.add_document_with_intelligence(
doc['id'], doc['text'], doc['metadata']
)
print(f"\nā
Auto-created knowledge base with intelligent relationships!")
print("š RudraDB-Opin discovered connections automatically!")
š Multi-Hop Discovery
AdvancedDiscover connections through relationship chains that traditional databases miss.
import rudradb
import numpy as np
class ConnectionDiscovery:
def __init__(self):
self.db = rudradb.RudraDB()
def build_research_network(self):
"""Build a research paper network with complex relationships"""
# Research papers
papers = {
'transformer_paper': 'Attention Is All You Need - Transformer architecture',
'bert_paper': 'BERT: Bidirectional Encoder Representations',
'gpt_paper': 'GPT: Generative Pre-trained Transformer',
'vision_transformer': 'Vision Transformer: An Image is Worth 16x16 Words'
}
# Add papers with metadata
for paper_id, title in papers.items():
embedding = np.random.rand(384).astype(np.float32)
metadata = {'title': title, 'domain': 'AI', 'impact': 'high'}
self.db.add_vector(paper_id, embedding, metadata)
# Build research relationships
relationships = [
('transformer_paper', 'bert_paper', 'temporal', 0.9), # Transformer ā BERT
('transformer_paper', 'gpt_paper', 'temporal', 0.9), # Transformer ā GPT
('bert_paper', 'gpt_paper', 'semantic', 0.8), # Both use transformers
('transformer_paper', 'vision_transformer', 'hierarchical', 0.8), # Applied to vision
]
for source, target, rel_type, strength in relationships:
self.db.add_relationship(source, target, rel_type, strength)
print(f"š¬ Research network: {self.db.vector_count()} papers, {self.db.relationship_count()} connections")
def discover_research_connections(self, starting_paper, max_hops=2):
"""Discover research connections through relationship chains"""
print(f"\nš Discovering connections from '{starting_paper}':")
# Get connected papers through relationships
connected = self.db.get_connected_vectors(starting_paper, max_hops=max_hops)
# Organize by hop count
connections_by_hop = {}
for vector, hop_count in connected:
if hop_count not in connections_by_hop:
connections_by_hop[hop_count] = []
connections_by_hop[hop_count].append(vector)
total_discovered = 0
for hop_count in sorted(connections_by_hop.keys()):
papers = connections_by_hop[hop_count]
if hop_count == 0:
print(f" š Starting paper: {papers[0]['metadata']['title']}")
else:
print(f" {hop_count}-hop connections ({len(papers)} papers):")
for paper in papers:
title = paper['metadata']['title']
print(f" ā {paper['id']}: {title[:50]}...")
total_discovered += 1
print(f"\nš Discovered {total_discovered} connected papers!")
print(f" Traditional similarity search would miss these connections!")
return connected
# Demo: Research Discovery
discovery = ConnectionDiscovery()
discovery.build_research_network()
# Discover connections from Transformer paper
connections = discovery.discover_research_connections('transformer_paper', max_hops=2)
print("\nš Multi-hop discovery revealed hidden research connections!")
print(" This is the power of relationship-aware search! š§¬")
š§ Framework Integrations
Works seamlessly with your favorite ML frameworks
OpenAI
Auto-detects 1536D embeddings
HuggingFace
Any transformer model supported
Sentence Transformers
384D, 768D auto-detected
LangChain
Seamless integration
š Recommended Learning Path
Master relationship-aware vector search step by step
Start with Auto-Detection
Learn how RudraDB-Opin automatically handles dimensions
10 minutesBuild Relationships
Explore the 5 relationship types and their use cases
20 minutesML Framework Integration
Integrate with OpenAI, HuggingFace, or Sentence Transformers
30 minutesAdvanced Use Cases
Build RAG systems, recommendation engines, knowledge bases
60 minutesš Need Help?
Get support and connect with the community