Query Structure
Query Structure
Section titled “Query Structure”OstrichDB CLI uses an intuitive query structure based on CLPs (Command, Location, Parameter) tokens and dot notation syntax. This system provides clear, readable queries that follow the hierarchical data organization.
CLP Token System
Section titled “CLP Token System”Overview
Section titled “Overview”Every OstrichDB query is built using three types of tokens:
- (C)ommand Token: Specifies the operation to perform
- (L)ocation Token: Defines the path using dot notation
- (P)arameter Token: Additional modifiers for the operation
Note: Not all queries require all three token types.
Token Breakdown
Section titled “Token Breakdown”NEW foo.bar.baz OF_TYPE []STRING WITH value1,value2,value3│ │ │ │ ││ │ │ │ └─ Parameter value│ │ │ └─ Parameter token│ │ └─ Parameter token│ └─ Location token (dot notation path)└─ Command tokenDot Notation Syntax
Section titled “Dot Notation Syntax”Hierarchical Path Structure
Section titled “Hierarchical Path Structure”OstrichDB uses dot notation to represent the data hierarchy:
collection.cluster.record│ │ ││ │ └─ Record name (third level)│ └─ Cluster name (second level)└─ Collection name (first level)Path Examples
Section titled “Path Examples”# Simple three-level pathusers.active.john_doe│ │ ││ │ └─ Record: john_doe│ └─ Cluster: active└─ Collection: users
# Complex business structurecompany.departments.engineering.team_lead│ │ │ ││ │ │ └─ Record: team_lead│ │ └─ Cluster: engineering│ └─ Cluster: departments└─ Collection: companyPath Resolution Rules
Section titled “Path Resolution Rules”- First Level: Always refers to a collection
- Second Level: Always refers to a cluster within the collection
- Third Level: Always refers to a record within the cluster
- Auto-Creation: Missing collections and clusters are created automatically
- Case Sensitive:
Usersandusersare different paths
Command Tokens
Section titled “Command Tokens”Single-Token Commands
Section titled “Single-Token Commands”Commands that work independently without additional arguments:
# System commandsVERSION # Show OstrichDB versionHELP # Display help informationCLEAR # Clear the terminal screenEXIT # Exit OstrichDB CLIRESTART # Restart the programLOGOUT # Log out current user
# Data explorationTREE # Show entire data structureHISTORY # Show command history
# Server operationsSERVE # Start HTTP serverAGENT # Start natural language processor
# MaintenanceBENCHMARK # Run performance testsDESTROY # Completely destroy all data (use with caution)Multi-Token Commands
Section titled “Multi-Token Commands”Commands that require additional tokens to complete the operation:
# Data manipulationNEW # Create collections, clusters, records, or usersFETCH # Retrieve data from any levelERASE # Delete collections, clusters, or recordsRENAME # Rename existing objectsSET # Assign values to records or configurations
# Data analysisCOUNT # Count objects (COLLECTIONS, CLUSTERS, RECORDS)SIZE_OF # Get size in bytes of objectsTYPE_OF # Get the data type of a recordWHERE # Search for records or clusters
# Data managementBACKUP # Create collection backupsPURGE # Remove data while keeping structureVALIDATE # Check collection integrityISOLATE # Quarantine collectionsLOCK # Set collection access modesUNLOCK # Remove collection restrictions
# SecurityENC # Encrypt collectionsDEC # Decrypt collections
# Import/ExportIMPORT # Import CSV or JSON filesParameter Tokens
Section titled “Parameter Tokens”Modifier Tokens
Section titled “Modifier Tokens”Parameters that modify command behavior:
OF_TYPE # Specify data type for recordsWITH # Assign value during creationTO # Target for rename/assignment operationsUsage Examples
Section titled “Usage Examples”# OF_TYPE: Specify data typeNEW users.staff.employee_name OF_TYPE STRING
# WITH: Assign value during creationNEW products.electronics.laptop OF_TYPE INTEGER WITH 25
# TO: Rename or reassignRENAME old_collection TO new_collectionSET CONFIG AUTO_SERVE TO true
# Combined parametersNEW inventory.books.count OF_TYPE INTEGER WITH 150Query Construction Patterns
Section titled “Query Construction Patterns”Basic Patterns
Section titled “Basic Patterns”Create and Assign
Section titled “Create and Assign”# Pattern: NEW location OF_TYPE type WITH valueNEW blog.posts.title OF_TYPE STRING WITH "My First Post"NEW inventory.products.stock OF_TYPE INTEGER WITH 100NEW settings.features.enabled OF_TYPE BOOLEAN WITH trueFetch Data
Section titled “Fetch Data”# Pattern: FETCH locationFETCH blog.posts.titleFETCH inventory.productsFETCH settingsRename Objects
Section titled “Rename Objects”# Pattern: RENAME old_location TO new_locationRENAME blog.posts TO blog.articlesRENAME inventory.products.old_item TO inventory.products.new_itemCount Objects
Section titled “Count Objects”# Pattern: COUNT object_type [IN location]COUNT COLLECTIONSCOUNT CLUSTERS IN inventoryCOUNT RECORDS IN blog.postsAdvanced Patterns
Section titled “Advanced Patterns”Conditional Operations
Section titled “Conditional Operations”# Search and modifyWHERE laptopRENAME products.electronics.laptop TO products.electronics.notebook
# Validate and backupVALIDATE important_dataBACKUP important_dataBulk Operations with Chaining
Section titled “Bulk Operations with Chaining”# Create multiple related recordsNEW users.staff.alice OF_TYPE STRING WITH "Alice Johnson" && NEW users.staff.alice_role OF_TYPE STRING WITH "Developer" && NEW users.staff.alice_salary OF_TYPE FLOAT WITH 75000.50Location Token Deep Dive
Section titled “Location Token Deep Dive”Collection Names
Section titled “Collection Names”Collections are the top-level containers:
# Good collection namesusers # Simple, descriptiveblog_posts # Underscore separationcompany_data # Clear purposeinventory_2024 # Version/date inclusion
# Avoiddata # Too genericstuff # Not descriptivecollection1 # Not meaningfulCluster Names
Section titled “Cluster Names”Clusters organize records within collections:
# Logical cluster organizationusers.active # Status-basedusers.inactiveusers.administrators
products.electronics # Category-basedproducts.booksproducts.clothing
blog.published_posts # State-basedblog.draft_postsblog.archived_postsRecord Names
Section titled “Record Names”Records store the actual data:
# Descriptive record namesusers.staff.john_doe_email # Person + attributeproducts.laptops.dell_xps_price # Category + model + attributeblog.posts.welcome_post_title # Context + identifier + attribute
# Use consistent naming patternsusers.staff.alice_nameusers.staff.alice_emailusers.staff.alice_departmentQuery Chaining
Section titled “Query Chaining”Chain Operator
Section titled “Chain Operator”Use && to execute multiple queries in sequence:
# Basic chainingNEW users.staff.bob OF_TYPE STRING WITH "Bob Smith" && FETCH users.staff.bob
# Complex chainingNEW company.engineering.team_size OF_TYPE INTEGER WITH 5 && NEW company.engineering.budget OF_TYPE FLOAT WITH 500000.00 && COUNT RECORDS IN company.engineering && TREEChaining Best Practices
Section titled “Chaining Best Practices”Related Operations
Section titled “Related Operations”# Good: Group related operationsNEW project.webapp.name OF_TYPE STRING WITH "Company Website" && NEW project.webapp.status OF_TYPE STRING WITH "In Progress" && NEW project.webapp.deadline OF_TYPE DATE WITH 2024-06-15
# Less efficient: Separate unrelated operationsNEW project.webapp.name OF_TYPE STRING WITH "Company Website" && COUNT COLLECTIONS && HELP NEWError Handling in Chains
Section titled “Error Handling in Chains”# If any operation in a chain fails, subsequent operations are skippedNEW invalid.path.record OF_TYPE INVALID_TYPE WITH value && FETCH valid.path.record# The FETCH won't execute if NEW failsQuery Examples by Use Case
Section titled “Query Examples by Use Case”User Management
Section titled “User Management”# Create user structureNEW users.active.john_smith OF_TYPE STRING WITH "John Smith"NEW users.active.john_email OF_TYPE STRING WITH "john@company.com"NEW users.active.john_role OF_TYPE STRING WITH "developer"NEW users.active.john_hire_date OF_TYPE DATE WITH 2024-01-15
# Fetch user informationFETCH users.active.john_smithFETCH users.active
# Manage user statusRENAME users.active.john_smith TO users.inactive.john_smithInventory Tracking
Section titled “Inventory Tracking”# Stock managementNEW inventory.electronics.laptops OF_TYPE INTEGER WITH 25NEW inventory.electronics.phones OF_TYPE INTEGER WITH 50NEW inventory.books.programming OF_TYPE INTEGER WITH 100
# Check inventory levelsFETCH inventory.electronicsCOUNT RECORDS IN inventory.electronicsSIZE_OF inventoryProject Management
Section titled “Project Management”# Project setupNEW projects.website.status OF_TYPE STRING WITH "Planning"NEW projects.website.team_members OF_TYPE []STRING WITH "Alice,Bob,Carol"NEW projects.website.deadline OF_TYPE DATE WITH 2024-08-01NEW projects.website.budget OF_TYPE FLOAT WITH 75000.00
# Project trackingFETCH projects.website.statusCOUNT RECORDS IN projects.websiteWHERE deadlineContent Management
Section titled “Content Management”# Blog post creationNEW blog.posts.welcome_title OF_TYPE STRING WITH "Welcome to Our Blog"NEW blog.posts.welcome_content OF_TYPE STRING WITH "This is our first blog post..."NEW blog.posts.welcome_author OF_TYPE STRING WITH "Jane Doe"NEW blog.posts.welcome_published OF_TYPE DATETIME WITH 2024-01-15T10:00:00
# Content organizationCOUNT RECORDS IN blog.postsBACKUP blogTREEError Prevention
Section titled “Error Prevention”Common Query Mistakes
Section titled “Common Query Mistakes”Invalid Paths
Section titled “Invalid Paths”# Wrong: Missing cluster levelNEW users.john_doe OF_TYPE STRING WITH "John"# Correct: Include all three levelsNEW users.staff.john_doe OF_TYPE STRING WITH "John"Type Mismatches
Section titled “Type Mismatches”# Wrong: Invalid typeNEW products.count OF_TYPE INVALID_TYPE WITH 50# Correct: Use valid typeNEW products.electronics.count OF_TYPE INTEGER WITH 50Parameter Order
Section titled “Parameter Order”# Wrong: Parameters in wrong orderNEW users.staff.alice WITH "Alice" OF_TYPE STRING# Correct: Proper parameter orderNEW users.staff.alice OF_TYPE STRING WITH "Alice"Validation Queries
Section titled “Validation Queries”# Check before operationsTYPE_OF users.staff.employee_count # Verify data typeSIZE_OF large_collection # Check collection sizeVALIDATE collection_name # Verify integrityQuery Optimization
Section titled “Query Optimization”Efficient Querying
Section titled “Efficient Querying”# Efficient: Specific pathsFETCH users.staff.specific_record
# Less efficient: Broad fetches followed by filteringFETCH users# Then manually looking for specific dataBatch Operations
Section titled “Batch Operations”# Use chaining for related operationsNEW company.dept.engineering OF_TYPE STRING WITH "Engineering Department" && NEW company.dept.engineering_head OF_TYPE STRING WITH "Alice Johnson" && NEW company.dept.engineering_size OF_TYPE INTEGER WITH 15
# Instead of separate queriesNEW company.dept.engineering OF_TYPE STRING WITH "Engineering Department"NEW company.dept.engineering_head OF_TYPE STRING WITH "Alice Johnson"NEW company.dept.engineering_size OF_TYPE INTEGER WITH 15Best Practices
Section titled “Best Practices”Naming Conventions
Section titled “Naming Conventions”- Use descriptive names:
user_emailinstead ofemail - Be consistent: If you use underscores, use them everywhere
- Include context:
blog_post_titleinstead of justtitle - Use logical grouping: Group related records in the same cluster
Query Organization
Section titled “Query Organization”- Plan your hierarchy: Design your collection/cluster structure before creating data
- Use appropriate levels: Don’t create unnecessary nesting
- Group related operations: Use query chaining for related tasks
- Validate early: Check data types and structure before complex operations
Performance Tips
Section titled “Performance Tips”- Use specific paths: Avoid broad FETCH operations when possible
- Chain related queries: Reduce the number of separate operations
- Regular maintenance: Use VALIDATE and SIZE_OF to monitor collections
- Clean up: Use ERASE to remove unused data structures
Next Steps
Section titled “Next Steps”Now that you understand query structure:
- Explore Commands Reference - Learn all available commands in detail
- Master Data Types - Understand type system and validation
- Configure Your Setup - Customize OstrichDB behavior
- Practice: Use the patterns and examples to build your own queries
The CLP system and dot notation make OstrichDB queries both powerful and readable. Master these concepts to efficiently manage your hierarchical data.