Friday, 29 August 2025

Transforming Dimensions in Apache Druid: Using Uppercase on City and Product Fields

Apache Druid is a powerful real-time analytics database designed for fast slice-and-dice analytics on large datasets. It supports transforming data during ingestion to help clean, normalize, and enrich it for faster and more effective queries.

In this post, we’ll walk through a simple use case of applying transformations to columns in a CSV file before ingesting it into Druid. Specifically, we’ll demonstrate how to use the upper transformation on the city and product columns to ensure consistent capitalization, an essential step in preparing data for reliable filtering, grouping, and analysis.

 

Whether you're new to Druid or exploring your first ingestion spec, this post will help you get started with transformations.

 

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

Let’s transform the product and city columns to uppercase before they are stored in Druid.

 

We’ll define an ingestion spec using the Druid native batch ingestion method and use the transformSpec section to apply the upper function on both product and city.

 

sales_data_transformation.json

 

{
  "type": "index",
  "spec": {
    "dataSchema": {
      "dataSource": "sales_data_transformation_demo",
      "timestampSpec": {
        "column": "timestamp",
        "format": "iso"
      },
      "dimensionsSpec": {
        "dimensions": [
          "product_upper",
          "city_upper"
        ]
      },
      "transformSpec": {
        "transforms": [
          {
            "type": "expression",
            "name": "product_upper",
            "expression": "upper(product)"
          },
          {
            "type": "expression",
            "name": "city_upper",
            "expression": "upper(city)"
          }
        ]
      },
      "metricsSpec": [
        {
          "name": "total_sales",
          "type": "doubleSum",
          "fieldName": "sales"
        }
      ],
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "day",
        "queryGranularity": "hour",
        "rollup": false
      }
    },
    "ioConfig": {
      "type": "index",
      "inputSource": {
        "type": "local",
        "baseDir": "/Users/Shared/druid_samples",
        "filter": "sales_data.csv"
      },
      "inputFormat": {
        "type": "csv",
        "columns": ["timestamp", "product", "city", "sales"]
      }
    },
    "tuningConfig": {
      "type": "index"
    }
  }
}

Execute following curl command to submit sales_data_transformation.json spec to Druid.  

 

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

curl -X POST http://localhost:8081/druid/indexer/v1/task \
>      -H 'Content-Type: application/json' \
>      -d @sales_data_transformation.json
{"task":"index_sales_data_transformation_demo_ojacglhm_2025-04-18T13:11:30.578Z"}

Navigate to Druid Workbench -> Query tab, and execute following sql query.

SELECT * FROM "sales_data_transformation_demo"

 

How Transformation is Done in This Spec?

In this ingestion spec, transformations are handled by the transformSpec block. This block is used to define new fields that are derived from existing columns using expression functions during ingestion.


 

 

"transformSpec": {
  "transforms": [
    {
      "type": "expression",
      "name": "product_upper",
      "expression": "upper(product)"
    },
    {
      "type": "expression",
      "name": "city_upper",
      "expression": "upper(city)"
    }
  ]
}

What This Does?

Defines two new fields:

·      product_upper

·      city_upper

 

Each field is created by applying the upper() function:

·      product_upper takes the value of the original product column and converts it to uppercase.

·      city_upper does the same for the city column.

 

If the original row looks like this:

2025-04-01T10:00:00Z,Laptop,Delhi,300

 

After applying the transformations:

 

·      product_upper becomes LAPTOP

·      city_upper becomes DELHI

 

These transformed fields are then treated as dimensions (declared in dimensionsSpec) and can be used for filtering, grouping, or displaying in queries.

 

 

Previous                                                    Next                                                    Home

Transforming TextSegments in LangChain4j: Enhance Retrieval Quality with Custom Transformers

When building retrieval-augmented generation (RAG) systems, it's not just how you chunk documents that matters, but also how you transform and enrich those chunks, known as TextSegments. LangChain4j provides the TextSegmentTransformer interface, which lets you customize these transformations. This can help to optimize search results, reduce noise, and add valuable context to each chunk (like titles or summaries).

This post shows how to implement a custom TextSegmentTransformer that enriches segments with the document title and filters out segments that are too short to be useful.

 

Why Use TextSegmentTransformer?

In LangChain4j, documents are split into smaller pieces called TextSegments. These are the units used for retrieval when querying your vector store. Before storing them, it's often beneficial to:

 

·      Clean up text (e.g., remove boilerplate)

·      Filter out irrelevant or tiny segments

·      Enrich with metadata (e.g., document title or summary)

·      The TextSegmentTransformer interface makes this easy to do.

 

Find the below working application.

 

TextSegmentTransformerDemo.java

package com.sample.app.textsegment;

import java.util.List;

import dev.langchain4j.data.document.Metadata;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.data.segment.TextSegmentTransformer;

public class TextSegmentTransformerDemo {

	public static class TitlePrependingSegmentTransformer implements TextSegmentTransformer {

