Sunday, 3 August 2025

Using Metadata with Documents in Langchain4j

Langchain4j enables developers to associate metadata with each document, stored as key-value pairs (String keys and typed values like String, Integer, etc.). This metadata enhances document retrieval and prompt construction in powerful ways:

·      Better Prompt Construction: Include metadata like document name or source to provide the LLM with extra context.

·      Targeted Filtering: Narrow down semantic search results using metadata filters (e.g., owner, date, or document type).

·      Efficient Updates: Quickly identify and sync updated documents in your EmbeddingStore using metadata keys like “source” or “id”.

·      Whether you're building a QA bot, a document search system, or an AI assistant, using metadata ensures more context-aware and maintainable LLM applications.

 

Creating a Metadata Object

You can create a Metadata object using the following constructors:

public Metadata()
public Metadata(Map<String, ?> metadata)

Langchain4j also provides convenient static factory methods to simplify the creation.  

public static Metadata from(String key, String value)
public static Metadata from(Map<String, ?> metadata)
public static Metadata metadata(String key, String value)

These methods are useful for creating metadata with a single entry or directly from a map of values.

 

Adding Key-Value Pairs to Metadata

Yes, you can easily add new entries to an existing Metadata object using the put methods. Langchain4j supports several data types, including.

public Metadata put(String key, String value)
public Metadata put(String key, int value)
public Metadata put(String key, long value)
public Metadata put(String key, float value)
public Metadata put(String key, double value)
public Metadata put(String key, UUID value)

 

You can chain these put calls for cleaner code.

 

Adding Multiple Entries at Once

If you have a map of metadata entries, you can add all of them using the putAll method:

public Metadata putAll(Map<String, Object> metadata)

This is especially helpful when you want to merge or update metadata in bulk.

 

Find the below working application.

 

MetadataDemo.java

 

package com.sample.app.rag.apis.metadata;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.Metadata;

import java.util.UUID;
import java.util.HashMap;
import java.util.Map;

public class MetadataDemo {
	public static void main(String[] args) {

		// Step 1: Create metadata using static method
		Metadata metadata = Metadata.from("title", "Langchain4j Java API Reference").put("author", "Langchain Team")
				.put("version", 2).put("source", "https://docs.langchain4j.dev").put("id", UUID.randomUUID())
				.put("lastUpdated", "2025-06-01");

		// Step 2: Create a document with content and metadata
		String content = "This section covers the Metadata class and its usage in Langchain4j.";
		Document document = Document.from(content, metadata);

		// Step 3: Print document metadata
		System.out.println("Document Metadata:");
		document.metadata().toMap().forEach((k, v) -> System.out.println(k + " => " + v));

		// Step 4: Add additional metadata dynamically
		Map<String, Object> extraMeta = new HashMap<>();
		extraMeta.put("category", "Java SDK");

		document.metadata().putAll(extraMeta);

		// Print updated metadata
		System.out.println("\nUpdated Metadata:");
		document.metadata().toMap().forEach((k, v) -> System.out.println(k + " => " + v));
	}
}

Output

Document Metadata:
lastUpdated => 2025-06-01
source => https://docs.langchain4j.dev
id => 435df22d-0333-4e67-b29a-9ef17e443bb1
title => Langchain4j Java API Reference
version => 2
author => Langchain Team

Updated Metadata:
lastUpdated => 2025-06-01
author => Langchain Team
source => https://docs.langchain4j.dev
id => 435df22d-0333-4e67-b29a-9ef17e443bb1
title => Langchain4j Java API Reference
category => Java SDK
version => 2

 

Previous                                                    Next                                                    Home

Langchain4j: How to Use the Document API

If you're building AI apps using Langchain4j, one of the first things you’ll deal with is text—lots of it. That text can come from many sources like PDFs, Word files, websites, or plain text files.


To make it easier to handle, Langchain4j provides a handy class called Document. It lets you store the content along with useful details (called metadata) like where the text came from, when it was created, or who owns it.

 

Key methods:

·      Document.text(): Get the raw content

·      Document.metadata(): Fetch associated metadata

·      Document.toTextSegment(): Convert to a TextSegment for chunking and indexing

·      Document.from(String, Metadata), Document.document(String, Metadata) creates a Document from text and Metadata

·      Document.from(String), Document.document(String):  creates a Document from text with empty Metadata

 

Find the below working application.

 

DocumentHelloWorld.java

package com.sample.app.rag.apis.documents;

import java.util.HashMap;
import java.util.Map;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.Metadata;

