Sunday, 10 August 2025

Getting Started with Loading Data into Apache Druid Using a Spec File and CURL request

Apache Druid is a high-performance, real-time analytics database designed for interactive querying of large datasets. Native batch ingestion using a specification file (also called an ingestion spec) provides greater control over how data is ingested, transformed, and indexed.

 

In this blog, I’ll Walk through the basics of loading data into Druid using a spec file. This is perfect for beginners who want a deeper understanding of Druid's ingestion pipeline and want to start exploring Druid beyond quick demos.

 

1.  Data file to ingest.

sales_data.csv  

timestamp,product,city,sales
2025-04-01T10:00:00Z,Laptop,Delhi,300
2025-04-01T10:00:00Z,Laptop,Delhi,200
2025-04-01T11:00:00Z,Tablet,Mumbai,150
2025-04-01T11:00:00Z,Tablet,Mumbai,50
2025-04-01T12:00:00Z,Mobile,Bengaluru,200
2025-04-01T13:00:00Z,Laptop,Hyderabad,250
2025-04-01T14:00:00Z,Tablet,Chennai,180
2025-04-01T15:00:00Z,Mobile,Pune,220
2025-04-01T15:00:00Z,Mobile,Pune,80

2. Define specification file to ingest the sales data to Druid.

 

sales_data_ingestion_spec.json

{
  "type": "index",
  "spec": {
    "dataSchema": {
      "dataSource": "sales_data",
      "timestampSpec": {
        "column": "timestamp",
        "format": "iso"
      },
      "dimensionsSpec": {
        "dimensions": ["product", "city"]
      },
      "metricsSpec": [
        {
          "type": "doubleSum",
          "name": "total_sales",
          "fieldName": "sales"
        }
      ],
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "day",
        "queryGranularity": "none",
        "rollup": false
      }
    },
    "ioConfig": {
      "type": "index",
      "inputSource": {
        "type": "local",
        "baseDir": "/Users/Shared/druid_samples",
        "filter": "sales_data.csv"
      },
      "inputFormat": {
        "type": "csv",
        "findColumnsFromHeader": true
      }
    },
    "tuningConfig": {
      "type": "index"
    }
  }
}

2.1 What is this spec file?

A Druid ingestion spec file tells Druid how to read, parse, transform, and store data. It contains information like:

 

·      Where is your data?

·      Metadata about the data (Ex: columns like product, city, sales)

·      What do you want to do with them? (sum, group, roll up)

·      How should Druid store the final processed data?

 

Now let's go line-by-line through your file.

 

2.1.1 Full Spec Overview

{
  "type": "index",
  "spec": {
    // ...
  }
}

"type": "index"

This tells Druid you are doing a batch ingestion, which means you’re loading data from files (not real-time streams like Kafka).

 

2.1.2 dataSchema: Describes your data

This section defines:

 

·      What the data looks like

·      Which fields to use

·      How to store and query it

 

{
  "spec": {
    "dataSchema": {
      "dataSource": "sales_data",
      "timestampSpec": {
        "column": "timestamp",
        "format": "iso"
      },
      "dimensionsSpec": {
        "dimensions": [
          "product",
          "city"
        ]
      },
      "metricsSpec": [
        {
          "type": "doubleSum",
          "name": "total_sales",
          "fieldName": "sales"
        }
      ],
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "day",
        "queryGranularity": "none",
        "rollup": false
      }
    }
  }
}

 

"dataSource": "sales_data"

This is the name of your Druid table. After ingestion, your data will live under this name and you can query it like:

SELECT * FROM sales_data;

timestampSpec

"timestampSpec": {
  "column": "timestamp",
  "format": "iso"
}

 

Druid requires a time column to effectively address time-based queries. This tells Druid to use the column named "timestamp" for time based queries and it's in ISO format like "2023-08-01T10:30:00Z"

 

Without a proper timestamp, Druid won’t know when the data created, which is crucial for time-series analysis.

 

dimensionsSpec

"dimensionsSpec": {
  "dimensions": ["product", "city"]
}

 

