Tuesday, 16 September 2025

Exploring Apache Druid Native Queries

Apache Druid is a real-time analytics database designed for fast slice-and-dice analytics on large datasets. While SQL is a convenient way to query data in Druid, native queries provide greater flexibility, control, and performance tuning.

 

In this blog post, we’ll explore how to use Druid’s scan native query to extract raw event-level data from a sales_data datasource. We'll walk through examples using real-world sales data.

 

Sample Data: sales_data

I ingested the following CSV into Druid with the name sales_data.

timestamp,product,city,total_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

Each row represents a product sale at a specific timestamp, city, and quantity.

 

1. Scan Query in Druid

The scan query in Druid is used to fetch raw data from your datasource. Unlike groupBy or timeseries queries that aggregate data, scan queries return unprocessed rows in a customizable format.

 

Here’s a basic scan query that fetches all data from the sales_data datasource between two timestamps.

 

{
  "queryType": "scan",
  "dataSource": "sales_data",
  "resultFormat": "compactedList",
  "columns": ["__time", "product", "city", "total_sales"],
  "intervals": ["2025-04-01T10:00:00Z/2025-04-01T16:00:00Z"],
  "batchSize": 35575,
  "limit": 100
}

 


 

Following table summarizes the native query payload.

 

Field

Purpose

queryType

Specifies the query type. In this case, scan

dataSource 

The name of the Druid datasource (your table)

resultFormat 

Format of the result: compactedList, list, or valueVector

columns

List of columns to include in the response

intervals

Time interval filter, ISO 8601 format

batchSize

Number of rows fetched internally per scan

limit

Maximum number of rows returned in the result

 

Output json looks like below.

 

Output 

[
  {
    "segmentId": "sales_data_2025-04-01T00:00:00.000Z_2025-04-02T00:00:00.000Z_2025-04-18T08:18:17.761Z",
    "columns": [
      "__time",
      "product",
      "city",
      "total_sales"
    ],
    "events": [
      [
        1743501600000,
        "Laptop",
        "Delhi",
        300
      ],
      [
        1743501600000,
        "Laptop",
        "Delhi",
        200
      ],
      [
        1743505200000,
        "Tablet",
        "Mumbai",
        150
      ],
      [
        1743505200000,
        "Tablet",
        "Mumbai",
        50
      ],
      [
        1743508800000,
        "Mobile",
        "Bengaluru",
        200
      ],
      [
        1743512400000,
        "Laptop",
        "Hyderabad",
        250
      ],
      [
        1743516000000,
        "Tablet",
        "Chennai",
        180
      ],
      [
        1743519600000,
        "Mobile",
        "Pune",
        220
      ],
      [
        1743519600000,
        "Mobile",
        "Pune",
        80
      ]
    ],
    "rowSignature": [
      {
        "name": "__time",
        "type": "LONG"
      },
      {
        "name": "product",
        "type": "STRING"
      },
      {
        "name": "city",
        "type": "STRING"
      },
      {
        "name": "total_sales",
        "type": "DOUBLE"
      }
    ]
  }
]

  Example 1:  Retrieve all rows where sales happened in a specific hour

 

{
  "queryType": "scan",
  "dataSource": "sales_data",
  "resultFormat": "compactedList",
  "columns": ["__time", "product", "city", "total_sales"],
  "intervals": ["2025-04-01T11:00:00Z/2025-04-01T12:00:00Z"]
}

 

Example 2: Filter specific columns only (e.g., product, city and total_sales) 

{
  "queryType": "scan",
  "dataSource": "sales_data",
  "resultFormat": "list",
  "columns": ["product", "city", "total_sales"],
  "intervals": ["2025-04-01T11:00:00Z/2025-04-01T12:00:00Z"]
}

 

Example 3: Limit the number of records returned.

{
  "queryType": "scan",
  "dataSource": "sales_data",
  "resultFormat": "compactedList",
  "columns": ["__time", "product", "total_sales"],
  "intervals": ["2025-04-01T10:00:00Z/2025-04-01T16:00:00Z"],
  "limit": 3
}

 

Example 4: Using resultFormat as list.

{
  "queryType": "scan",
  "dataSource": "sales_data",
  "resultFormat": "list",
  "columns": ["__time", "city", "total_sales"],
  "intervals": ["2025-04-01T13:00:00Z/2025-04-01T16:00:00Z"]
}

2. Druid GroupBy Native Queries with Filters

While scan queries in Druid return raw data, groupBy queries are used to aggregate data much like SQL GROUP BY. This is useful when you want to answer questions like:

 

·      What is the total sales per product?

·      What is the sales count by city per hour?

·      How much did each city sell after 2 PM?

 

 

Example 1: Total Sales by Product

