# Query Language Reference
Complete reference for hawk's query syntax and operations.
## 📖 Table of Contents
- [Query Structure](#query-structure)
- [Field Access](#field-access)
- [Array Slicing](#array-slicing)
- [Pipeline Operations](#pipeline-operations)
- [Filtering](#filtering)
- [Logical Operations](#logical-operations)
- [Data Transformation](#data-transformation)
- [String Operations](#string-operations)
- [Statistical Operations](#statistical-operations)
- [Aggregation Functions](#aggregation-functions)
- [Grouping Operations](#grouping-operations)
- [Output Control](#output-control)
- [Advanced Patterns](#advanced-patterns)
- [Error Handling](#error-handling)
## Query Structure
### Basic Syntax
```
hawk '<query>' [file]
hawk '<query>' [options] [file]
```
### Pipeline Structure
```
<base_query> | <operation1> | <operation2> | ...
```
**Examples:**
```bash
# Simple field access
hawk '.users[0].name' data.json
# Pipeline with operations
# Complex pipeline
## Field Access
### Object Fields
```bash
# Access top-level field
.field_name
# Access nested field
.parent.child.grandchild
```
**Examples:**
```bash
# Simple access
hawk '.name' user.json
# Nested access
hawk '.user.profile.email' data.json
```
### Array Access
#### Index Access
```bash
# Access specific element
.array[0] # First element
.array[1] # Second element
.array[-1] # Last element (NEW!)
.array[-2] # Second to last element (NEW!)
```
#### Array Iteration
```bash
# Access all elements
.array[]
# Access field from all elements
.array[].field_name
# Nested array access
.array[].nested_array[]
```
**Examples:**
```bash
# Get first user
hawk '.users[0]' data.json
# Get last user
hawk '.users[-1]' data.json
# Get all user names
hawk '.users[].name' data.json
# Get all project names from all users
hawk '.users[].projects[].name' data.json
```
### Root Access
```bash
# Access entire document
.
# Process each top-level element (for arrays)
.[]
```
## Array Slicing
### Basic Slicing Syntax
```bash
# Slice notation
.[start:end] # Elements from start to end (exclusive)
.[start:] # Elements from start to end
.[:end] # Elements from beginning to end
.[:] # All elements (copy)
```
### Negative Index Support
```bash
# Negative indices
.[-5:] # Last 5 elements
.[:-3] # All except last 3 elements
.[-10:-5] # Elements from 10th-last to 5th-last
```
### Field-specific Slicing
```bash
# Slice specific arrays
.users[0:5] # First 5 users
.logs[-100:] # Last 100 log entries
.data[10:20] # Elements 10-19
```
### Slicing with String Operations
```bash
# Split and slice results (NEW!)
.csv_line | split(",")[2:5] # Get columns 2-4
```
**Examples:**
```bash
# Basic slicing
hawk '.users[0:5]' users.json # First 5 users
hawk '.logs[-50:]' logs.json # Last 50 log entries
hawk '.data[10:20]' data.json # Middle section
# Combined with operations
# String split slicing
hawk '.urls[] | split("://")[1] | split("/")[0]' urls.json # Get domain
# Advanced slicing patterns
```
## Pipeline Operations
### Pipeline Syntax
Operations are chained with the pipe operator `|`:
```bash
### Operation Categories
1. **Filtering**: `select()`, text filters, logical operations
2. **Transformation**: `map()`, string operations
3. **Aggregation**: `count`, `sum()`, `avg()`, etc.
4. **Grouping**: `group_by()`
5. **Statistical**: `unique`, `sort`, `median`, `stddev`
## Filtering
### Basic Filtering with select()
```bash
# Numeric comparisons
select(.field > value)
select(.field < value)
select(.field == value)
select(.field != value)
select(.field >= value)
select(.field <= value)
# String comparisons
select(.field == "string")
select(.field != "string")
# Boolean comparisons
select(.field == true)
select(.field == false)
```
### Nested Field Filtering
```bash
# Filter by nested field
select(.parent.child > value)
select(.user.profile.age >= 18)
select(.config.database.enabled == true)
```
### String-based Filtering
```bash
# Text contains pattern
# Text starts/ends with pattern
# Case-insensitive filtering
**Examples:**
```bash
# Find users over 30
# Find active users
# Find users in Engineering
# Find log entries containing "ERROR"
# Find files ending with .log
## Logical Operations
### NOT Operator
```bash
# NOT operator syntax (requires parentheses)
select(not (.condition))
# Examples
select(not (.age > 30)) # Users 30 or younger
select(not (.status == "active")) # Inactive users
### OR Operator (Pattern-based)
```bash
# OR using pipe-delimited patterns within contains()
# Multiple pattern matching
select(.level | contains("ERROR|FATAL|CRITICAL"))
```
### Complex Logical Combinations
```bash
# NOT with string operations
# OR with pattern matching
```
**Examples:**
```bash
# NOT operator examples
hawk -t '. | select(not (. | contains("#")))' config.txt # Non-comment lines
# OR operator examples
hawk '.files[] | select(.ext | contains("jpg|png|gif"))' files.json
# Combined logical operations
# Complex conditions with slicing
```
## Data Transformation
### map() Function
#### Single Field Transformation
```bash
# Transform single field
# Examples
map(.content | length) # Get content length
```
#### Multiple Field Transformation
```bash
# Transform multiple fields with same operation
# Examples
map(.title, .description | length) # Get length of both fields
```
#### Root Element Transformation
```bash
# Transform entire element
# Examples for text processing
map(. | upper) # Convert each line to uppercase
```
**Examples:**
```bash
# Convert all names to uppercase
# Get email domains
# Process multiple fields
# Text processing with slicing
```
### Field Selection
```bash
# Select specific fields
select_fields(field1,field2,field3)
# Examples
select_fields(name,age) # Keep only name and age
select_fields(id,title,description) # Keep only specified fields
```
## String Operations
### Case Conversion
```bash
upper # Convert to uppercase
lower # Convert to lowercase
```
### Whitespace Management
```bash
trim # Remove leading and trailing whitespace
trim_start # Remove leading whitespace only
trim_end # Remove trailing whitespace only
```
### String Analysis
```bash
length # Get string length
reverse # Reverse string
```
### Pattern Matching
```bash
contains("pattern") # Check if string contains pattern
starts_with("prefix") # Check if string starts with prefix
ends_with("suffix") # Check if string ends with suffix
```
### Text Transformation
```bash
replace("old", "new") # Replace text
substring(start, length) # Extract substring
substring(start) # Extract from start to end
```
### String Splitting and Joining
```bash
split("delimiter") # Split string into array
split("delimiter")[index] # Split and access specific element
split("delimiter")[start:end] # Split and slice result (NEW!)
join("delimiter") # Join array elements into string
```
**Examples:**
```bash
# Basic string operations
"Hello World" | length # → 11
# Pattern matching
# Text transformation
# Splitting with slicing (NEW!)
"path/to/my/file.txt" | split("/")[-1] # → "file.txt"
"one,two,three,four,five" | split(",")[::2] # → ["one", "three", "five"] (future)
```
## Statistical Operations
### Basic Statistics
```bash
unique # Remove duplicates
sort # Sort values
length # Get array length
```
### Advanced Statistics
```bash
median # Calculate median
median(.field) # Calculate median of field
stddev # Calculate standard deviation
stddev(.field) # Calculate standard deviation of field
```
**Examples:**
```bash
# Get unique values
# Sort values
# Calculate statistics
# Combined with slicing
```
## Aggregation Functions
### Counting
```bash
count # Count elements
```
### Numeric Aggregation
```bash
sum(.field) # Sum numeric values
avg(.field) # Calculate average
min(.field) # Find minimum value
max(.field) # Find maximum value
```
### Field-specific Aggregation
```bash
# Apply to specific field
sum(.price)
avg(.score)
min(.temperature)
max(.response_time)
```
**Examples:**
```bash
# Count users
# Calculate totals
# Find averages
# Find extremes
# With slicing
```
## Grouping Operations
### Basic Grouping
```bash
group_by(.field) # Group by field value
```
### Grouping with Aggregation
```bash
group_by(.field) | count # Count items in each group
group_by(.field) | sum(.numeric_field) # Sum by group
group_by(.field) | avg(.numeric_field) # Average by group
group_by(.field) | min(.numeric_field) # Minimum by group
group_by(.field) | max(.numeric_field) # Maximum by group
```
**Examples:**
```bash
# Group users by department
# Count by department
# Average salary by department
# Sales sum by region
# Group with logical filtering
## Output Control
### Format Options
```bash
--format auto # Smart format detection (default)
--format table # Force table output
--format json # Force JSON output
--format list # Force list output
```
### Text Processing Mode
```bash
--text, -t # Force text interpretation
```
**Examples:**
```bash
# Force specific output format
hawk '.users[]' --format table users.json
hawk '.users[].name' --format list users.json
# Process as text
## Advanced Patterns
### Complex Filtering with Logic
```bash
# Multiple NOT conditions
select(not (.age > 65)) and select(not (.status == "inactive"))
# OR with NOT combinations
# Complex string filtering with OR patterns
### Multi-step Transformations with Slicing
```bash
# Filter, slice, then transform
# Transform, slice, then analyze
# Slice grouped data
### Text Processing Workflows with Advanced Operations
```bash
# Complex log analysis
# CSV processing with pattern matching
# Configuration analysis with OR patterns
### Combining All Features
```bash
# Complex data pipeline
.events[-1000:] |
group_by(.) |
count
# Advanced text processing with OR patterns
.logs[] |
select(. | length > 10) |
unique[0:20]
# Multi-field analysis with pattern matching
.users[0:500] |
group_by(.) |
count
```
## Error Handling
### Common Error Patterns
#### Field Not Found
```bash
# ❌ Error: field doesn't exist
.users[].nonexistent_field
# ✅ Solution: filter first
#### Index Out of Bounds
```bash
# ❌ Error: array index doesn't exist
.users[999].name
# ✅ Solution: use slicing safely
#### Slice Range Issues
```bash
# ❌ Error: invalid slice range
.array[10:5] # End before start
# ✅ Solution: check bounds
```
#### Logical Operation Errors
```bash
# ❌ Error: missing parentheses in NOT
select(not .field == "value")
# ✅ Solution: use proper syntax
select(not (.field == "value"))
```
### Debugging Techniques
#### Data Structure Exploration
```bash
# Understand data structure
# Check array lengths with slicing
.array_field | length
.array_field[0:5] # Sample first 5 elements
# Examine specific ranges
.array_field[-10:] # Last 10 elements
```
#### Step-by-step Building
```bash
# Build query incrementally
.users[] # Step 1: get all users
.users[] | select(.age > 30) | .[0:10] | count # Step 4: add aggregation
```
## Query Examples by Use Case
### Data Exploration
```bash
# Quick overview
# Sample data with slicing
.[0:5] # First 5 records
.[-3:] # Last 3 records
# Unique values
### API Response Analysis
```bash
# Extract specific data with limits
.data[0:100].id # First 100 IDs
.response.results[-50:].title # Last 50 titles
# Filter by status with logic
# Aggregate metrics with slicing
### Log File Analysis
```bash
# Find errors excluding debug info
# Extract timestamps with slicing
# Recent log analysis
### CSV Data Processing
```bash
# Column analysis with slicing
.[].column_name | unique[0:20] # Top 20 unique values
# Filtering with logical operations
# Multi-column processing
### Configuration File Analysis
```bash
# Non-comment, non-empty lines
# Configuration sections
# Key-value extraction
## Performance Tips
### Efficient Query Patterns
```bash
# ✅ Filter early, slice after
.large_array[] | select(.condition) | .[0:100] | expensive_operation
# ❌ Process everything then filter
### Memory Considerations with Slicing
```bash
# ✅ Process data in chunks
# ❌ Load everything into memory
### Logical Operation Efficiency
```bash
# ✅ Use specific conditions early
# ❌ Complex logical operations on large datasets
---
**Related Documentation:**
- [Getting Started Guide](getting-started.md) - Quick introduction
- [String Operations](string-operations.md) - Detailed text processing
- [Examples](examples/) - Real-world use cases
- [Advanced Topics](advanced/) - Performance and optimization