Dimensions are descriptive fields, you group or filter data by them.

 

In this example:

·      "product" – like "Laptop", "Phone"

·      "city" – like "New York", "London"

 

These are used for slicing/dicing your data:

SELECT SUM(total_sales) FROM sales_data WHERE city = 'New York';

 

metricsSpec

"metricsSpec": [
  {
    "type": "doubleSum",
    "name": "total_sales",
    "fieldName": "sales"
  }
]

 

"metricsSpec": This is an array that lists the metrics you want Druid to ingest and aggregate.

 

"type": "doubleSum"

This specifies the type of aggregation to perform on the data in the "fieldName". In this case, it's "doubleSum", which means Druid will calculate and store the sum of the values found in the "sales" column as a 64-bit floating-point number (double). This aggregation applied when rollup is set to true. In our example, we set the rollup to false, so no aggregated is applied, and raw value is used as it is.

 

"name": "total_sales":

This defines the name that this aggregated metric will have in your Druid datasource after ingestion. When you query this datasource later, you will refer to the sum of the "sales" column using the name "total_sales".

 

"fieldName": "sales":

This specifies the name of the column in your input data source (e.g., a CSV file, Kafka topic, etc.) that contains the numeric values you want to sum. Druid will read the values from this column and apply the doubleSum aggregation.

 

granularitySpec

"granularitySpec": {
  "type": "uniform",
  "segmentGranularity": "day",
  "queryGranularity": "none",
  "rollup": false
}

·      "granularitySpec": This is the top-level object that contains the configuration for time-based partitioning and querying.

 

·      "type": "uniform": This specifies the type of granularitySpec. "uniform" indicates that Druid should create segments of a uniform time duration, as defined by segmentGranularity.

 

·      "segmentGranularity": "day": This parameter defines the time chunking for how Druid stores your data into segments. In this case, "day" means that Druid will aim to create new data segments that contain data for a single day. For example, all data ingested on April 18, 2025, will likely be stored in one or more segments covering that entire day. Segment granularity is crucial for efficient data storage and querying, as Druid prunes segments that are not relevant to a query.

 

·      "queryGranularity": "none": This parameter defines the lowest level of time precision that will be available for querying. Setting it to "none" means that Druid will retain the original timestamp precision of your data during ingestion and will not truncate or aggregate timestamps at a coarser level for querying. When you query this data, you will be able to group and filter down to the most granular timestamp available in your raw data.

 

·      "rollup": false": This parameter controls ingestion-time data rollup (pre-aggregation). When set to false, Druid will not automatically pre-aggregate data during the ingestion process based on the dimensions and the segmentGranularity. Each raw event will be stored as a separate record (within the bounds of the segmentGranularity). If rollup were set to true, Druid would attempt to aggregate rows with the same timestamp and dimension values based on the specified aggregators in the "metricsSpec", potentially reducing the storage footprint and improving query performance for aggregated queries. However, with rollup: false, you retain the ability to perform more flexible aggregations at query time.

 

2.1.3 ioConfig: Where the data comes from

This section tells Druid where and how to read your source file.

"ioConfig": {
  "type": "index",
  "inputSource": {
    "type": "local",
    "baseDir": "/Users/Shared/druid_samples",
    "filter": "sales_data.csv"
  },
  // ...
}

 

·      "ioConfig": This is the top-level object that configures the input and parsing aspects of the ingestion process.

 

·      "type": "index": This specifies the ingestion task type. "index" is the standard task type for batch ingestion of data directly into Druid segments.

 

·      "inputSource": This nested object defines the source of your input data.

 

·      "type": "local": This indicates that the input data is located on the local filesystem of the Druid indexing task node.

 

·      "baseDir": "/Users/Shared/druid_samples": This specifies the base directory on the local filesystem where Druid should look for the input files.

 

·      "filter": "sales_data.csv": This is a filter that tells Druid which files within the baseDir to process. In this case, it will only process the file named sales_data.csv.

 

 