		@Override
		public TextSegment transform(TextSegment segment) {
			// Filter out short segments
			String originalText = segment.text();
			if (originalText == null || originalText.length() < 20) {
				return null;
			}

			// Get the document title from metadata, if available
			String title = segment.metadata().getString("title");
			if (title == null || title.isEmpty()) {
				title = "Untitled";
			}

			// Prepend the title to the text
			String enrichedText = title + ": " + originalText;

			// Return a new TextSegment with enriched text and same metadata
			return new TextSegment(enrichedText, segment.metadata());
		}
	}

	public static void main(String[] args) {
		List<TextSegment> originalSegments = List.of(
				new TextSegment("Intro to LangChain4j.", Metadata.from("title", "LangChain4j Overview")),
				new TextSegment("Short", Metadata.from("title", "LangChain4j Overview")),
				new TextSegment("It supports document parsing, segmentation, and transformation.",
						Metadata.from("title", "LangChain4j Overview")));

		TextSegmentTransformer transformer = new TitlePrependingSegmentTransformer();
		List<TextSegment> transformed = transformer.transformAll(originalSegments);

		transformed.forEach(segment -> System.out.println(segment.text()));
	}

}

Output

LangChain4j Overview: Intro to LangChain4j.
LangChain4j Overview: It supports document parsing, segmentation, and transformation.

In summary, LangChain4j gives you full control over how your data flows through a RAG system. With TextSegmentTransformer, you can fine tune the quality of segments used for retrieval by filtering, enriching, or reshaping them.  

  

Previous                                                    Next                                                    Home

Split Large Documents for LLMs: Understanding DocumentSplitter in LangChain4j

With the rise of Large Language Models (LLMs), integrating them into Java applications has become increasingly popular. However, working with large documents comes with a challenge due to the limited context window of LLMs. LangChain4j offers a clean solution through its DocumentSplitter interface, which allows developers to split large documents into smaller, manageable text segments before feeding them to an LLM. This blog post explains the importance of document splitting and walks through the LangChain4j DocumentSplitter interface.

 

Why Document Splitting?

Imagine you are trying to feed a 50 page document into an LLM in one go. You’ll likely hit the model’s token limit. Not only this is inefficient, but it also leads to errors or loss of crucial information.

 

Instead, by splitting the document into smaller parts (text segments), we can

·      Stay within the token limit

·      Select only the most relevant segments for the task

·      Improve LLM response quality and performance

 

DocumentSplitter Interface 

LangChain4j provides the DocumentSplitter interface to define how documents should be split.

public interface DocumentSplitter {

    /**
     * Splits a single Document into a list of TextSegment objects.
     */
    List<TextSegment> split(Document document);

    /**
     * Splits a list of Documents into segments.
     * A convenient default method.
     */
    default List<TextSegment> splitAll(List<Document> documents) {
        return documents.stream()
                .flatMap(document -> split(document).stream())
                .collect(toList());
    }
}

What is a TextSegment?

A TextSegment is a smaller, manageable portion of the original document. These segments are enriched with metadata and used in retrieval-augmented generation (RAG) pipelines, making them easier to send to an LLM.

 

Different Document Splitters supported by Langchain4j

LangChain4j provides a versatile DocumentSplitter interface along with several built-in implementations for different splitting strategies. Let’s explore each of them:

 

·      DocumentByParagraphSplitter: Splits the document based on paragraph boundaries.

·      DocumentByLineSplitter: Splits the content line by line.

·      DocumentBySentenceSplitter: Breaks the document into individual sentences.

·      DocumentByWordSplitter: Divides the text into separate words.

·      DocumentByCharacterSplitter: Splits the text at the character level.

·      DocumentByRegexSplitter:Uses regular expressions to define custom splitting patterns.

·      Recursive Splitter created using DocumentSplitters.recursive(...),

 

Following snippet split the document by paragraph.

 

DocumentByParagraphSplitterDemo.java

 

package com.sample.app.document.splitters;

import java.util.List;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.splitter.DocumentByParagraphSplitter;
import dev.langchain4j.data.segment.TextSegment;

public class DocumentByParagraphSplitterDemo {
  private static final String CONTENT = """
      LangChain4j is a powerful Java framework that helps developers integrate Large Language Models (LLMs) into their applications. It offers components like document loaders, text segmenters, retrievers, and chat interfaces, making it easy to build LLM-powered apps in Java.
      Text segmentation is a crucial step in building scalable and efficient LLM solutions. Rather than sending an entire document to the LLM, which might exceed token limits or introduce irrelevant noise, it's more practical to split the content into meaningful segments.
      For instance, if you’re building a document search engine, you want the LLM to search through relevant pieces instead of parsing a 100-page document at once. Segments can be paragraphs, sentences, or even semantically meaningful sections, depending on your use case.
      Let’s say you are analyzing a user manual. The introduction, setup instructions, troubleshooting steps, and safety guidelines can be treated as separate segments. This makes it easier to retrieve and serve only the part of the document that answers the user's query.
      LangChain4j supports different splitting strategies such as fixed-size chunking, recursive splitting, or custom logic based on punctuation or semantics. Choosing the right strategy impacts the quality of responses generated by the LLM.
      In summary, proper segmentation reduces cost, enhances response relevance, and ensures faster processing times. It also improves traceability, making it easier to understand why the LLM gave a certain response.
            """;