{
  "queryType": "groupBy",
  "dataSource": "sales_data",
  "intervals": ["2025-04-01T10:00:00Z/2025-04-01T16:00:00Z"],
  "granularity": "all",
  "dimensions": ["product"],
  "aggregations": [
    { "type": "longSum", "name": "sales_by_product", "fieldName": "total_sales" }
  ]
}

 


Example 2: Sales per City after 1 PM

{
  "queryType": "groupBy",
  "dataSource": "sales_data",
  "intervals": ["2025-04-01T13:00:00Z/2025-04-01T16:00:00Z"],
  "granularity": "all",
  "dimensions": ["city"],
  "aggregations": [
    { "type": "longSum", "name": "sales_per_city", "fieldName": "total_sales" }
  ]
}

Example 3: Add a WHERE Clause (Filter by product = 'Laptop')

{
  "queryType": "groupBy",
  "dataSource": "sales_data",
  "intervals": ["2025-04-01T10:00:00Z/2025-04-01T16:00:00Z"],
  "granularity": "all",
  "filter": {
    "type": "selector",
    "dimension": "product",
    "value": "Laptop"
  },
  "dimensions": ["city"],
  "aggregations": [
    { "type": "longSum", "name": "total_sales", "fieldName": "total_sales" }
  ]
}

 




Previous                                                    Next                                                    Home

Friday, 12 September 2025

How to load data from ORC file into Druid?

What is ORC file format?

ORC stands for Optimized Row Columnar. It's a highly efficient columnar storage format used primarily in the Hadoop ecosystem, especially with Apache Hive and Apache Spark.

 

Enable ORC format in Apache Druid

ORC support is not enabled by default in Apache Druid. To enable ORC format support and load ORC files into Druid, you need to manually add the ORC extension to the common.runtime.properties file and restart the Druid instance.

 

Step-by-Step: Enable ORC Format in Apache Druid

1. Locate the common.runtime.properties file

If you're using the Druid single-server micro-quickstart, the file path is typically:

 

{DRUID_HOME}/conf/druid/single-server/micro-quickstart/_common/common.runtime.properties

 

f you're using other modes like small, nano-quickstart, large, medium, or xlarge, locate the appropriate folder under:

{DRUID_HOME}/conf/druid/single-server/

 

Then navigate into the respective _common/common.runtime.properties.

 

2. Edit the druid.extensions.loadList property

 

Find the following line:

 

druid.extensions.loadList=["druid-hdfs-storage", "druid-kafka-indexing-service", "druid-datasketches", "druid-multi-stage-query", "druid-parquet-extensions"]

 

You need to add "druid-orc-extensions" to the list like this:

 

druid.extensions.loadList=["druid-hdfs-storage", "druid-kafka-indexing-service", "druid-datasketches", "druid-multi-stage-query", "druid-parquet-extensions", "druid-orc-extensions"]

 

3. Restart your Druid instance

After saving the file, restart Druid using:

bin/start-micro-quickstart

 

This ensures Druid loads the ORC extension during startup.

 

Preparing orc file

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

Navigate to the url https://dataconverter.io/convert/csv-to-orc and convert the csv to orc file, and save it as ‘sales_data.orc’.

 

Loading orc file

Once Druid is running, go to the Druid Web Console http://localhost:8888.

 

Load data -> Batch-SQL multi-stage-query

 


Select Input type as ‘Local disk’.

 


Set the Base directory to the parent directory of orc file.

Give the file name as sales_data.orc and click on Connect data button.

 

You will be taken to Load data / Parse page.

 


Click on Next button. You will be taken to ‘Load data / Configure schema’ tab

 


Click on SQL tab.

 

Give the table name as ‘sales_data_orc’.

 


Click on ‘Start loading data’ button.

 

Upon Ingestion is successful, you will see successful message like below.

 


Navigate to Query tab by clicking on ‘Query: sales_data_orc’ button.

 

Type following sql statement, and run the query.

 

SELECT * FROM "sales_data_orc"

 


That’s it you are done…, Happy learning…

  

Previous                                                    Next                                                    Home

How to Ingest Data from an HTTPS Endpoint into Apache Druid?

Are you working with real-time or batch data that's accessible over HTTPS and wondering how to bring it into Apache Druid for fast analytics? You're in the right place! 

Apache Druid is a high-performance analytics database designed for rapid, ad-hoc queries on large datasets. While it's commonly used with Kafka, local files, or cloud storage systems like S3 or GCS, you can also pull data from an HTTPS endpoint such as a public API or your internal service and ingest it into Druid.

 

In this blog post, I’ll Walk through how to ingest data from an HTTPS source using Druid’s HTTPs input type.

 

Open the url ‘http://localhost:8888’ in browser, you will be taken Druid console.

 


Click on Load data -> Batch – SQL (multi-stage-query) button.

 


On the “Load Data / Select Input Type” page in Druid, choose HTTP(s) as your input type. This option allows you to provide one or more HTTPS URLs, separated by commas. For example, I used the following URL to ingest data into the Druid ecosystem:

 