3. Submit the spec file to Druid using following curl command.

curl -X POST http://localhost:8081/druid/indexer/v1/task \
     -H 'Content-Type: application/json' \
     -d @sales_data_ingestion_spec.json

$curl -X POST http://localhost:8081/druid/indexer/v1/task \
>      -H 'Content-Type: application/json' \
>      -d @sales_data_ingestion_spec.json
{"task":"index_sales_data_dgbdecpd_2025-04-18T08:02:05.636Z"}

 

Navigate to Tasks tab in Druid, you can observe that the task is successfully completed.

 


Navigate to Query tab and execute the following query to print the records of sales_data datasoruce.

SELECT * FROM "sales_data"

 


Let’s update the config file by setting rollup to true.

sales_data_aggregated_ingestion_spec.json 

{
  "type": "index",
  "spec": {
    "dataSchema": {
      "dataSource": "sales_data_aggregated",
      "timestampSpec": {
        "column": "timestamp",
        "format": "iso"
      },
      "dimensionsSpec": {
        "dimensions": ["product", "city"]
      },
      "metricsSpec": [
        {
          "type": "doubleSum",
          "name": "total_sales",
          "fieldName": "sales"
        }
      ],
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "day",
        "queryGranularity": "none",
        "rollup": true
      }
    },
    "ioConfig": {
      "type": "index",
      "inputSource": {
        "type": "local",
        "baseDir": "/Users/Shared/druid_samples",
        "filter": "sales_data.csv"
      },
      "inputFormat": {
        "type": "csv",
        "findColumnsFromHeader": true
      }
    },
    "tuningConfig": {
      "type": "index"
    }
  }
}

Submit above schema file

curl -X POST http://localhost:8081/druid/indexer/v1/task \
     -H 'Content-Type: application/json' \
     -d @sales_data_aggregated_ingestion_spec.json

 


 

In this example, as we set the rollout to true, Druid groups data based on these dimensions + timestamp (rounded by queryGranularity). 

  

Previous                                                    Next                                                    Home

Druid Architecture

Druid uses a distributed system, which means it runs on a group of computers that work together. It's built to work well in the cloud and is designed to be easy to manage. You can adjust or grow different parts of the system separately, which gives you a lot of control and flexibility.

Druid is also built to be fault-tolerant, if one component stops working, the rest of the system can keep running without crashing.

 

The diagram below shows the different parts of Druid, how they are usually set up across machines, and how data is stored, and queries are executed in the system.

 


Druid Services

Druid is made up of different parts, and each part has a special job:

 

·      Coordinator: Makes sure that the data is available on the system.

·      Overlord: Controls the assignment of data ingestion workloads.  In simple terms, it manages the process of bringing new data into Druid.

·      Broker: Handle Queries from external clients

·      Router: Routes requests to Brokers, Coordinators, and Overlords. Historical: Stores data that’s ready to be searched and used in queries.

·      Middle Manager + Peon: Work together to bring in and process new data.

·      Indexer: A newer option that can do the same work as the Middle Manager and Peon, but in a simpler way.

 

You can view services in the Services tab in the web console:

 


1. Master Server

In a Druid cluster, a Master Server is not a single machine, but rather a logical role performed by two important services:

 

·      Coordinator Service

·      Overlord Service

 

Together, these two "brain-like" components manage the whole cluster's behavior. They don’t process queries or store data directly, instead, they make decisions about where and how data is stored and how new data should be ingested.

 

1.1 Coordinator Service ("The Segment Manager")

 

The Coordinator is a Master Server process responsible for the management and optimization of data availability within the Druid cluster. Its key responsibilities include:

 

·      Segment Management: Tracking the location and health of data segments (the fundamental storage unit in Druid) across the Historical nodes.

·      Load Balancing: Ensuring that data segments are evenly distributed across the Historical nodes to optimize query performance and resource utilization.

·      Data Tiering: Managing the movement of segments between different storage tiers based on configured rules (e.g., moving older, less frequently accessed data to cheaper storage).

