Okay, let's create a Spring Boot application that exposes a REST endpoint /api/query to execute Spark SQL queries against a given dataset path.
We'll need the following components:
pom.xml: Project dependencies (Spring Web, Spark, Lombok).
SparkConfig.java: Configures and provides the SparkSession bean.
QueryRequest.java: A DTO (Data Transfer Object) for the incoming JSON request.
AnalyticsService.java: The service layer that handles Spark logic.
QueryController.java: The REST controller that exposes the /api/query endpoint.
SparkSpringBootApiApplication.java: The main Spring Boot application class.
1. Project Setup (pom.xml)
First, create a new Spring Boot project (e.g., using Spring Initializr: https://start.spring.io/). Choose Maven project, Java 17+, and add Spring Web dependency.
Then, manually add Spark dependencies to your pom.xml.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version> <!-- Use a recent Spring Boot version -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spark-springboot-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spark-springboot-api</name>
<description>Demo project for Spring Boot Spark Integration</description>
<properties>
<java.version>17</java.version>
<spark.version>3.5.0</spark.version> <!-- Use a recent Spark version -->
<scala.binary.version>2.12</scala.binary.version> <!-- Matches Spark's Scala version -->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spark Dependencies -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
<!-- Exclude Netty dependencies if they clash with Spring Boot's -->
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Optional: If you need to read specific formats like Avro, add their respective packages -->
<!-- For CSV, Parquet, JSON, Spark 3.x usually has built-in support -->
<!-- Lombok (for DTOs - highly recommended) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Note on Netty exclusions: Sometimes, Spark's transitive Netty dependencies can conflict with Spring Boot's or other libraries. Adding those <exclusions> can help resolve potential NoSuchMethodError or ClassNotFoundException issues related to Netty. This might not always be necessary but is a common troubleshooting step.
2. Spark Session Configuration (src/main/java/com/example/sparkspringbootapi/config/SparkConfig.java)
This class provides a singleton SparkSession bean that Spring can inject wherever needed.
package com.example.sparkspringbootapi.config;
import org.apache.spark.sql.SparkSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SparkConfig {
@Bean
public SparkSession sparkSession() {
// Configure your SparkSession
// .master("local[*]") means Spark will run in local mode using all available cores.
// For production, this would typically be "yarn", "k8s", "mesos", or a specific cluster URL.
return SparkSession.builder()
.appName("SparkSpringBootAPI")
.master("local[*]")
// Optional: Set Spark configurations
// .config("spark.driver.memory", "2g")
// .config("spark.executor.memory", "2g")
// .enableHiveSupport() // Uncomment if you need Hive integration
.getOrCreate();
}
}
3. Request DTO (src/main/java/com/example/sparkspringbootapi/dto/QueryRequest.java)
This simple class will map the incoming JSON body of the POST request.
package com.example.sparkspringbootapi.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Data // Generates getters, setters, toString, equals, and hashCode
@NoArgsConstructor // Generates a no-argument constructor
@AllArgsConstructor // Generates a constructor with all fields
public class QueryRequest {
private String datasetPath;
private String query;
}
4. Analytics Service (src/main/java/com/example/sparkspringbootapi/service/AnalyticsService.java)
This is where the Spark logic resides. It receives the SparkSession via constructor injection.
package com.example.sparkspringbootapi.service;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class AnalyticsService {
private final SparkSession sparkSession;
// SparkSession is @Autowired via the constructor, as requested
@Autowired
public AnalyticsService(SparkSession sparkSession) {
this.sparkSession = sparkSession;
}
/**
* Executes a Spark SQL query against a dataset and returns the results.
*
* @param datasetPath The path to the dataset (e.g., "file:///path/to/data.csv", "s3a://bucket/data.parquet")
* @param query The SQL query to execute against the dataset (e.g., "SELECT * FROM temp_data WHERE age > 30")
* @return A list of maps, where each map represents a row and contains column_name -> value pairs.
* @throws RuntimeException if there's an error during Spark execution.
*/
public List<Map<String, Object>> executeSparkQuery(String datasetPath, String query) {
try {
// 1. Read the dataset into a DataFrame
// For CSV, you often need .option("header", "true") and .option("inferSchema", "true")
// For Parquet/JSON, Spark can typically infer schema and header is not applicable.
// Adjust options based on your dataset format.
Dataset<Row> df = sparkSession.read()
.option("header", "true") // Assuming CSV with header
.option("inferSchema", "true") // Infer schema types
.load(datasetPath);
// 2. Create a temporary view from the DataFrame
// This allows you to run SQL queries against it.
// The view name "temp_data" is what your `query` should reference.
df.createOrReplaceTempView("temp_data");
// 3. Execute the SQL query using SparkSession
Dataset<Row> resultDf = sparkSession.sql(query);
// 4. Collect results and convert them to a list of Maps for JSON serialization
List<Row> rows = resultDf.collectAsList();
return rows.stream()
.map(row -> {
Map<String, Object> rowMap = new java.util.HashMap<>();
// Iterate over the schema fields to get column names and their corresponding values
Arrays.asList(row.schema().fieldNames()).forEach(fieldName -> {
// getAs() returns the value of the field with the given name
// Note: Spark's internal types might not directly map to simple Java types for JSON.
// For complex types (e.g., arrays, structs), you might need custom serialization.
rowMap.put(fieldName, row.getAs(fieldName));
});
return rowMap;
})
.collect(Collectors.toList());
} catch (Exception e) {
// Log the exception for debugging purposes
System.err.println("Error executing Spark query: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException("Failed to execute Spark query: " + e.getMessage(), e);
} finally {
// Optional: Drop the temporary view if it's no longer needed or to prevent name clashes
// For simple, short-lived queries within a single SparkSession, Spark typically handles this.
// If you have many concurrent calls that might try to create the same view,
// consider dynamic view names (e.g., "temp_data_" + UUID.randomUUID())
// or explicit dropping if not handled automatically.
// sparkSession.catalog().dropTempView("temp_data");
}
}
}
5. Query Controller (src/main/java/com/example/sparkspringbootapi/controller/QueryController.java)
This is the REST endpoint that receives the API call.
package com.example.sparkspringbootapi.controller;
import com.example.sparkspringbootapi.dto.QueryRequest;
import com.example.sparkspringbootapi.service.AnalyticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api") // Base path for your API endpoints
public class QueryController {
private final AnalyticsService analyticsService;
@Autowired
public QueryController(AnalyticsService analyticsService) {
this.analyticsService = analyticsService;
}
@PostMapping("/query")
public ResponseEntity<?> queryData(@RequestBody QueryRequest request) {
// Basic validation
if (request.getDatasetPath() == null || request.getDatasetPath().isEmpty()) {
return new ResponseEntity<>("Dataset path cannot be empty.", HttpStatus.BAD_REQUEST);
}
if (request.getQuery() == null || request.getQuery().isEmpty()) {
return new ResponseEntity<>("Query cannot be empty.", HttpStatus.BAD_REQUEST);
}
if (!request.getQuery().toLowerCase().contains("from temp_data")) {
return new ResponseEntity<>("Query must reference 'temp_data' (e.g., 'SELECT * FROM temp_data').", HttpStatus.BAD_REQUEST);
}
try {
List<Map<String, Object>> results = analyticsService.executeSparkQuery(
request.getDatasetPath(),
request.getQuery()
);
return new ResponseEntity<>(results, HttpStatus.OK);
} catch (Exception e) {
// Log the exception details
e.printStackTrace();
// Return a meaningful error message
return new ResponseEntity<>("Error processing query: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
6. Main Application Class (src/main/java/com/example/sparkspringbootapi/SparkSpringBootApiApplication.java)
This is the standard Spring Boot application entry point.
package com.example.sparkspringbootapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SparkSpringBootApiApplication {
public static void main(String[] args) {
SpringApplication.run(SparkSpringBootApiApplication.class, args);
}
}
How to Run and Test
-
Create a Sample Dataset:
Create a file named data.csv in your project's root directory (or any accessible path) with some sample data:
id,name,age,city
1,Alice,30,New York
2,Bob,24,London
3,Charlie,35,Paris
4,David,29,New York
5,Eve,40,London
-
Build the Application:
Open your terminal in the project's root directory and run:
mvn clean install
-
Run the Application:
java -jar target/spark-springboot-api-0.0.1-SNAPSHOT.jar
You should see Spring Boot starting up, and Spark logs will appear. The application will typically run on http://localhost:8080.
-
Make an API Call (e.g., using curl or Postman):
Example 1: Select all data
curl -X POST \
http://localhost:8080/api/query \
-H 'Content-Type: application/json' \
-d '{
"datasetPath": "file:///path/to/your/project/root/data.csv",
"query": "SELECT * FROM temp_data"
}'
Replace /path/to/your/project/root/data.csv with the actual absolute path to your data.csv file.
Expected JSON Response:
[
{
"id": 1,
"name": "Alice",
"age": 30,
"city": "New York"
},
{
"id": 2,
"name": "Bob",
"age": 24,
"city": "London"
},
{
"id": 3,
"name": "Charlie",
"age": 35,
"city": "Paris"
},
{
"id": 4,
"name": "David",
"age": 29,
"city": "New York"
},
{
"id": 5,
"name": "Eve",
"age": 40,
"city": "London"
}
]
Example 2: Filter and aggregate data
curl -X POST \
http://localhost:8080/api/query \
-H 'Content-Type: application/json' \
-d '{
"datasetPath": "file:///path/to/your/project/root/data.csv",
"query": "SELECT city, COUNT(*) as count FROM temp_data GROUP BY city HAVING count > 1"
}'
Expected JSON Response:
[
{
"city": "New York",
"count": 2
},
{
"city": "London",
"count": 2
}
]
Important Considerations for Production:
- Spark Master Configuration:
master("local[*]") is for local development. In production, you'd configure it to connect to your Spark cluster (YARN, Kubernetes, Mesos, Standalone).
- Dataset Path:
file:// is for local file systems. For distributed environments, you'd use paths like s3a://your-bucket/path/to/data.parquet, hdfs://namenode:8020/path/to/data.orc, etc. Ensure your Spark cluster has access to these paths and necessary connectors (e.g., hadoop-aws for S3).
- Security: Allowing arbitrary SQL queries from an external API is a security risk. In a real-world scenario, you might want to:
- Validate queries against a whitelist of allowed commands/functions.
- Restrict table names.
- Implement authentication and authorization for the API.
- Error Handling: The current error handling is basic. You might want more specific exceptions and a global exception handler for better API error responses.
- Performance & Resource Management:
- Spark Session is a heavy object; it's correctly managed as a singleton by Spring.
collectAsList() brings all data to the driver (your Spring Boot application). For very large result sets, this can lead to OutOfMemoryError. Consider:
- Returning paginated results.
- Writing query results to an external storage (S3, HDFS, a database) and returning a pointer/path to the results.
- Using Spark streaming if continuous results are needed.
- Data Format Flexibility: The
AnalyticsService currently uses .option("header", "true").option("inferSchema", "true").load(datasetPath). This is common for CSV. If you handle multiple data formats (Parquet, JSON, ORC), you might need to add a format parameter to your QueryRequest DTO and use sparkSession.read().format(request.getFormat()).load(datasetPath).
- Temporary View Names:
createOrReplaceTempView("temp_data") reuses the same name. If multiple concurrent requests hit your service, Spark handles isolation per thread/task for temporary views within a session, but if you're concerned about potential edge cases or very high concurrency, appending a UUID to the view name ("temp_data_" + UUID.randomUUID().toString()) could provide more explicit isolation, though it also means managing view cleanup. For most Spring Boot API use cases with shared SparkSession, createOrReplaceTempView is generally sufficient as it replaces existing views gracefully.