public class DocumentHelloWorld {

    private static void printDocument(Document document) {
        System.out.println("Content : " + document.text());
        System.out.println("Metadata : " + document.metadata());
    }

    public static void main(String[] args) {
        Document doc1 = Document.from("Sample Document1");
        printDocument(doc1);

        Map<String, Object> doc2Metadata = new HashMap<>();
        doc2Metadata.put(Document.FILE_NAME, "langchain4j_tutorial.pdf");
        Document doc2 = Document.from("Langchain4j is easy to learn", new Metadata(doc2Metadata));
        printDocument(doc2);

    }

}

 

Output

Content : Sample Document1
Metadata : Metadata { metadata = {} }
Content : Langchain4j is easy to learn
Metadata : Metadata { metadata = {file_name=langchain4j_tutorial.pdf} }

You can even load all the Documents from the specified directory using FileSystemDocumentLoader.loadDocuments(FOLDER_PATH) method

 

DocumentsFromFolder.java

package com.sample.app.rag.apis.documents;

import java.util.List;

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

public class DocumentsFromFolder {
	public static void main(String[] args) {
		String resourcesFolderPath = "/Users/Shared/llm_docs";
		List<Document> documents = FileSystemDocumentLoader.loadDocuments(resourcesFolderPath);

		for (Document doc : documents) {
			System.out.println("------------------------------------------");
			System.out.println("File name : " + doc.text());
			System.out.println("Metadata : " + doc.metadata());
			System.out.println("------------------------------------------\n");
		}
	}

}


  

Previous                                                    Next                                                    Home

Code Formatting Control in Java: Using @formatter:off and @formatter:on

When working in Java, most developers use automatic code formatters in their IDEs like IntelliJ IDEA or Eclipse. These formatters help to keep code clean and consistent, but sometimes, they change things you didn’t want them to.

Have you ever written a nicely aligned comment, an ASCII diagram, or a table in Javadoc, only to see it get messed up by your formatter? That's where @formatter:off and @formatter:on come in.

 

These special comments let you turn off the auto-formatter temporarily, so you can keep your code or documentation exactly how you want it. Once you're done, you turn formatting back on. It’s like telling your IDE, “Hands off — I’ve got this part.”

 

In this post, we’ll learn what these formatter tags are, when and how to use them, and how they’re supported in popular tools like IntelliJ, Eclipse, and Spotless. If you’ve ever struggled with keeping your code layout, this guide is for you.

 

1. Introduction

Most developers use an automatic code formatter in their code editor or IDE (like IntelliJ IDEA or Eclipse). A code formatter is a tool that automatically cleans up your code’s layout, like adding proper indentation, fixing spacing, aligning braces, and so on.

 

This helps:

·      Make your code easier to read.

·      Keep everyone on a team writing code in a consistent style.

·      Save time by not having to format everything by hand.

 

But sometimes, the formatter can be too aggressive, meaning it changes parts of your code that you want to keep exactly as they are.

 

1.1 Common Problems That Happen

 

a. ASCII Diagrams or Visual Layouts

 

Example

public class FileProcessingPipeline {

    public void runPipeline() {

        // ┌────────────────┐
        // │  Input Source  │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Preprocessor │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Processor    │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Formatter    │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │ Output Writer  │
        // └────────────────┘

        // Steps would be called here in order
    }

   
}

After code formatting it change like below.

 


b. Tables in Javadoc

If you create a table in your Javadoc using text, the formatter might shift lines around and ruin the alignment:

/**
 * User Information Table:
 *
 * +------------+-----+-------------+----------------------+------------------+
 * | Name       | Age | Occupation  | Email                | Registered Date  |
 * +------------+-----+-------------+----------------------+------------------+
 * | Alice      | 28  | Engineer    | alice@example.com    | 2021-03-15       |
 * | Bob        | 35  | Designer    | bob.design@example.com | 2020-11-30     |
 * | Charlie    | 22  | Student     | charlie@univ.edu     | 2023-01-05       |
 * | Diana      | 41  | Manager     | diana@corp.com       | 2019-07-19       |
 * +------------+-----+-------------+----------------------+------------------+
 *
 * <p>
 * Columns:
 * <ul>
 * <li><b>Name</b> - Full name of the user</li>
 * <li><b>Age</b> - Current age</li>
 * <li><b>Occupation</b> - Current profession</li>
 * <li><b>Email</b> - Contact email address</li>
 * <li><b>Registered Date</b> - Date the user registered in the system</li>
 * </ul>
 */