·      Compaction: Initiating tasks to merge smaller segments into larger ones to improve query efficiency.

·      Data Retention: Enforcing data retention policies by identifying and marking old segments for deletion.

·      The Coordinator communicates with the Historical nodes to assign and manage segments. Typically, in a production environment, you would have one active Coordinator and one or more standby Coordinators for high availability.

 

1.2 Overlord Service:

The Overlord is another Master Server process that manages and orchestrates data ingestion tasks. Its main responsibilities include:

 

·      Task Management: Accepting and managing the lifecycle of ingestion tasks submitted by clients or other Druid processes (like MiddleManagers).

·      Task Assignment: Assigning ingestion tasks to available MiddleManager nodes (or Peons/Indexers in other ingestion models).

·      Task Monitoring: Tracking the progress and status of running ingestion tasks.

·      Coordination of Segment Publishing: Ensuring that newly created data segments are properly published to deep storage and made available for querying by the Historical nodes (informing the Coordinator about new segments).

·      Similar to the Coordinator, you would typically have an active Overlord and standby Overlords for fault tolerance.

 

2. Query Server

In Druid, Query Server refers to the components that receive, route, and respond to user queries. These are the services that power analytics by turning questions into answers.

 

There are two main services that play a role in the query layer.

 

·      Broker Service (core Query Server)

·      Router Service (optional Query Gateway)

 

Historical and MiddleManager Services (data servers that process parts of the query — not considered Query Servers, but they help fulfill queries)

 

2.1 Router Service:

The Router is an optional Query Server process that provides a unified API gateway in front of the Broker, Coordinator, and Overlord services. Its benefits include:

 

·      The Router is an optional Query Server process that provides a unified API gateway in front of the Broker, Coordinator, and Overlord services. Its benefits include:

·      Simplified Client Interaction: External clients only need to interact with the Router's endpoint, which then handles routing the requests to the appropriate backend service. This simplifies client configurations and can provide a more stable API.

·      Load Balancing: The Router can perform basic load balancing across multiple Broker, Coordinator, and Overlord instances.

·      Security and Authentication: The Router can act as a central point for implementing security measures like authentication and authorization.

·      While optional, Routers are highly recommended for larger, production deployments as they enhance manageability, scalability, and security.

 

The Router service also runs the web console, a UI for loading data, managing datasources and tasks, and viewing server status and segment information.

 

2.2 Broker Service

The Broker is a Query Server process that acts as the entry point for external client queries. Its primary responsibilities include:

 

·      Query Reception: Receiving queries (typically in Druid’s JSON-based query language or SQL) from applications and users.

·      Query Planning and Distribution: Understanding the query and determining which Historical nodes (and potentially MiddleManagers for real-time data) contain the necessary data segments.

·      Query Routing: Forwarding sub-queries to the relevant data nodes (Historicals and MiddleManagers).

·      Result Merging and Aggregation: Collecting the results from the data nodes, performing any final merging or aggregation required by the original query, and returning the final result to the client.

·      Brokers maintain a cache of segment metadata to efficiently route queries. You can scale out Broker services to handle a higher volume of concurrent queries.

 

3. Data Server

A Data server executes ingestion jobs and stores queryable data. Data servers divide operations between Historical and Middle Manager services.

 

3.1 The MiddleManager service

It is a Data Server process that handles the active ingestion of data. Its primary responsibilities include:

 

·      Task Execution: Receiving ingestion tasks from the Overlord and spawning "Peon" processes (or running tasks as threads in "Indexer" service) to execute these tasks.

·      Data Processing: Reading data from the configured input source, transforming it according to the ingestion specification, and creating new Druid segments.

·      Temporary Storage: Using local disk for temporary storage during the data processing and segment creation phases.

·      Segment Hand-off: Once a segment is built, the MiddleManager coordinates the hand-off of the segment to deep storage and informs the Overlord about the completed task.

·      MiddleManagers are scalable, and you add more of them to increase your data ingestion throughput.

 

3.2 Historical Service:

