GigaBrain Examples#
This directory contains practical examples of using GigaBrain for various use cases.
Example Categories#
CLI Examples#
- Interactive REPL usage
- Command-line operations
- Batch processing
- Administrative commands
- Data import/export
Basic Operations#
- Creating nodes and relationships
- Basic queries
- Property management
- Graph traversal
Social Network#
- User profiles and friendships
- Friend recommendations
- Community detection
- Influence analysis
Fraud Detection#
- Transaction networks
- Anomaly detection
- Risk scoring
- Pattern recognition
Knowledge Graph#
- Entity relationships
- Semantic queries
- Recommendation systems
- Data lineage
Supply Chain#
- Product dependencies
- Route optimization
- Supplier networks
- Impact analysis
Performance Testing#
- Load testing scripts
- Benchmark scenarios
- Performance optimization
- Monitoring examples
Running Examples#
Each example includes:
- Setup instructions: Required data and configuration
- Code samples: REST API calls and gRPC examples
- Expected output: Sample responses and results
- Variations: Alternative approaches and extensions
Prerequisites#
-
Running GigaBrain server:
cargo run --bin gigabrain -
CLI tool (for CLI examples):
cargo build --release --bin gigabrain-cli -
Required tools:
# For CLI examples ./target/release/gigabrain-cli # For REST API examples curl # For gRPC examples grpcurl # For data generation python3 (optional) -
Authentication (if enabled):
export GIGABRAIN_TOKEN="your-jwt-token"
Quick Start#
-
CLI interactive mode:
./target/release/gigabrain-cli gigabrain> CREATE (alice:Person {name: 'Alice', age: 30}) gigabrain> MATCH (n:Person) RETURN n.name, n.age -
Basic node creation:
cd examples/basic-operations ./01-create-nodes.sh -
Load sample social network:
cd examples/social-network ./setup-network.sh -
Run performance tests:
cd examples/performance-testing ./benchmark-suite.sh
Example Structure#
Each example follows this structure:
example-name/
├── README.md # Detailed explanation
├── setup.sh # Data setup script
├── queries/ # Sample queries
│ ├── basic.cypher
│ └── advanced.cypher
├── rest-api/ # REST API examples
│ ├── create-data.sh
│ └── run-queries.sh
├── grpc-client/ # gRPC examples
│ ├── client.py
│ └── client.go
└── data/ # Sample datasets
└── sample.json
Integration Examples#
Python Client#
import requests
import json
class GigaBrainClient:
def __init__(self, base_url="http://localhost:3000/api/v1", token=None):
self.base_url = base_url
self.headers = {"Content-Type": "application/json"}
if token:
self.headers["Authorization"] = f"Bearer {token}"
def create_node(self, labels, properties):
response = requests.post(
f"{self.base_url}/nodes",
headers=self.headers,
json={"labels": labels, "properties": properties}
)
return response.json()
def execute_cypher(self, query, parameters=None):
response = requests.post(
f"{self.base_url}/cypher",
headers=self.headers,
json={"query": query, "parameters": parameters or {}}
)
return response.json()
# Usage
client = GigaBrainClient()
node = client.create_node(["Person"], [
{"key": "name", "value": {"string_value": "Alice"}}
])
print(f"Created node: {node}")
Go Client#
package main
import (
"context"
"log"
"google.golang.org/grpc"
pb "your-org/gigabrain/proto"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()
client := pb.NewGigaBrainServiceClient(conn)
// Create a node
node, err := client.CreateNode(context.Background(), &pb.CreateNodeRequest{
Labels: []string{"Person"},
Properties: []*pb.Property{
{
Key: "name",
Value: &pb.PropertyValue{
Value: &pb.PropertyValue_StringValue{
StringValue: "Alice",
},
},
},
},
})
if err != nil {
log.Fatalf("CreateNode failed: %v", err)
}
log.Printf("Created node with ID: %d", node.NodeId.Id)
}
JavaScript/Node.js Client#
const axios = require('axios');
class GigaBrainClient {
constructor(baseURL = 'http://localhost:3000/api/v1', token = null) {
this.client = axios.create({
baseURL,
headers: {
'Content-Type': 'application/json',
...(token && { 'Authorization': `Bearer ${token}` })
}
});
}
async createNode(labels, properties) {
const response = await this.client.post('/nodes', {
labels,
properties
});
return response.data;
}
async executeCypher(query, parameters = {}) {
const response = await this.client.post('/cypher', {
query,
parameters
});
return response.data;
}
}
// Usage
const client = new GigaBrainClient();
client.createNode(['Person'], [
{ key: 'name', value: { string_value: 'Alice' } }
]).then(node => {
console.log('Created node:', node);
});
Common Patterns#
Data Import#
# Bulk import from JSON
curl -X POST http://localhost:3000/api/v1/bulk/import \
-H "Content-Type: application/json" \
-d @large-dataset.json
# Import with transactions
curl -X POST http://localhost:3000/api/v1/transactions/begin
# ... multiple operations ...
curl -X POST http://localhost:3000/api/v1/transactions/commit
Query Optimization#
// Use indexes for faster lookups
CREATE INDEX ON :Person(email);
// Efficient pattern matching
MATCH (p:Person {email: $email})-[:FRIENDS]->(friend)
RETURN friend.name
LIMIT 10;
// Avoid cartesian products
MATCH (p:Person)-[:FRIENDS]->(f:Person)
WHERE p.age > 25 AND f.age > 25
RETURN COUNT(*)
Error Handling#
try:
result = client.execute_cypher("MATCH (n) RETURN n LIMIT 10")
if result.get('error'):
print(f"Query error: {result['error']}")
else:
print(f"Found {len(result['results'])} results")
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
Performance Tips#
- Batch Operations: Group multiple operations in transactions
- Use Indexes: Create indexes on frequently queried properties
- Limit Results: Always use LIMIT in development queries
- Property Types: Use appropriate property types for your data
- Query Planning: Analyze query execution plans for optimization
Troubleshooting#
Common Issues#
-
Connection Refused:
- Ensure GigaBrain server is running
- Check port configuration (3000 for REST, 50051 for gRPC)
-
Authentication Errors:
- Verify JWT token is valid and not expired
- Check token permissions for the operation
-
Query Timeouts:
- Reduce query complexity
- Add appropriate LIMIT clauses
- Consider breaking large queries into smaller parts
-
Memory Issues:
- Monitor memory usage during large imports
- Use streaming for large result sets
- Configure appropriate JVM heap size
Debug Mode#
Enable debug logging for troubleshooting:
RUST_LOG=debug cargo run --bin gigabrain
Contributing Examples#
To contribute new examples:
- Create a new directory under
examples/ - Follow the standard structure outlined above
- Include comprehensive documentation
- Test all code samples
- Submit a pull request
Guidelines#
- Clear documentation: Explain the use case and approach
- Working code: All examples must run successfully
- Error handling: Include proper error handling
- Performance notes: Mention any performance considerations
- Extensions: Suggest ways to extend or modify the example