After formatting it change like below.

 


c. Legacy Code

Sometimes you’re working with old code written in a very specific format. Changing it could cause bugs or confusion. A formatter might reformat it without understanding why it was written that way.

 

d. Aligned Comments

You might write comments like this

    int count    = 10;  // number of items
    int maxLimit = 100; // maximum allowed

A formatter might remove the spacing before the comments, making them harder to read in a block.


While formatters try to make your code clean and consistent, they don’t always understand the meaning or importance of certain formatting. This can be frustrating when you’ve spent time making something readable, only for the formatter to undo your work.

 

2. The Hidden Gems: @formatter:off and @formatter:on

@formatter:off and @formatter:on are special comments (not actual Java code or annotations) that tell your IDE or code formatter to stop and start formatting automatically.

 

They are not part of the Java language itself, they are just instructions to the code formatting tool, like saying:

 

“Hey formatter, don’t touch the next few lines.”

“Okay formatter, you can start again now.”

 

This is very helpful when you want to keep specific formatting exactly as you typed it, and prevent the formatter from changing it.

 

Even though they look like annotations (@something), they are not Java annotations. Instead, they are just inline comments that some IDEs recognize.

 

Example

 

// @formatter:off

 

Which tools support these instructions?

These formatter tags are recognized by:

·      Eclipse (out of the box)

·      IntelliJ IDEA (you need to enable it)

·      Spotless (depends on the formatter engine you use, Google Java Format ignores it, but Eclipse formatters might support it)

 

Here’s a simple code snippet showing how to use them:

// @formatter:off
int valueA    = 10;  // aligned comment
int valueLong = 20;  // aligned comment
int shortV    = 30;  // aligned comment
// @formatter:on

Without @formatter:off, your formatter might collapse everything like this:

int valueA = 10; // aligned comment
int valueLong = 20; // aligned comment
int shortV = 30; // aligned comment

 

3. Best Practices for Using @formatter:off and @formatter:on

Using @formatter:off and @formatter:on can be very helpful, but like any powerful tool, it's important to use it carefully and responsibly. Here are some best practices to follow.

 

3.1 Don’t Overuse It

Just because you can turn off the formatter doesn't mean you should do it everywhere. Auto-formatting helps keep your code:

 

·      Clean

·      Consistent

·      Easy to read, especially in large teams

 

If you turn off formatting too often, your code might start looking messy or inconsistent, which defeats the purpose of using a formatter in the first place.

 

3.2. Use It Only When You Really Need To

Use @formatter:off only around specific blocks where you absolutely need to preserve the exact layout, such as:

 

·      Javadoc tables

·      ASCII diagrams

·      Aligned comments

·      Legacy code where formatting affects logic or readability.

 

Example

// @formatter:off
/**
 * +----------+--------------+
 * | Name       | Role       |
 * +------------+------------+
 * | Ram        | Developer  |
 * | Krishna    | Designer   |
 */
// @formatter:on

 

3.3 Leave a Comment Explaining Why

If you turn off formatting for a section, it's a good habit to leave a short comment explaining why. This helps other developers (or future you!) understand the reason.

 

Example

// @formatter:off
// Table format must be preserved for documentation readability
/**
 * +----------+------------+
 * | Column A | Column B   |
 * +----------+------------+
 */
// @formatter:on

 

4. Final Thoughts

4.1 When Should You Use @formatter:off?

Use this feature only when auto-formatting makes your code harder to read, and you have a good reason to keep your own formatting.

 

Examples include:

·      Tables or diagrams in Javadoc

·      Aligned comments for better visual structure

·      Preserving formatting in legacy code or custom layouts

 

You shouldn't use it just because you don't like the formatter's style, formatters help teams write consistent code. But when readability truly depends on your layout, that’s the right time to reach for @formatter:off.

 

4.2 Your Code, Your Way - Without Fighting the Formatter

Instead of turning off formatting for your entire file or disabling your formatter altogether, @formatter:off and @formatter:on let you:

 

·      Keep control where it matters

·      Let the formatter work everywhere else

 

This means your code stays mostly clean and consistent, but also preserves your intent in areas that require special formatting.

 

In summary, think of @formatter:off as a temporary "pause" button for formatting, use it only when needed, and your code will be both clean and human-friendly.

 

  

You may like

Miscellaneous

Programmatically import certificate to cacerts file in Java

Command to check CPU temperature in Mac

Quick guide to Java DecimalFormat class

Compress and decompress a string in Java

Discover and load the implementations of a service using ServiceLoader in Java