Historical services handle storage and querying on historical data, including any streaming data that has been in the system long enough to be committed. Historical services download segments from deep storage and respond to queries about these segments. They don't accept writes.

 

Its key characteristics include:

·      Segment Storage: Downloading and storing data segments from deep storage on its local disk.

·      Query Processing: Directly processing the parts of incoming queries that pertain to the data segments it holds.

·      No Writes: Historical nodes do not handle data ingestion (writes); they only serve read requests.

·      Historical nodes are designed to be scalable, and you add more of them to increase your capacity for storing and querying historical data. They are typically deployed on machines with significant disk space and memory (for caching frequently accessed data).

 

 

At high level

·      Coordinator manages data availability on the cluster.

·      Overlord controls the assignment of data ingestion workloads.

·      Broker handles queries from external clients.

·      Router routes requests to Brokers, Coordinators, and Overlords.

·      Historical stores queryable data.

·      Middle Manager and Peon ingest data.

 

In summary, Druid's architecture is designed for distributed, high-performance analytics with a clear separation of concerns among its different service types. This modularity allows for independent scaling and fault tolerance of each component, making Druid well-suited for handling large, real-time datasets and serving low-latency queries.

 

Previous                                                    Next                                                    Home

Thursday, 7 August 2025

FileSystemDocumentLoader in Langchain4j: Efficient Document Loading from File System

Langchain4j is a powerful Java framework for building LLM-powered applications. One of its most essential utilities is the FileSystemDocumentLoader, which simplifies loading documents directly from the file system for further processing and indexing. In this post, we will explore how FileSystemDocumentLoader works, the available methods to load documents, and how you can customize document parsing with your own DocumentParser.

What is FileSystemDocumentLoader?

The FileSystemDocumentLoader class offers static methods to load documents from file paths or Path objects. It reads the file content and parses it into Langchain4j's Document model.

 

You can get a Document object using given file path, custom Document Parser using below methods. 

public static Document loadDocument(String filePath)
public static Document loadDocument(Path filePath)
public static Document loadDocument(Path filePath, DocumentParser documentParser)
public static Document loadDocument(String filePath, DocumentParser documentParser)

If you call loadDocument with just the file path, the loader uses the default DocumentParser. Langchain4j loads the default parser through the Java SPI (Service Provider Interface) mechanism, which means you can plug in custom parsers easily without modifying the loader code.

 

You can specify your own DocumentParser implementation to handle file formats in a custom way.

 

How Document Parsing Works?

At the core of parsing is the DocumentParser interface.

public interface DocumentParser {
    Document parse(InputStream inputStream);
}

It takes an InputStream from the file. Parses the content and returns a Document object.

 

Loading Multiple Documents from a Directory

Langchain4j’s FileSystemDocumentLoader also provides convenient methods to load all documents within a specified folder. This makes it easy to bulk ingest content from a directory without manually handling individual files.

 

You can load all documents in a folder using the following overloaded methods:

public static List<Document> loadDocuments(Path directoryPath)
public static List<Document> loadDocuments(String directoryPath)
public static List<Document> loadDocuments(Path directoryPath, DocumentParser documentParser)
public static List<Document> loadDocuments(String directoryPath, DocumentParser documentParser)

Simply provide the directory path (as a String or Path) and the loader will process every file found in that folder using the default parser. If you want to apply a custom parsing strategy to all files, pass your own DocumentParser instance to control how each document is read and converted.

 

Filtering Documents Using PathMatcher

Sometimes, you may want to load only a subset of documents from a folder, for example, only .txt files or files matching a specific naming pattern. The loader supports this by accepting a PathMatcher, which acts as a filter to select files that meet certain criteria.

public static List<Document> loadDocuments(Path directoryPath, PathMatcher pathMatcher)
public static List<Document> loadDocuments(String directoryPath, PathMatcher pathMatcher)
public static List<Document> loadDocuments(Path directoryPath, PathMatcher pathMatcher, DocumentParser documentParser)
public static List<Document> loadDocuments(String directoryPath, PathMatcher pathMatcher, DocumentParser documentParser)

