Here's a PowerShell script to make a POST call to your /query API endpoint:
# Define the API endpoint URL
$apiUrl = "http://localhost:8080/api/query"
# Define the request body with datasetPath and query parameters
$requestBody = @{
datasetPath = "file:///C:/path/to/your/data.csv" # Update this path
query = "SELECT * FROM temp_data WHERE age > 25"
} | ConvertTo-Json
# Set the headers
$headers = @{
"Content-Type" = "application/json"
}
try {
# Make the POST request
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $requestBody -Headers $headers
# Display the response (list of maps/objects)
Write-Host "Query executed successfully. Results:" -ForegroundColor Green
# Pretty print the JSON response
$response | ConvertTo-Json -Depth 10 | Write-Host
# Alternative: Display as a table (works well for flat data)
# $response | Format-Table -AutoSize
# Alternative: Access individual records
# foreach ($record in $response) {
# Write-Host "ID: $($record.id), Name: $($record.name), Age: $($record.age), City: $($record.city)"
# }
} catch {
Write-Host "Error occurred while calling the API:" -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
# If there's a response body with error details
if ($_.Exception.Response) {
$reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
$errorResponse = $reader.ReadToEnd()
Write-Host "Error details: $errorResponse" -ForegroundColor Yellow
}
}
Here are several variations and examples:
Example 1: Basic Query with Error Handling
# Function to call the Spark query API
function Invoke-SparkQuery {
param(
[Parameter(Mandatory=$true)]
[string]$DatasetPath,
[Parameter(Mandatory=$true)]
[string]$Query,
[string]$ApiUrl = "http://localhost:8080/api/query"
)
$body = @{
datasetPath = $DatasetPath
query = $Query
} | ConvertTo-Json
try {
$response = Invoke-RestMethod -Uri $ApiUrl -Method Post -Body $body -ContentType "application/json"
return $response
} catch {
throw "API call failed: $_"
}
}
# Usage
$results = Invoke-SparkQuery -DatasetPath "file:///C:/data/sample.csv" -Query "SELECT * FROM temp_data LIMIT 10"
$results | Format-Table
Example 2: Query with Filtering and Aggregation
# Define multiple queries
$queries = @(
@{
name = "All Records"
datasetPath = "file:///C:/data/employees.csv"
query = "SELECT * FROM temp_data"
},
@{
name = "High Earners"
datasetPath = "file:///C:/data/employees.csv"
query = "SELECT name, salary FROM temp_data WHERE salary > 50000 ORDER BY salary DESC"
},
@{
name = "Department Summary"
datasetPath = "file:///C:/data/employees.csv"
query = "SELECT department, COUNT(*) as employee_count, AVG(salary) as avg_salary FROM temp_data GROUP BY department"
}
)
# Execute each query
foreach ($q in $queries) {
Write-Host "`nExecuting query: $($q.name)" -ForegroundColor Cyan
Write-Host "Query: $($q.query)" -ForegroundColor Gray
$body = @{
datasetPath = $q.datasetPath
query = $q.query
} | ConvertTo-Json
try {
$response = Invoke-RestMethod -Uri "http://localhost:8080/api/query" -Method Post -Body $body -ContentType "application/json"
$response | Format-Table -AutoSize
} catch {
Write-Host "Failed to execute query: $_" -ForegroundColor Red
}
}
Example 3: Save Results to CSV
# Query and save results to CSV
$apiUrl = "http://localhost:8080/api/query"
$outputPath = "C:/output/query_results.csv"
$requestBody = @{
datasetPath = "file:///C:/data/sales.parquet"
query = "SELECT product_id, product_name, SUM(quantity) as total_sold, SUM(revenue) as total_revenue FROM temp_data GROUP BY product_id, product_name ORDER BY total_revenue DESC"
} | ConvertTo-Json
try {
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $requestBody -ContentType "application/json"
# Convert the list of maps to PowerShell objects and export to CSV
$response | Export-Csv -Path $outputPath -NoTypeInformation
Write-Host "Results saved to: $outputPath" -ForegroundColor Green
Write-Host "Total records: $($response.Count)" -ForegroundColor Cyan
} catch {
Write-Host "Error: $_" -ForegroundColor Red
}
Example 4: Interactive Query Tool
# Interactive Spark Query Tool
function Start-SparkQueryTool {
$apiUrl = "http://localhost:8080/api/query"
Write-Host "Spark Query Tool" -ForegroundColor Yellow
Write-Host "================`n" -ForegroundColor Yellow
while ($true) {
# Get dataset path
$datasetPath = Read-Host "Enter dataset path (or 'quit' to exit)"
if ($datasetPath -eq 'quit') { break }
# Get query
$query = Read-Host "Enter SQL query"
if ($query -eq 'quit') { break }
# Prepare request
$body = @{
datasetPath = $datasetPath
query = $query
} | ConvertTo-Json
try {
Write-Host "`nExecuting query..." -ForegroundColor Cyan
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $body -ContentType "application/json"
if ($response.Count -eq 0) {
Write-Host "No results found." -ForegroundColor Yellow
} else {
Write-Host "Results ($($response.Count) rows):" -ForegroundColor Green
$response | Format-Table -AutoSize
}
} catch {
Write-Host "Error: $_" -ForegroundColor Red
}
Write-Host "`n" # Add spacing between queries
}
}
# Run the interactive tool
Start-SparkQueryTool
Example 5: Batch Processing with Progress
# Process multiple datasets with progress tracking
$datasets = @(
"file:///C:/data/sales_2023.csv",
"file:///C:/data/sales_2024.csv",
"s3a://mybucket/data/sales_2025.parquet"
)
$query = "SELECT COUNT(*) as total_records, SUM(amount) as total_sales, AVG(amount) as avg_sale FROM temp_data"
$results = @()
$i = 0
foreach ($dataset in $datasets) {
$i++
Write-Progress -Activity "Processing datasets" -Status "Dataset $i of $($datasets.Count)" -PercentComplete (($i / $datasets.Count) * 100)
$body = @{
datasetPath = $dataset
query = $query
} | ConvertTo-Json
try {
$response = Invoke-RestMethod -Uri "http://localhost:8080/api/query" -Method Post -Body $body -ContentType "application/json"
# Add dataset info to response
$response | ForEach-Object {
$_ | Add-Member -NotePropertyName "dataset" -NotePropertyValue $dataset
}
$results += $response
} catch {
Write-Warning "Failed to process $dataset : $_"
}
}
Write-Progress -Activity "Processing datasets" -Completed
# Display combined results
Write-Host "`nSummary of all datasets:" -ForegroundColor Green
$results | Format-Table -Property dataset, total_records, total_sales, avg_sale -AutoSize
Example 6: Using with Authentication (if your API requires it)
# If your API requires authentication
$apiUrl = "http://localhost:8080/api/query"
$token = "your-auth-token-here"
$headers = @{
"Content-Type" = "application/json"
"Authorization" = "Bearer $token"
}
$body = @{
datasetPath = "hdfs://namenode:8020/user/data/transactions.parquet"
query = "SELECT transaction_date, COUNT(*) as tx_count, SUM(amount) as daily_total FROM temp_data GROUP BY transaction_date ORDER BY transaction_date DESC LIMIT 30"
} | ConvertTo-Json
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Headers $headers -Body $body
$response | ConvertTo-Json -Depth 10
Tips for Using the PowerShell Scripts:
-
Path Format: On Windows, use forward slashes in the file URI: file:///C:/path/to/file.csv
-
Handling Large Results: For large result sets, you might want to save to a file instead of displaying:
$response | ConvertTo-Json -Depth 10 | Out-File -FilePath "results.json"
-
Debugging: To see the raw HTTP response:
$response = Invoke-WebRequest -Uri $apiUrl -Method Post -Body $body -ContentType "application/json"
Write-Host "Status Code: $($response.StatusCode)"
Write-Host "Content: $($response.Content)"
-
PowerShell Version: These examples work with PowerShell 5.1+ and PowerShell Core 7+. For older versions, you might need to use Invoke-WebRequest instead of Invoke-RestMethod.