A modern, responsive web-based client for interacting with Dgraph databases using DQL (Dgraph Query Language). This application provides an intuitive, mobile-first interface for database administrators and developers to work with Dgraph databases without needing to use command-line tools or write code.
-
🎯 Modern UI/UX
- Professional Design System: Modern browser-based development tool interface
- Chakra UI v3: Beautiful, accessible components with semantic design tokens
- Lucide Icons: Consistent, scalable icon system throughout the application
- Responsive Design: Mobile-first design that works perfectly on all devices
- Dark/Light Themes: Automatic theme switching with system preference detection
- Enhanced Accessibility: WCAG compliant components with full keyboard navigation
- Smooth Animations: Micro-interactions and transitions for better UX
-
🔌 Connection Management
- Connect to any Dgraph instance with endpoint URL configuration
- Optional API key support for secured Dgraph instances
- Visual connection status indicators with real-time updates
- Secure credential handling and connection state management
-
📊 Schema Management & Visualization
- View the current DQL schema with syntax highlighting
- Edit and update the schema with real-time feedback
- Support for all Dgraph schema types and directives
- Advanced Schema Visualization: Interactive graph representation of your database structure
- Smart Data Analysis: Automatically discovers types, predicates, and relationships from live data
- Real-time Insights: Shows instance counts and relationship mappings
- Click-to-Inspect: Interactive nodes and edges with detailed property panels
-
💻 DQL Query Interface
- Execute DQL queries against your Dgraph instance
- CodeMirror Integration: Advanced syntax highlighting and autocomplete
- Query Variables: Support for parameterized queries
- Error Handling: Descriptive error messages with context
- Fullscreen Mode: Distraction-free query editing
-
🎨 Results Visualization
- Multiple Visualization Engines: Sigma.js, react-graph-vis, and Leaflet.js
- Interactive Graph Visualization: Node and edge manipulation with physics simulation
- Geographic Data Support: Map-based visualization for location data
- Responsive Views: Toggle between graph, JSON, and map views
- Advanced Controls: Zoom, pan, node positioning, and simulation settings
-
📚 Query History & Learning
- Persistent storage of executed queries using browser localStorage
- Interactive Guides: Step-by-step DQL tutorials with examples
- Query Templates: Pre-built queries for common operations
- Learning Path: Progressive difficulty levels for DQL mastery
-
🧠 Intelligent Autocomplete
- Schema-Aware Suggestions: Based on your current Dgraph schema
- Context-Sensitive Completions: DQL queries and schema editing
- Real-Time Updates: Suggestions update as you modify schemas
- Function & Directive Support: Complete DQL language coverage
-
🔍 Vector Search & AI Integration
- Multi-Provider Support: OpenAI, Anthropic, and Ollama embeddings
- Semantic Search: Natural language queries converted to vector embeddings
- Local AI Support: Run embeddings locally with Ollama integration
- Auto-Query Generation: Automatically generates DQL vector search queries
- Variable Integration: Embeddings passed as query variables to Dgraph
-
🤖 Text to DQL (AI-Powered Query Generation)
- Natural Language Interface: Convert plain English to DQL queries
- MCP Integration: Uses Model Context Protocol for enhanced query generation
- Schema-Aware: Leverages your database schema for accurate queries
- Dual Mode: MCP server support with AI fallback
- One-Click Execution: Generated queries can be run immediately
The application follows a modern, scalable React architecture using Next.js 15 with the App Router, built with TypeScript and Chakra UI v3. The architecture emphasizes:
- Component-Based Design: Modular, reusable components with clear separation of concerns
- Type Safety: Full TypeScript coverage for better development experience
- Responsive Design: Mobile-first approach with progressive enhancement
- Performance: Optimized rendering with Next.js App Router and Turbopack
- Accessibility: WCAG compliant components and keyboard navigation
┌─────────────────────────────────────────────────────────────┐
│ Application Shell │
├─────────────────────────────────────────────────────────────┤
│ Toolbar │ Sidebar │ ContentPanel │
│ (Header)│ (Nav) │ (Dynamic Content) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Feature Components │
├─────────────────────────────────────────────────────────────┤
│ Connection │ Schema │ Guides │ Query │
│ Management │ Editor │ System │ Editor │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Data Layer │
├─────────────────────────────────────────────────────────────┤
│ DgraphContext │ DgraphService │ Local Storage │
│ (State Mgmt) │ (API Client) │ (Query History) │
└─────────────────────────────────────────────────────────────┘
dgraph-client-app/
├── src/
│ ├── app/ # Next.js App Router pages
│ │ ├── api/ # API routes for guides and data
│ │ ├── globals.css # Global styles and Chakra UI overrides
│ │ ├── layout.tsx # Root layout with Chakra UI providers
│ │ └── page.tsx # Main application page
│ ├── components/ # React components
│ │ ├── ui/ # Base UI components and theme
│ │ │ ├── provider.tsx # Chakra UI provider setup
│ │ │ ├── theme.ts # Custom theme with semantic tokens
│ │ │ └── color-mode.tsx # Theme switching logic
│ │ ├── __tests__/ # Component tests
│ │ ├── mdx/ # MDX rendering components
│ │ └── *.tsx # Feature components
│ ├── context/ # React Context providers
│ │ └── DgraphContext.tsx # Global Dgraph state management
│ ├── services/ # Business logic and API services
│ │ ├── dgraphService.ts # Dgraph API communication
│ │ └── embeddingService.ts # AI embedding generation service
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions and helpers
│ │ ├── vectorSearchBuilder.ts # Vector search query generation
│ │ └── *.ts # Other utility functions
│ └── styles/ # Component-specific styles
├── public/ # Static assets and images
├── jest.config.js # Jest testing configuration
├── next.config.ts # Next.js configuration
├── tsconfig.json # TypeScript configuration
└── package.json # Dependencies and scripts
-
Context-Based State Management
- Uses React Context API for global state (no external libraries)
- Provides Dgraph connection state throughout the application
- Manages theme switching and user preferences
-
Service Layer Pattern
- Isolates API communication in a dedicated service layer
- Abstracts Dgraph-specific operations and error handling
- Provides clean interfaces for data operations
-
Component Composition
- Modular components with single responsibilities
- Reusable UI elements with consistent styling
- Responsive design patterns throughout
-
Modern Design System
- Professional development tool interface with semantic design tokens
- Lucide React icon system for consistent visual language
- Enhanced accessibility with focus management and keyboard navigation
- Micro-interactions and smooth animations for better UX
The application follows modern browser-based development tool design patterns, drawing inspiration from VS Code, GitHub, and other professional developer tools:
- Clean Layout: Minimalist design focused on content and functionality
- Consistent Spacing: Systematic spacing scale using Chakra UI design tokens
- Professional Typography: Hierarchy with proper font weights and sizes
- Subtle Shadows: Layered elevation system for visual depth
- Border Radius: Consistent rounded corners (lg: 12px for cards, md: 8px for buttons)
- Hover Effects: Subtle color changes and elevation on interactive elements
- Focus States: Clear, accessible focus indicators for keyboard users
- Loading States: Professional loading indicators and disabled states
- Micro-animations: Smooth transitions (0.15s ease-in-out) for better perceived performance
- Lucide React: Professional icon library with 1000+ consistent icons
- Semantic Usage: Icons that clearly communicate function and state
- Consistent Sizing: 16px default with larger sizes (18-20px) for important actions
- Accessibility: All icons include proper ARIA labels and tooltips
- Connection Status: Real-time visual indicators with color-coded states
- Error Handling: Clear, actionable error messages with appropriate styling
- Success States: Positive feedback for completed actions
- Loading States: Professional spinners and skeleton states
The application supports comprehensive keyboard navigation for power users:
- Cmd/Ctrl + B: Toggle sidebar visibility
- Cmd/Ctrl + 1: Navigate to Connection section
- Cmd/Ctrl + 2: Navigate to Schema section
- Cmd/Ctrl + 3: Navigate to Guides section
- Cmd/Ctrl + 4: Navigate to Query section
- Cmd/Ctrl + 5: Navigate to Text to DQL section
- Tab Navigation: Logical tab order through all interactive elements
- Focus Trapping: Proper focus management in modals and panels
- Next.js 15 - React framework with App Router and Turbopack
- React 19 - Latest React with concurrent features
- TypeScript 5 - Static type checking and modern JavaScript features
- Chakra UI v3 - Modern component library with semantic design tokens
- Lucide React - Professional icon system with 1000+ consistent icons
- Emotion - CSS-in-JS styling solution
- Custom Theme System - Semantic color tokens and layer styles
- Responsive Design - Mobile-first approach with breakpoint system
- pnpm - Fast, disk space efficient package manager
- Turbopack - Next.js built-in bundler for fast development
- dgraph-js-http - Official Dgraph client for JavaScript
- axios - Promise-based HTTP client with interceptors
- CodeMirror 6 - Modern text editor with DQL syntax support
- @uiw/react-codemirror - React wrapper for CodeMirror
- Language Support - DQL, JSON, and SQL syntax highlighting
- Sigma.js - Modern graph visualization library
- react-sigma - React wrapper for Sigma.js
- Leaflet.js - Interactive maps for geographic data
- react-leaflet - React wrapper for Leaflet.js
- Vercel AI SDK - Unified interface for multiple AI providers
- @ai-sdk/openai - OpenAI integration for embeddings
- @ai-sdk/anthropic - Anthropic integration for embeddings
- Ollama Support - Local AI model inference for privacy-first deployments
- Jest - Test runner with React Testing Library
- ESLint - Code quality and consistency
- TypeScript - Compile-time error checking
The application is built with a mobile-first approach and provides an excellent experience across all device sizes:
- Mobile: 0px - 768px (full-width sidebar overlay)
- Tablet: 768px - 992px (medium sidebar width)
- Desktop: 992px+ (standard sidebar width)
- Adaptive Layout: Content adjusts based on screen size with consistent spacing
- Touch-Friendly: Optimized for mobile and tablet interaction with larger touch targets
- Smart Sidebar: Collapsible with icon-only mode (72px width) for efficient space usage
- Smooth Transitions: 300ms cubic-bezier animations for sidebar and content adjustments
- Fixed Toolbar: 60px height toolbar that stays accessible across all screen sizes
- Flexible Content: Main content expands dynamically to use available space
- Mobile Overlay: Intuitive dark backdrop when sidebar is open on mobile
- Progressive Enhancement: Enhanced features and labels appear on larger screens
The application features a comprehensive design system inspired by modern development tools like VS Code and GitHub:
// Sophisticated color palette
'bg.primary': { _light: '#fafafa', _dark: '#0a0a0a' }
'bg.secondary': { _light: '#ffffff', _dark: '#111111' }
'fg.primary': { _light: '#18181b', _dark: '#fafafa' }
'accent.primary': { _light: '#2563eb', _dark: '#3b82f6' }
'status.success': { _light: '#059669', _dark: '#10b981' }
- Navigation Items: Interactive hover states with smooth micro-animations and subtle transforms
- Status Badges: Professional indicators with icon and label combinations
- Code Editors: Enhanced focus states with custom border highlighting and shadows
- Cards & Panels: Elevated designs with consistent border radius (lg) and hover effects
- Buttons: Multiple variants (primary, secondary, ghost, toolbar) with proper states
- Input Fields: Large touch-friendly inputs with focus indicators
- Focus Management: Visible focus rings and logical tab order
- Keyboard Navigation: Cmd/Ctrl+B (sidebar), Cmd/Ctrl+1-4 (sections)
- Screen Reader Support: Proper ARIA labels and semantic markup
- Color Contrast: WCAG AA compliant color combinations
- Automatic Detection: Follows system preference by default
- Manual Override: Users can manually switch between light/dark
- Persistent: Theme choice is saved across sessions
- Smooth Transitions: Animated theme switching with CSS transitions
The application includes powerful vector search capabilities that enable semantic search using AI embeddings. This feature allows you to search your Dgraph data using natural language queries instead of exact matches.
Vector search converts text into numerical representations (embeddings) that capture semantic meaning. Similar concepts have similar embeddings, enabling "fuzzy" or semantic matching beyond exact text matches.
Traditional Search vs Vector Search:
# Traditional exact match
{ q(func: regexp(description, /database/i)) { uid name description } }
# Vector search for similar meaning
{ vectorSearch(by: description_embedding, vector: $queryVector, topk: 10) { uid name description } }
Configure your preferred embedding provider in the Connection Settings under "Vector Search Configuration":
- Select "OpenAI" as provider
- Enter your OpenAI API key
- Optionally specify model (defaults to
text-embedding-ada-002
)
- Select "Anthropic" as provider
- Enter your Anthropic API key
- Optionally specify model (defaults to
claude-3-haiku-20240307
)
- Install and run Ollama locally:
ollama serve
- Pull an embedding model:
ollama pull nomic-embed-text
- Select "Ollama (Local)" as provider
- Configure endpoint (defaults to
http://localhost:11434
) - Optionally specify model (defaults to
nomic-embed-text
)
- Open Vector Search: Click "Vector Search" button in Query Editor
- Enter Search Text: Type natural language description of what you're looking for
- Configure Field: Specify which field contains your vector embeddings
- Generate Query: Click "Generate Vector Search Query" to create DQL with embeddings
- Execute: Run the generated query to get semantic search results
Write DQL queries using the $queryVector
variable:
query vectorSearch($queryVector: [float], $topK: int, $alpha: float) {
vectorSearch(by: description_embedding, vector: $queryVector, topk: $topK, alpha: $alpha) {
uid
dgraph.type
name
description
description_embedding
}
}
// Search text: "comfortable running shoes"
// Generated query:
query vectorSearch($queryVector: [float], $topK: int, $alpha: float) {
vectorSearch(by: product_description_embedding, vector: $queryVector, topk: 10, alpha: 1.0) {
uid
dgraph.type
product_name
product_description
price
category
}
}
// Search text: "machine learning tutorials for beginners"
// Generated query:
query vectorSearch($queryVector: [float], $topK: int, $alpha: float) {
vectorSearch(by: content_embedding, vector: $queryVector, topk: 5, alpha: 1.0) {
uid
dgraph.type
title
content
author {
name
}
tags {
name
}
}
}
// Search text: "order cancellation refund policy"
// Generated query:
query vectorSearch($queryVector: [float], $topK: int, $alpha: float) {
vectorSearch(by: faq_embedding, vector: $queryVector, topk: 3, alpha: 1.0) {
uid
dgraph.type
question
answer
category
helpful_count
}
}
Define predicates to store vector embeddings:
type Product {
name: string @index(term) .
description: string .
description_embedding: [float] @index(hnsw(metric: "cosine", exponent: 4, m: 16, efConstruction: 100)) .
}
Create embeddings for your existing data (external script):
import { openai } from '@ai-sdk/openai';
import { embedMany } from 'ai';
const products = [/* your product data */];
const embeddings = await embedMany({
model: openai.embedding('text-embedding-ada-002'),
values: products.map(p => p.description)
});
// Store embeddings in Dgraph
{
set {
_:product1 <name> "Running Shoes" .
_:product1 <description> "Lightweight, comfortable running shoes perfect for daily training" .
_:product1 <description_embedding> "[0.1, -0.2, 0.3, ...]"^^<[float]> .
_:product1 <dgraph.type> "Product" .
}
}
Dgraph supports HNSW (Hierarchical Navigable Small World) indexing for efficient vector search:
# Optimal index configuration for different use cases
description_embedding: [float] @index(hnsw(metric: "cosine", exponent: 4, m: 16, efConstruction: 100)) .
# Parameters:
# - metric: "cosine", "euclidean", or "dotproduct"
# - exponent: Controls precision (2-6, higher = more precise)
# - m: Max bidirectional links (8-48, higher = better recall)
# - efConstruction: Build-time search width (100-800, higher = better quality)
- topK: Limit results (1-100, typically 5-20 for good performance)
- alpha: Similarity threshold (0.0-1.0, higher = more similar)
- Field Selection: Only query fields you need for better performance
- API Keys: Store securely, never commit to version control
- Environment Variables: Use
.env.local
for sensitive data - Rate Limiting: Be aware of provider API limits
- Batch Operations: Generate multiple embeddings together when possible
- Caching: Consider caching embeddings for frequently searched content
- Index Tuning: Adjust HNSW parameters based on your data size and accuracy needs
- Consistent Text: Normalize text before generating embeddings
- Meaningful Content: Ensure embedded text is descriptive and relevant
- Regular Updates: Regenerate embeddings when content changes significantly
- No Results: Check if your data has embeddings in the specified field
- API Errors: Verify API keys and provider configuration
- Ollama Connection: Ensure Ollama server is running and model is pulled
- Schema Issues: Verify vector fields have proper HNSW indexing
# Check if embeddings exist
{ q(func: has(description_embedding)) { uid count(description_embedding) } }
# Verify embedding format
{ q(func: has(description_embedding), first: 1) {
uid
description
description_embedding
} }
The Text to DQL feature allows you to generate DQL queries from natural language descriptions using AI. This powerful capability makes it easier for developers to interact with Dgraph databases without needing to memorize complex DQL syntax.
The Text to DQL system operates in two modes:
- MCP Mode (Enhanced): Uses a Model Context Protocol (MCP) server specifically designed for Dgraph
- Direct AI Mode (Fallback): Uses the Vercel AI SDK to generate queries directly
The system automatically leverages your database schema to generate more accurate and relevant queries.
-
Install the Dgraph MCP Server:
npm install -g @modelcontextprotocol/server-dgraph
-
Configure MCP in the Connection Tab:
- Navigate to the Connection section
- Expand "MCP Configuration"
- Enter your MCP config JSON:
{ "endpoint": "localhost:9080", "apiKey": "your-dgraph-api-key", "serverUrl": "http://localhost:3001/mcp" }
-
Start your MCP server (typically runs alongside your application)
The system automatically falls back to direct AI generation using the Vercel AI SDK if MCP is not configured or unavailable. This uses Anthropic's Claude model to generate queries.
- Navigate to Text to DQL tab in the left sidebar
- Ensure database connection - you must be connected to a Dgraph instance
- Enter your description in plain English:
Find all patients with diabetes who visited in the last month
- Generate query - click "Generate DQL Query"
- Review the generated DQL:
{ patients(func: eq(diagnosis, "diabetes")) @filter(ge(last_visit, "2024-07-01")) { uid dgraph.type name diagnosis last_visit } }
- Execute immediately - click "Execute Query" to run the generated query
Input: "Show me all movies from 2023" Generated DQL:
{
movies(func: eq(release_year, "2023")) {
uid
dgraph.type
title
release_year
genre
}
}
Input: "Find directors who have made more than 3 action movies" Generated DQL:
{
directors(func: type(Director)) @filter(gt(count(directed), 3)) {
uid
dgraph.type
name
directed @filter(eq(genre, "Action")) {
uid
title
genre
}
}
}
Input: "What's the average rating of sci-fi movies released after 2020?" Generated DQL:
{
query(func: allofterms(genre, "sci-fi")) @filter(ge(release_year, "2020")) {
avg_rating: avg(rating)
count: count(uid)
}
}
{
"endpoint": "your-dgraph-host:9080",
"apiKey": "your-api-key",
"serverUrl": "http://localhost:3001/mcp",
"timeout": 30000,
"maxRetries": 3
}
The system uses Anthropic's Claude Haiku model by default for fast, cost-effective query generation. The model selection is optimized for:
- Speed: Quick response times for interactive use
- Accuracy: Schema-aware generation using your database structure
- Cost-Effectiveness: Efficient token usage for query generation
- API Keys: MCP configuration is stored locally in browser localStorage
- Validation: Generated queries are validated before execution
- Sandboxing: MCP server runs in isolated environment
- Error Handling: Safe fallback to direct AI mode if MCP fails
-
"MCP Server not configured"
- Configure MCP in the Connection tab
- Ensure your MCP server is running
- Check the JSON configuration format
-
"Failed to generate query"
- Check your database connection
- Verify AI provider credentials (Anthropic API key)
- Try simpler language in your description
-
Generated query syntax errors
- The AI generates queries based on your schema
- Ensure your schema is properly loaded
- Try more specific descriptions with field names
- Check MCP Status: The Text to DQL tab shows MCP connection status
- Review Schema: Ensure your database schema is loaded and visible
- Start Simple: Begin with basic queries and gradually increase complexity
- Use Field Names: Include specific predicate names in your descriptions for better results
- Be Specific: Include field names and relationships in your descriptions
- Use Schema Terms: Reference types and predicates from your actual schema
- Start Simple: Begin with basic queries before moving to complex aggregations
- Review Generated Queries: Always review AI-generated queries before execution
- Iterate: Refine your natural language descriptions based on results
The Text to DQL feature represents a significant step toward making graph databases more accessible to developers of all skill levels, while maintaining the power and flexibility of DQL.
The Schema Visualization feature provides a comprehensive, interactive view of your Dgraph database structure. Unlike traditional schema viewers that only show static type definitions, this advanced visualization analyzes your live data to create a dynamic, relationship-rich representation of your database.
The visualization automatically analyzes your database to discover:
- Type Nodes: All types in your database with instance counts (e.g., "Patient (1,099)")
- Predicate Relationships: Actual connections between types based on your data
- Property Details: Complete predicate information for each type
- Real-time Updates: Live data analysis with refresh capability
- Clickable Type Nodes: Click any node to see all its predicates and properties
- Relationship Edges: Blue arrows showing connections between types with predicate labels
- Property Panel: Detailed view of predicates with type information, array flags, and references
- Professional Design: Clean, readable visualization with proper sizing and coloring
- Instance Counting: See how many instances of each type exist in your database
- Relationship Mapping: Understand which types connect to which other types
- Predicate Analysis: View all predicates for a type with detailed metadata
- Performance Optimized: Efficient queries that don't impact database performance
The visualization uses a sophisticated DQL query to analyze your database structure:
{
# Variable block to collect all typed nodes
var(func: has(dgraph.type)) {
all_typed_nodes as uid
}
# 1. GET ALL UNIQUE NODE TYPES WITH COUNTS
node_type_counts(func: has(dgraph.type)) @groupby(dgraph.type) {
count(uid)
}
# 2. COMPLETE SCHEMA DISCOVERY - No hardcoded predicates
schema_discovery(func: uid(all_typed_nodes), first: 100) {
node_type: dgraph.type
node_uid: uid
# Expand ALL predicates dynamically - captures everything
expand(_all_) {
# For any connected nodes, get their type to map relationships
relationship_target_type: dgraph.type
}
}
}
- Type Discovery: Identifies all types in your database with instance counts
- Predicate Extraction: Analyzes actual data to find all predicates for each type
- Relationship Mapping: Detects connections between types through UID predicates
- Graph Construction: Creates an interactive visualization with proper node and edge data
- Connect to Database: Ensure you're connected to your Dgraph instance
- Navigate to Schema: Click the "Schema" tab in the sidebar
- View Visualization: The graph loads automatically with your database structure
- Refresh Data: Click the "🔄 Refresh" button to update with latest data
- Overview: See all types as red nodes with instance counts
- Relationships: Blue arrows show how types are connected
- Click Nodes: Click any type node to see its predicates in the property panel
- Click Edges: Click relationship arrows to see connection details
- Fullscreen Mode: Use fullscreen for better visualization of large schemas
Node Types:
- Red Circles: Database types (e.g., Patient, Address, MedicalVisit)
- Node Labels: Type name with instance count (e.g., "Patient (1,099)")
- Node Sizes: Scaled based on instance count for visual hierarchy
Edge Types:
- Blue Arrows: Relationships between types
- Edge Labels: Predicate names or relationship counts
- Directional: Show the direction of relationships
Property Panel:
- Type Details: Shows selected type information
- Predicate List: All predicates with type, array, and UID information
- Reference Types: Which types are referenced by UID predicates
For a medical database, the visualization might show:
- Schema Visualization: 600px container with 450px graph area for optimal schema exploration
- Query Results: 500px graph containers for clear, usable query result visualization
- Guide Examples: Consistent 500px height across all graph visualization modes
- Responsive Design: Adapts to different screen sizes while maintaining usability
- Click-to-Inspect: Click nodes to see detailed predicate information
- Relationship Exploration: Click edges to understand type connections
- Property Panels: Dedicated panels for node and edge details
- Loading States: Professional loading indicators during data processing
- Color Coding: Consistent color scheme across all visualizations
- Node Sizing: Dynamic sizing based on data importance
- Edge Styling: Clear relationship indicators with proper labeling
- Layout Optimization: Force-directed layouts for optimal node placement
- Patient (1,099): Large node representing patient records
- MedicalVisit (764): Medium node for medical visits
- Address (635): Medium node for location data
- Organization (248): Smaller node for healthcare providers
- Patient → Address (via
lives_in
predicate) - Patient → MedicalVisit (via
has_visit
predicate) - MedicalVisit → Patient (via
visit_of
predicate) - Patient → MedicalCondition (via
has_condition
predicate)
Predicates (12):
- name: string [Array]
- age: int [Array]
- lives_in: uid [Array] → References: Address
- has_visit: uid [Array] → References: MedicalVisit
- has_condition: uid [Array] → References: MedicalCondition
- primary_language: string [Array]
- marital_status: string [Array]
- gender: string [Array]
- date_of_birth: string [Array]
- multiple_birth: bool [Array]
- Professional Loading Indicators: Spinner with progress messages
- Smooth Transitions: Loading → Complete visualization
- Disabled Controls: Prevents multiple refresh attempts during processing
- Hover Effects: Visual feedback on interactive elements
- Click Handlers: Separate handlers for nodes and edges
- Property Panels: Slide-in panels with detailed information
- Close Controls: Easy-to-access close buttons for panels
- Professional Color Scheme: Red nodes, blue edges, consistent styling
- Readable Labels: Clear typography with proper contrast
- Responsive Layout: Works on all screen sizes
- Accessibility: Keyboard navigation and screen reader support
- Predicate Grouping: Multiple predicates between same types are grouped
- Relationship Counts: Shows "3 relationships" for multi-predicate connections
- Target Type Analysis: Identifies all possible target types for predicates
- Efficient Queries: Optimized for large databases
- Smart Sampling: Uses limited sample size (100 nodes) for analysis
- Caching: Processes data once and caches results
- Background Processing: Non-blocking analysis with loading states
- Instance Counts: Understand data distribution across types
- Relationship Density: See which types are most connected
- Schema Completeness: Identify types with few or many predicates
- Data Patterns: Understand your database structure at a glance
- React + TypeScript: Type-safe component architecture
- Sigma.js Integration: Professional graph visualization library
- Graphology: Efficient graph data structure management
- Real-time Updates: Live data synchronization with database
- Fixed Height Containers: Eliminates CSS height inheritance issues
- Direct Height Assignment: SigmaGraph components use explicit 500px heights
- Container Hierarchy: Proper height flow from parent to child components
- Responsive Fallbacks: Maintains usability across different viewport sizes
- Container Validation: Sigma.js containers have proper dimensions
- Height Constraints: Prevents "Container has no height" errors
- Professional Sizing: 500px height provides substantial visualization space
- Consistent Layout: All graph modes maintain uniform height allocation
- Dynamic Discovery: No hardcoded predicates or types
- Efficient Sampling: Uses
first: 100
for performance - Relationship Detection: Automatic UID predicate identification
- Error Handling: Graceful fallbacks and error states
- Progressive Loading: Data loads incrementally with feedback
- Interactive Design: Click-to-explore interface
- Responsive: Works on mobile, tablet, and desktop
- Accessible: WCAG compliant with keyboard navigation
- New Database: Quickly understand structure of unfamiliar databases
- Data Modeling: Visualize relationships for schema design decisions
- Documentation: Generate visual documentation of database structure
- Training: Help team members understand data relationships
- Schema Validation: Verify relationships are properly modeled
- Data Quality: Identify types with unusual instance counts
- Performance Analysis: Understand query patterns and relationships
- Migration Planning: Visualize current state before schema changes
- Stakeholder Communication: Show database structure to non-technical users
- Data Governance: Understand data flow and relationships
- Compliance: Document data relationships for regulatory requirements
- Analytics Planning: Identify key entities and relationships for analysis
The Schema Visualization feature transforms the way you understand and work with your Dgraph database, providing immediate insights into your data structure and relationships through an intuitive, interactive interface.
The Geospatial Analysis feature provides an interactive, map-based interface for exploring and querying geospatial data in your Dgraph database. This powerful tool transforms location-based data into visual insights, making it perfect for applications requiring geographic analysis, location-based queries, and spatial intelligence.
- MapLibre GL JS Integration: High-performance, open-source mapping engine
- Professional Basemaps: CartoDB integration for clean, professional map tiles
- Responsive Controls: Navigation, zoom, and pan controls optimized for all devices
- Real-time Rendering: Smooth 60fps map interactions with WebGL acceleration
- Polygon Drawing: Draw custom areas for spatial queries
- Point & Line Tools: Support for different geometry types
- Interactive Drawing: Click-and-drag interface with visual feedback
- Geometry Validation: Automatic coordinate validation and polygon closure
- Automatic Predicate Detection: Discovers geospatial predicates in your database
- Pattern Recognition: Identifies common geospatial naming conventions
- Dynamic Query Generation: Creates queries for any discovered predicate
- Fallback Strategies: Multiple query approaches for maximum compatibility
- Real-time Statistics: Node counts, type distributions, and property analysis
- Interactive Charts: Visual representation of query results
- Property Aggregations: Statistical analysis of returned data
- Export Capabilities: Save results for further analysis
The component automatically discovers geospatial predicates using multiple strategies:
// Common geospatial predicate names to check
const commonGeoPredicates = [
'geometry', 'location', 'coordinates', 'boundary', 'area', 'shape',
'geo', 'spatial', 'lat', 'lng', 'lon', 'latitude', 'longitude',
'point', 'polygon', 'line', 'multipoint', 'multipolygon', 'multilinestring'
];
// Test each potential predicate individually
for (const predName of commonGeoPredicates) {
const testQuery = `{
q(func: has(${predName}), first: 1) {
uid
dgraph.type
${predName}
}
}`;
const result = await dgraphService.query(testQuery);
if (result.data?.q?.length > 0) {
potentialGeoPredicates.push(predName);
}
}
For each discovered predicate, the system generates optimized DQL queries:
// Generate queries for each discovered predicate
const queries = geoPredicates.map(predicate => {
const safePredicate = predicate.replace(/[^a-zA-Z0-9_]/g, '_');
return {
predicate,
safePredicate,
query: `{
q(func: has(${safePredicate})) @filter(within(${safePredicate}, "POLYGON((${polygonString}))")) {
uid
dgraph.type
${safePredicate}
expand(_all_)
}
}`
};
});
The system tries each query sequentially until one succeeds:
// Try each query until one succeeds
for (const { predicate, safePredicate, query: queryString } of queries) {
try {
result = await dgraphService.query(queryString);
if (result.data && result.data.q && result.data.q.length > 0) {
successfulPredicate = predicate;
setActivePredicate(predicate);
break;
}
} catch (queryError) {
console.log(`Query with predicate ${predicate} failed:`, queryError);
continue;
}
}
Query results are automatically rendered on the map with proper styling:
// Add results to map with different geometry types
mapRef.current.addLayer({
id: 'results-points',
type: 'circle',
source: 'query-results',
paint: {
'circle-radius': 8,
'circle-color': '#3B82F6',
'circle-stroke-color': '#1E40AF',
'circle-stroke-width': 2
},
filter: ['==', '$type', 'Point']
});
- Navigate to Geospatial Tab: Click the 6th tab (🗺️) in the sidebar
- Connect to Database: Ensure you're connected to a Dgraph instance
- Wait for Discovery: The system automatically discovers geospatial predicates
- Draw Query Area: Use the polygon tool to draw your search area
- Execute Query: Click "Execute Query" to run the spatial search
- Polygon Tool: Draw custom areas for spatial queries
- Point Tool: Mark specific locations
- Line Tool: Define linear features
- Clear Tool: Remove all drawings and start over
- Automatic Discovery: System finds all geospatial predicates
- Smart Querying: Tries each predicate until one succeeds
- Result Processing: Automatically processes and visualizes results
- Dashboard Updates: Real-time statistics and analysis
- Map View: Results displayed as interactive map features
- Dashboard: Statistical analysis and property aggregations
- Data Table: Detailed view of all returned nodes
- Export Options: Save results for further analysis
Scenario: Find all properties within a specific neighborhood
- Draw polygon around the neighborhood
- System discovers
location
predicate - Executes spatial query for properties
- Shows property distribution and statistics
Scenario: Analyze public transit coverage
- Draw lines along major routes
- System discovers
coordinates
predicate - Queries for nearby transit stops
- Visualizes coverage gaps and density
Scenario: Monitor pollution levels in specific areas
- Draw polygons around monitoring zones
- System discovers
boundary
predicate - Queries for environmental data points
- Shows pollution distribution and trends
Scenario: Find competitors within a radius
- Draw circle around target location
- System discovers
geo
predicate - Queries for nearby businesses
- Analyzes competitive landscape
- MapLibre GL JS: High-performance WebGL-based mapping
- React Integration: Seamless React component integration
- Custom Styling: Professional map appearance with CartoDB tiles
- Performance Optimization: Efficient rendering for large datasets
- Mapbox GL Draw: Professional drawing tools for map interactions
- Event Handling: Proper event management for drawing operations
- Geometry Validation: Automatic coordinate validation and correction
- Visual Feedback: Real-time drawing preview and editing
- Predicate Caching: Remembers discovered predicates for faster queries
- Query Batching: Efficient execution of multiple query strategies
- Error Handling: Graceful fallbacks and comprehensive error reporting
- Performance Monitoring: Real-time query performance tracking
- GeoJSON Conversion: Automatic conversion of Dgraph results to GeoJSON
- Geometry Type Detection: Supports points, lines, and polygons
- Property Mapping: Preserves all node properties for analysis
- Spatial Indexing: Optimized for large geospatial datasets
- Within Queries: Find nodes inside drawn polygons
- Near Queries: Find nodes within specific distances
- Intersection Queries: Find nodes intersecting with drawn areas
- Buffer Queries: Expand search areas with automatic buffering
- Clustering Analysis: Group nearby nodes for better visualization
- Density Mapping: Show data concentration across areas
- Hotspot Detection: Identify areas with high data density
- Trend Analysis: Track changes over time in specific areas
- GeoJSON Export: Save results in standard geospatial format
- CSV Export: Tabular data export for analysis tools
- Image Export: High-resolution map screenshots
- API Integration: RESTful endpoints for external tools
// Customize map appearance
const mapConfig = {
style: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',
center: [-74.006, 40.7128], // Default center coordinates
zoom: 10, // Default zoom level
maxZoom: 18, // Maximum zoom level
minZoom: 3 // Minimum zoom level
};
// Customize drawing tools
const drawConfig = {
displayControlsDefault: false,
controls: {
polygon: true, // Enable polygon drawing
point: true, // Enable point marking
line: true, // Enable line drawing
trash: true // Enable deletion tool
}
};
// Customize query behavior
const queryConfig = {
maxResults: 1000, // Maximum results to return
timeout: 30000, // Query timeout in milliseconds
retryAttempts: 3, // Number of retry attempts
fallbackQueries: true // Enable fallback query strategies
};
- Browser Compatibility: Requires WebGL support (IE11+, modern browsers)
- Data Size: Large datasets may impact performance (recommended: <10,000 nodes)
- Coordinate Systems: Currently supports WGS84 (lat/lng) coordinates
- Geometry Types: Limited to basic geometry types (Point, LineString, Polygon)
- Spatial Indexing: Requires proper spatial indexing for optimal performance
- Predicate Discovery: Limited to common geospatial naming patterns
- Query Complexity: Complex spatial queries may timeout on large datasets
- Schema Requirements: Geospatial predicates must be properly typed
- Map Rendering: Large result sets may slow down map interactions
- Query Execution: Complex spatial queries may take several seconds
- Memory Usage: Very large datasets may impact browser memory
- Network Latency: Remote Dgraph instances may have higher query times
- 3D Visualization: Support for 3D geospatial data and terrain
- Time Series: Temporal analysis of spatial data changes
- Spatial Statistics: Advanced statistical analysis of spatial patterns
- Machine Learning: AI-powered spatial pattern recognition
- Spatial Joins: Query relationships between different spatial datasets
- Buffer Analysis: Automatic buffer generation around features
- Network Analysis: Routing and network-based spatial queries
- Spatial Aggregation: Group and analyze data by spatial regions
- External GIS Tools: Integration with QGIS, ArcGIS, and other GIS software
- Real-time Data: Live data streaming and real-time updates
- Mobile Support: Native mobile applications for field work
- Cloud Integration: Direct integration with cloud geospatial services
- Custom Basemaps: Support for custom map tile servers
- Advanced Drawing: More sophisticated drawing tools and templates
- Collaborative Features: Multi-user editing and sharing
- Offline Support: Work with cached data when offline
- Consistent Naming: Use consistent naming for geospatial predicates
- Proper Indexing: Implement spatial indexes for performance
- Data Validation: Ensure coordinate data is valid and consistent
- Schema Documentation: Document geospatial data structure clearly
- Limit Results: Use reasonable limits for large datasets
- Index Usage: Ensure queries use available spatial indexes
- Error Handling: Implement proper error handling for failed queries
- Performance Monitoring: Track query performance and optimize as needed
- Clear Instructions: Provide clear guidance for drawing and querying
- Loading States: Show appropriate loading indicators during queries
- Error Messages: Display helpful error messages for failed operations
- Result Feedback: Provide clear feedback on query results
The Geospatial Analysis feature transforms your Dgraph database into a powerful spatial intelligence platform, enabling location-based insights and geographic analysis through an intuitive, interactive interface.
- Node.js: Version 18.17 or higher
- pnpm: Version 8.0 or higher (recommended) or npm 9+
- Git: Latest version
-
Clone the repository
git clone https://github.com/your-username/dgraph-client-app.git cd dgraph-client-app
-
Install dependencies
pnpm install
-
Start development server
pnpm run dev
-
Open your browser Navigate to
http://localhost:3000
to see the application
For default vector search configuration, create a .env.local
file:
# OpenAI Configuration (optional - can also be set in UI)
NEXT_PUBLIC_DEFAULT_EMBEDDING_PROVIDER=openai
NEXT_PUBLIC_OPENAI_API_KEY=your_openai_api_key
# Anthropic Configuration (optional - can also be set in UI)
NEXT_PUBLIC_ANTHROPIC_API_KEY=your_anthropic_api_key
# Ollama Configuration (optional - can also be set in UI)
NEXT_PUBLIC_OLLAMA_ENDPOINT=http://localhost:11434
NEXT_PUBLIC_DEFAULT_EMBEDDING_MODEL=nomic-embed-text
Note: API keys can be configured either through environment variables or the connection settings UI. The UI settings take precedence and are stored securely in browser localStorage.
# Development
pnpm run dev # Start development server with Turbopack
pnpm run build # Build for production
pnpm run start # Start production server
# Testing & Quality
pnpm run test # Run Jest tests
pnpm run test:watch # Run tests in watch mode
pnpm run test:coverage # Generate test coverage report
pnpm run lint # Run ESLint
pnpm run type-check # Run TypeScript type checking
# Maintenance
pnpm run clean # Clean dependencies and build artifacts
pnpm run reinstall # Clean and reinstall dependencies
- Start your Dgraph instance (locally or in the cloud)
- In the application, enter your Dgraph endpoint (e.g.,
http://localhost:8080
) - If your Dgraph instance requires authentication, enter your API key
- Click "Connect" to establish the connection
- HTTP/HTTPS: Standard web protocols
- DGraph Protocol: Native DGraph protocol with SSL support
- Hypermode: Cloud-hosted DGraph instances
- Local Development: Localhost connections for development
- SSL/TLS Support: Secure connections with certificate verification
- API Key Management: Secure storage of authentication credentials
- Connection Validation: Automatic endpoint validation and testing
- Interactive Schema Visualization: Explore your database structure through an interactive graph
- Live Data Analysis: See actual type counts and relationships from your data
- Click-to-Inspect: Click nodes to see predicates, click edges to see relationships
- Real-time Updates: Refresh to see latest database structure
- Syntax Highlighting: DQL syntax with CodeMirror integration
- Autocomplete: Schema-aware suggestions for predicates and functions
- Query Variables: Support for parameterized queries
- Fullscreen Mode: Distraction-free editing experience
- Graph View: Interactive node-edge visualization with Sigma.js and optimized 500px height containers
- JSON View: Structured data display with syntax highlighting
- Map View: Geographic data visualization with Leaflet.js
- Schema View: Database structure visualization with type relationships and 450px graph area
- Physics Simulation: Configurable force-directed layouts
- Node Clustering: Automatic grouping of similar nodes
- Search & Filter: Find specific nodes or relationships
- Export Options: Save visualizations as images or data
- Query Results: 500px height containers for clear, usable graph visualization
- Schema Visualization: 600px container with 450px dedicated graph area
- Guide Examples: Consistent 500px height across all interactive examples
- Responsive Design: Maintains usability across different screen sizes
- Fixed Height Containers: Eliminates CSS height inheritance issues
- Sigma.js Optimization: Prevents "Container has no height" errors
- Direct Height Assignment: Components use explicit height values
- Container Validation: Ensures proper dimensions for graph rendering
- Substantial Graph Areas: No more "few pixels high" visualization issues
- Professional Layout: Clean, balanced visualization containers
- Consistent Sizing: Uniform height across all graph modes
- Better Interaction: Larger graphs are easier to navigate and explore
The application includes comprehensive testing with:
- Unit Tests: Individual component testing
- Integration Tests: Component interaction testing
- Visual Regression: UI consistency testing
- Accessibility Tests: WCAG compliance verification
# Run all tests
pnpm run test
# Run tests in watch mode
pnpm run test:watch
# Generate coverage report
pnpm run test:coverage
# Run specific test file
pnpm run test QueryEditor.test.tsx
The application features a comprehensive interactive guides system that provides hands-on learning experiences for DQL and graph database concepts.
-
Introduction to Dgraph Query Language (
01-introduction.mdx
)- Basic DQL syntax and structure
- Setting up schemas and sample data
- Your first interactive queries
-
Filtering Data in DQL (
02-filtering.mdx
)- Predicate-based filtering
- Regular expression patterns
- Genre and type-based queries
-
Graph Traversal in DQL (
03-graph-traversal.mdx
)- Relationship traversal patterns
- Multi-level graph exploration
- Reverse edge navigation
-
Mutations and Data Management (
04-mutations-and-data-management.mdx
)- Schema definition and updates
- Data insertion and updates
- Relationship management
-
E-commerce Dataset Guide (
05-e-commerce-dataset.mdx
)- Complete e-commerce data model
- Product catalogs and customer analytics
- Order management queries
-
Social Network Analysis (
06-social-network-analysis.mdx
)- Social graph modeling
- Influence and engagement analytics
- Network growth analysis
-
Geospatial Data and Location Queries (
07-geospatial-data.mdx
)- Geographic data types
- Location-based queries
- Spatial analysis patterns
-
Advanced Analytics and Aggregations (
08-advanced-analytics.mdx
)- Complex aggregation functions
- Time-based analytics
- Business intelligence patterns
To create a new interactive guide:
-
Create the MDX file in
src/mdx/guides/
with the naming patternXX-guide-name.mdx
:touch src/mdx/guides/09-my-new-guide.mdx
-
Add frontmatter metadata at the top of your file:
--- title: "Your Guide Title" description: "Brief description of what this guide covers" order: 9 ---
-
Write your guide content using standard Markdown syntax with special interactive code blocks:
# Your Guide Title Introduction to your topic... ## Interactive Query Example ```dql-query { your_query(func: has(predicate)) { uid predicate } }
type YourType { field: string @index(term) . }
{ set { _:node <predicate> "value" . _:node <dgraph.type> "YourType" . } }
-
Interactive Code Block Types:
dql-query
: Runnable DQL queries with "Run Query" buttondql-mutation
: Executable mutations with "Run Mutation" buttondql-schema
: Schema definitions with "View Schema" and "Apply Schema" buttons- Regular code blocks: Standard syntax highlighting
-
Guide Structure Best Practices:
- Start with schema definition when introducing new concepts
- Provide sample data through mutations
- Follow with progressive query examples
- Include real-world use cases and scenarios
- Use consistent naming conventions
- Always include
uid
in queries for proper visualization
-
Testing Your Guide:
- Restart the development server:
npm run dev
- Navigate to the Guides tab
- Your new guide will appear in the selection interface
- Test all interactive code blocks work correctly
- Restart the development server:
- Educational Flow: Structure content from basic to advanced
- Interactive Examples: Include clickable code blocks for key concepts
- Real Datasets: Use relatable examples (movies, e-commerce, social networks)
- Visualization Ready: Ensure queries return data suitable for graph visualization
- Error Handling: Provide alternative queries if data might not exist
- Cross-References: Link concepts between different guides
- Dgraph Documentation - Official Dgraph guides
- DQL Reference - Complete DQL syntax
- Schema Design - Schema best practices
- Performance Tuning - Optimization guides
We welcome contributions! Please see our CONTRIBUTING.md file for detailed guidelines on:
- Setting up your development environment
- Understanding the project architecture
- Making code contributions
- Testing and quality standards
- Pull request process
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Dgraph Team - For the excellent database and client libraries
- Chakra UI Team - For the beautiful component library
- Next.js Team - For the amazing React framework
- Open Source Community - For all the amazing tools and libraries
Happy querying! 🚀
For questions, issues, or contributions, please visit our GitHub repository.