You can also specify a DocumentParser to handle filtered files with your preferred parsing logic.

 

Recursive Loading of Documents in Subdirectories

In many real-world scenarios, documents are organized into nested folders. Langchain4j’s loader allows you to recursively load documents from a directory and all its subdirectories with a set of similarly overloaded methods.

public static List<Document> loadDocumentsRecursively(Path directoryPath)
public static List<Document> loadDocumentsRecursively(String directoryPath)
public static List<Document> loadDocumentsRecursively(String directoryPath, DocumentParser documentParser)
public static List<Document> loadDocumentsRecursively(Path directoryPath, DocumentParser documentParser)
public static List<Document> loadDocumentsRecursively(Path directoryPath, PathMatcher pathMatcher)
public static List<Document> loadDocumentsRecursively(String directoryPath, PathMatcher pathMatcher)
public static List<Document> loadDocumentsRecursively(String directoryPath, PathMatcher pathMatcher, DocumentParser documentParser)
public static List<Document> loadDocumentsRecursively(Path directoryPath, PathMatcher pathMatcher, DocumentParser documentParser)

Find the below working application.

 

FileSystemDocumentLoaderDemo.java

package com.sample.app.documentloaders;

import java.util.List;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;

public class FileSystemDocumentLoaderDemo {
	public static void main(String[] args) {
		List<Document> documents = FileSystemDocumentLoader.loadDocuments("/Users/Shared/llm_docs/");
		
		for(Document document: documents) {
			System.out.println(document.metadata());
		}
	}

}

 

In summary, the FileSystemDocumentLoader provide flexible methods for loading documents from folders allow you to easily bulk ingest documents.

 

·      Load all documents in a folder with or without a custom parser.

·      Filter which documents to load by specifying a PathMatcher.

·      Recursively traverse folders and subfolders to load documents deeply.

·      Combine filtering and custom parsing seamlessly during recursive loading.

 

This rich API helps you build robust, scalable pipelines for document ingestion in Langchain4j applications.

 

Previous                                                    Next                                                    Home

Langchain4j’s Default Embedding Model: bge-small-en-v1.5 – Tiny in Size, Big on Performance

Langchain4j has officially adopted bge-small-en-v1.5 as the default embedding model for Easy RAG applications. This blog post introduces the model, explains why it was chosen, how it’s integrated into Langchain4j, and why it is ideal for developers who want lightweight, high-performance RAG applications.

Retrieval-Augmented Generation (RAG) workflows rely heavily on powerful embedding models to transform text into vector representations. The better the embeddings, the more relevant the retrieved context and the better the final response quality from the LLM.

 

Langchain4j has made an exciting default choice for this purpose: bge-small-en-v1.5.

 

Why bge-small-en-v1.5?

·      Top Performance: This model ranks impressively high on the MTEB (Massive Text Embedding Benchmark, https://huggingface.co/spaces/mteb/leaderboard), outperforming many larger alternatives while staying compact and efficient.

 

·      Tiny Footprint: Its quantized version weighs just 24MB, making it ideal for edge deployments, local development, and low-latency use cases. Quantization is a technique used in machine learning to reduce the size of a model and make it faster, without significantly sacrificing performance.

 

How to Use It in Langchain4j

Langchain4j offers a plug-and-play experience. You can load the quantized version of bge-small-en-v1.5 with a single line of Java code.

EmbeddingModel embeddingModel = new BgeSmallEnV15QuantizedEmbeddingModel();

No need to spin up separate services or deal with heavy models. This model runs directly in-process using ONNX Runtime under the hood.

 

Where It Fits: Easy RAG with Langchain4j?

Langchain4j's Easy RAG setup aims to minimize configuration and maximize developer productivity. By making bge-small-en-v1.5 the default, Langchain4j ensures:

 

·      No extra downloads or model selection hassle

·      Instant availability for embedding documents and queries

·      High-quality retrieval performance with minimal compute requirements

 


Previous                                                    Next                                                    Home