  public static void main(String[] args) {
    Document document = Document.from(CONTENT);
    DocumentByParagraphSplitter splitter = new DocumentByParagraphSplitter(200, 30);

    List<TextSegment> textSegments = splitter.split(document);
    int seqNo = 1;
    for (TextSegment textSegment : textSegments) {
      System.out.println(seqNo + "." + textSegment.text());
      seqNo++;
    }

  }

}

Output

1.LangChain4j is a powerful Java framework that helps developers integrate Large Language Models (LLMs) into their applications.
2.It offers components like document loaders, text segmenters, retrievers, and chat interfaces, making it easy to build LLM-powered apps in Java.
3.Text segmentation is a crucial step in building scalable and efficient LLM solutions.
4.Rather than sending an entire document to the LLM, which might exceed token limits or introduce irrelevant noise, it's more practical to split the content into meaningful segments.
5.For instance, if you’re building a document search engine, you want the LLM to search through relevant pieces instead of parsing a 100-page document at once.
6.Segments can be paragraphs, sentences, or even semantically meaningful sections, depending on your use case. Let’s say you are analyzing a user manual.
7.The introduction, setup instructions, troubleshooting steps, and safety guidelines can be treated as separate segments.
8.This makes it easier to retrieve and serve only the part of the document that answers the user's query.
9.LangChain4j supports different splitting strategies such as fixed-size chunking, recursive splitting, or custom logic based on punctuation or semantics.
10.Choosing the right strategy impacts the quality of responses generated by the LLM. In summary, proper segmentation reduces cost, enhances response relevance, and ensures faster processing times.
11.It also improves traceability, making it easier to understand why the LLM gave a certain response.

How DocumentSplitter Works in LangChain4j?

To begin, we need to create a DocumentSplitter by specifying the desired size of each TextSegment, along with an optional overlap in characters or tokens to help preserve context between segments.

 

Next, we should invoke the split(Document) or splitAll(List<Document>) methods to split the content. The splitter processes the document(s) into smaller units based on the splitting strategy used.

 

For example,

 

·      DocumentByParagraphSplitter divides the content into paragraphs using two or more consecutive newline characters as boundaries.

·      DocumentBySentenceSplitter detects sentence boundaries using the OpenNLP library.

·      Other strategies split by lines, words, characters, or custom patterns.

 

After splitting into these smaller units, the splitter groups them into TextSegments, each containing as many units as possible without exceeding the specified size limit.

 

If any individual unit is still too large to fit within a segment, the splitter delegates the task to a sub-splitter, which applies a more granular splitting method. Each resulting TextSegment inherits all metadata from the original Document, and an additional metadata field called "index" is added to indicate its position in the sequence starting from index = 0 for the first segment, index = 1 for the second, and so on.

 


Previous                                                    Next                                                    Home

Thursday, 28 August 2025

Ingesting Files Using post-index-task of Druid command

In this post, you’ll learn how to use the post-index-task command-line tool to ingest a CSV file into Druid running locally.

Sample Data

We’ll be working with a file called 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

Ingestion Spec

To load this data into Druid, we need an ingestion spec that tells Druid how to parse the file and where to store it.

 

Save the following JSON as:

sales_data_via_post_index_ingestion_spec.json

{
  "type": "index",
  "spec": {
    "dataSchema": {
      "dataSource": "sales_data_via_post_index",
      "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"
    }
  }
}

 

Running the Ingestion

Use the post-index-task tool to post the ingestion spec to Druid:

post-index-task --file sales_data_via_post_index_ingestion_spec.json --url http://localhost:8081

‘post-index-task’ command line tool is available in Druid bin directory.

$post-index-task --file sales_data_via_post_index_ingestion_spec.json --url http://localhost:8081
Beginning indexing data for sales_data_via_post_index
Task started: index_sales_data_via_post_index_ccbpifce_2025-04-18T08:44:43.646Z
Task log:     http://localhost:8081/druid/indexer/v1/task/index_sales_data_via_post_index_ccbpifce_2025-04-18T08:44:43.646Z/log
Task status:  http://localhost:8081/druid/indexer/v1/task/index_sales_data_via_post_index_ccbpifce_2025-04-18T08:44:43.646Z/status
Task index_sales_data_via_post_index_ccbpifce_2025-04-18T08:44:43.646Z still running...
Task finished with status: SUCCESS
Completed indexing data for sales_data_via_post_index. Now loading indexed data onto the cluster...
sales_data_via_post_index is 0.0% finished loading...
sales_data_via_post_index loading complete! You may now query your data

 

Go to Druid Query page and exeucte following SELECT statement.

SELECT * FROM "sales_data_via_post_index"

 

You can see the records of "sales_data_via_post_index" datasource.

 


With just one command, you’ve ingested your first CSV file into Druid using post-index-task! This method is great for testing and small-scale imports. For production ingestion, you'd typically use Druid's supervisor-based ingestion or connect to cloud object stores.

 

Previous                                                    Next                                                    Home