# Basic Operations Examples This guide covers fundamental operations in GigaBrain: creating nodes, relationships, and running basic queries. ## Table of Contents - [Setup](#setup) - [Node Operations](#node-operations) - [Relationship Operations](#relationship-operations) - [Basic Queries](#basic-queries) - [Property Management](#property-management) - [Error Handling](#error-handling) ## Setup Ensure GigaBrain server is running: ```bash cargo run --bin gigabrain ``` The server will start with: - REST API on port 3000 - gRPC API on port 50051 ## Node Operations ### Creating Nodes #### Simple Node Creation ```bash # Create a person node curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -d '{ "labels": ["Person"], "properties": [ { "key": "name", "value": {"string_value": "Alice Johnson"} }, { "key": "age", "value": {"int_value": 28} }, { "key": "email", "value": {"string_value": "alice@example.com"} } ] }' ``` **Expected Response:** ```json { "node_id": { "id": 1 } } ``` #### Node with Multiple Labels ```bash # Create a person who is also an employee curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -d '{ "labels": ["Person", "Employee"], "properties": [ { "key": "name", "value": {"string_value": "Bob Smith"} }, { "key": "employee_id", "value": {"string_value": "EMP001"} }, { "key": "salary", "value": {"float_value": 75000.0} }, { "key": "active", "value": {"bool_value": true} } ] }' ``` ### Retrieving Nodes ```bash # Get node by ID curl http://localhost:3000/api/v1/nodes/1 ``` **Expected Response:** ```json { "node": { "id": {"id": 1}, "labels": ["Person"], "properties": [ { "key": "name", "value": {"string_value": "Alice Johnson"} }, { "key": "age", "value": {"int_value": 28} }, { "key": "email", "value": {"string_value": "alice@example.com"} } ] } } ``` ### Updating Nodes ```bash # Update node properties curl -X PUT http://localhost:3000/api/v1/nodes/1 \ -H "Content-Type: application/json" \ -d '{ "node_id": {"id": 1}, "labels": ["Person", "Customer"], "properties": [ { "key": "name", "value": {"string_value": "Alice Johnson-Smith"} }, { "key": "age", "value": {"int_value": 29} }, { "key": "status", "value": {"string_value": "premium"} } ] }' ``` ### Deleting Nodes ```bash # Delete a node curl -X DELETE http://localhost:3000/api/v1/nodes/1 ``` **Expected Response:** ```json { "success": true } ``` ## Relationship Operations ### Creating Relationships #### Basic Relationship ```bash # Create friendship relationship curl -X POST http://localhost:3000/api/v1/relationships \ -H "Content-Type: application/json" \ -d '{ "start_node": {"id": 1}, "end_node": {"id": 2}, "rel_type": "FRIENDS", "properties": [ { "key": "since", "value": {"string_value": "2023-01-15"} }, { "key": "closeness", "value": {"float_value": 0.8} } ] }' ``` #### Work Relationship ```bash # Create employment relationship curl -X POST http://localhost:3000/api/v1/relationships \ -H "Content-Type: application/json" \ -d '{ "start_node": {"id": 2}, "end_node": {"id": 3}, "rel_type": "WORKS_FOR", "properties": [ { "key": "position", "value": {"string_value": "Software Engineer"} }, { "key": "start_date", "value": {"string_value": "2022-03-01"} }, { "key": "remote", "value": {"bool_value": true} } ] }' ``` ### Retrieving Relationships ```bash # Get relationship by ID curl http://localhost:3000/api/v1/relationships/1 ``` **Expected Response:** ```json { "relationship": { "id": {"id": 1}, "start_node": {"id": 1}, "end_node": {"id": 2}, "rel_type": "FRIENDS", "properties": [ { "key": "since", "value": {"string_value": "2023-01-15"} }, { "key": "closeness", "value": {"float_value": 0.8} } ] } } ``` ### Deleting Relationships ```bash # Delete a relationship curl -X DELETE http://localhost:3000/api/v1/relationships/1 ``` ## Basic Queries ### Simple Queries #### Find All Nodes ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (n) RETURN n LIMIT 10" }' ``` #### Find Nodes by Label ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age DESC" }' ``` #### Find Relationships ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (a)-[r:FRIENDS]->(b) RETURN a.name, r.since, b.name" }' ``` ### Parameterized Queries ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person) WHERE p.age > $min_age RETURN p.name, p.age", "parameters": { "min_age": 25 } }' ``` ### Complex Queries #### Find Friends of Friends ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person {name: $name})-[:FRIENDS]-(friend)-[:FRIENDS]-(fof) WHERE fof <> p RETURN DISTINCT fof.name", "parameters": { "name": "Alice Johnson" } }' ``` #### Find Colleagues ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person)-[:WORKS_FOR]->(company)<-[:WORKS_FOR]-(colleague) WHERE p.name = $name AND colleague <> p RETURN colleague.name, colleague.employee_id", "parameters": { "name": "Bob Smith" } }' ``` ## Property Management ### Property Types GigaBrain supports various property types: ```bash # String properties { "key": "name", "value": {"string_value": "John Doe"} } # Integer properties { "key": "age", "value": {"int_value": 30} } # Float properties { "key": "score", "value": {"float_value": 85.5} } # Boolean properties { "key": "active", "value": {"bool_value": true} } # Binary data { "key": "avatar", "value": {"bytes_value": "base64-encoded-data"} } ``` ### Property Queries #### Filter by Property Value ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person) WHERE p.age >= 25 AND p.age <= 35 RETURN p.name, p.age" }' ``` #### Property Existence ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person) WHERE EXISTS(p.email) RETURN p.name, p.email" }' ``` #### String Operations ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person) WHERE p.name CONTAINS $substring RETURN p.name", "parameters": { "substring": "John" } }' ``` ### Updating Properties #### Add New Property ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person {name: $name}) SET p.last_login = $timestamp RETURN p", "parameters": { "name": "Alice Johnson", "timestamp": "2024-01-15T10:30:00Z" } }' ``` #### Remove Property ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (p:Person {name: $name}) REMOVE p.temporary_field RETURN p", "parameters": { "name": "Alice Johnson" } }' ``` ## Error Handling ### Common Error Scenarios #### Node Not Found ```bash curl http://localhost:3000/api/v1/nodes/999999 ``` **Response (404):** ```json { "error": { "code": "NOT_FOUND", "message": "Node not found", "details": {} } } ``` #### Invalid Property Type ```bash curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -d '{ "labels": ["Person"], "properties": [ { "key": "age", "value": {"string_value": "not a number"} } ] }' ``` #### Syntax Error in Cypher ```bash curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -d '{ "query": "MATCH (n) RETURN invalid_syntax" }' ``` **Response:** ```json { "results": [], "error": "Parse error: unexpected token 'invalid_syntax'", "execution_time_ms": 0 } ``` ### Error Handling Best Practices 1. **Check HTTP Status Codes**: Always verify the response status 2. **Parse Error Messages**: Extract meaningful error information 3. **Retry Logic**: Implement appropriate retry strategies 4. **Validation**: Validate input data before sending requests 5. **Logging**: Log errors for debugging and monitoring ### Example Error Handling (Python) ```python import requests import json def safe_create_node(labels, properties): try: response = requests.post( "http://localhost:3000/api/v1/nodes", headers={"Content-Type": "application/json"}, json={"labels": labels, "properties": properties}, timeout=10 ) if response.status_code == 200: return response.json() elif response.status_code == 400: error = response.json().get('error', {}) print(f"Validation error: {error.get('message', 'Unknown error')}") return None elif response.status_code == 500: print("Server error occurred") return None else: print(f"Unexpected status code: {response.status_code}") return None except requests.exceptions.Timeout: print("Request timed out") return None except requests.exceptions.ConnectionError: print("Could not connect to server") return None except json.JSONDecodeError: print("Invalid JSON response") return None # Usage result = safe_create_node( ["Person"], [{"key": "name", "value": {"string_value": "Test User"}}] ) if result: print(f"Created node: {result}") else: print("Failed to create node") ``` ## Performance Tips 1. **Use Indexes**: Create indexes on frequently queried properties 2. **Limit Results**: Always use LIMIT in development and test queries 3. **Batch Operations**: Group multiple operations when possible 4. **Property Selection**: Only return properties you need 5. **Query Planning**: Analyze query execution plans for optimization ## Next Steps - Explore [Social Network Examples](./social-network.md) - Learn about [Graph Algorithms](../API.md#graph-algorithms) - Check out [Performance Testing](./performance-testing.md) - Review [gRPC Examples](./grpc-examples.md)