https://raw.githubusercontent.com/MainakRepositor/Datasets/refs/heads/master/Weather%20Data/pressure.csv

 


Click on Connect data button.

 

You will be taken to ‘Load data / Parse’ page. 


 

Click on Next button.

 

You will be taken to ‘Load data / Configure schema’ page. You can observe __time column is generated from the datetime values of the dataset. 

 


Click on ‘Start loading data’ button.

 


Upon ingesting successful, navigate to Query tab and execute following sql statement.

 

SELECT * FROM "pressure"

 


That’s it, you are done….

  

Previous                                                    Next                                                    Home

Customizing Content Retrieval in RAG with EmbeddingStoreContentRetriever for Smarter Responses

Retrieval-Augmented Generation (RAG) models enhance AI's capabilities by feeding responses from external knowledge sources. However, effective RAG systems depend heavily on how documents are retrieved. In this post, I demonstrate how to customize the retrieval process using EmbeddingStoreContentRetriever by fine-tuning parameters like maxResults and minScore, and seamlessly integrating it with a chat assistant powered by a language model.

Why to customize the Retriever?

When fetching documents for a query, we may want to

 

·      Limit the number of returned results (maxResults)

·      Filter out irrelevant results using a minimum similarity score (minScore)

·      Using custom embedding models

 

This allows the system to return only the most relevant knowledge for response generation, reducing noise and improving trustworthiness.

 

Example

ContentRetriever contentRetriever =
    EmbeddingStoreContentRetriever.builder()
        .embeddingStore(embeddingStore) // Your store (e.g., in-memory or persistent)
        .embeddingModel(embeddingModel) // BGE, OpenAI, etc.
        .maxResults(5)                  // Only return top 5 similar docs
        .minScore(0.75)                 // Filter out documents below this similarity score
        .build();

ChatAssistant assistant =
    AiServices.builder(ChatAssistant.class)
        .chatModel(chatModel)          // Your LLM (OpenAI, HuggingFace, etc.)
        .contentRetriever(contentRetriever)  // Inject customized retriever
        .build();

Find the below working Application.

 

ChatAssistant.java

 

package com.sample.app.assistants;

public interface ChatAssistant {
  String chat(String userMessage);
}

InMemoryRagWithContentRetriever.java

package com.sample.app;

import com.sample.app.assistants.ChatAssistant;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.embedding.onnx.bgesmallenv15q.BgeSmallEnV15QuantizedEmbeddingModel;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import java.util.ArrayList;
import java.util.List;

public class InMemoryRagWithContentRetriever {

  public static void main(String[] args) {

    // Initialize local embedding model
    EmbeddingModel embeddingModel = new BgeSmallEnV15QuantizedEmbeddingModel();

    // Load all the Documents
    String resourcesFolderPath = "/Users/Shared/llm_docs";
    System.out.println("Resources Folder Path is " + resourcesFolderPath);
    List<Document> documents = FileSystemDocumentLoader.loadDocuments(resourcesFolderPath);

    InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
    EmbeddingStoreIngestor.ingest(documents, embeddingStore);

    OllamaChatModel chatModel =
        OllamaChatModel.builder().baseUrl("http://localhost:11434").modelName("llama3.2").build();

    ContentRetriever contentRetriever =
        EmbeddingStoreContentRetriever.builder()
            .embeddingStore(embeddingStore)
            .embeddingModel(embeddingModel)
            .maxResults(5)
            .minScore(0.75)
            .build();

    ChatAssistant assistant =
        AiServices.builder(ChatAssistant.class)
            .chatModel(chatModel)
            .contentRetriever(contentRetriever)
            .build();

    List<String> questionsToAsk = new ArrayList<>();
    questionsToAsk.add("What is the tag line of ChronoCore Industries?");

    long time1 = System.currentTimeMillis();
    for (String question : questionsToAsk) {
      String answer = assistant.chat(question);
      System.out.println("----------------------------------------------------");
      System.out.println("Q: " + question);
      System.out.println("A : " + answer);
      System.out.println("----------------------------------------------------\n");
    }
    long time2 = System.currentTimeMillis();

    System.out.println("Total time taken is " + (time2 - time1));
  }
}

Output

Resources Folder Path is /Users/Shared/llm_docs
----------------------------------------------------
Q: What is the tag line of ChronoCore Industries?
A : I couldn't find the tagline explicitly stated in the provided information. However, I can provide you with a possible tagline based on the company's mission and values:

"Preserving Yesterday. Shaping Tomorrow."

This tagline is consistent with the company's mission to "unlock the fabric of time itself — responsibly, ethically, and with profound respect for the continuum that binds reality."
----------------------------------------------------

Total time taken is 4012

  

Previous                                                    Next                                                    Home