DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a Retrieval-Augmented Generation (RAG) System in Java With Spring AI, Vertex AI, and BigQuery
  • Building a Simple RAG Application With Java and Quarkus
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
  • Why Your RAG Pipeline, Not Your LLM, Is Causing Hallucinations

Trending

  • Deploying Small Language Models on Sovereign Cloud
  • Java Virtual Threads Under Load: Three Production Limits
  • Using Middleware in LangChain: Recovering From Tool Failures
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Beyond Semantic Similarity: Designing Two-Stage RAG With Java

Beyond Semantic Similarity: Designing Two-Stage RAG With Java

Learn how to use LangChain4j and Eclipse JNoSQL to resolve vector matches into Java entities and validate context before generation.

By 
Otavio Santana
DZone Core CORE ·
Nov. 26, 26 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
91 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Context is critical to sound decision-making, as software architecture shows. An elegantly implemented design pattern can become an anti-pattern if used inappropriately. Its effectiveness depends on both its function and the surrounding assumptions and constraints. AI systems face a similar issue: a technically correct answer may still be unsuitable for a specific customer, time frame, product, or business process.

Enterprise information is seldom timeless or universally relevant. Policies evolve, contracts have effective dates, customers hold different permissions, and similar scenarios may require different rules. Without recognizing these distinctions, an AI assistant may provide a convincing response based on accurate data but still reach an inappropriate conclusion. The challenge is not only to expand a language model’s knowledge, but to ensure it accesses the right information for each situation. This need drives the shift from direct generation to retrieval-augmented generation (RAG), and ultimately to a second retrieval stage.

From Direct Generation to Retrieval-Augmented Generation

In the simplest LLM interaction, an application submits a question and receives a response. The model relies on the prompt and its training data; it does not automatically access current company databases or business policies. While direct generation is useful for general explanations or text transformation, it is insufficient for decisions that require organization-specific facts.

User question -> LLM -> answer

This is sometimes referred to informally as a simple AI workflow. However, it should not be confused with a Directed Acyclic Graph (DAG). A DAG represents dependencies between processing steps and does not specifically denote direct generation. Both direct-generation and more complex retrieval pipelines can be represented as DAGs.

RAG modifies the workflow by retrieving external knowledge before generating a response. During ingestion, the system prepares documents or business records. At runtime, a retriever selects information relevant to the question and adds it to the prompt context, a process known as context augmentation or context injection. This lets the model consider facts not in its training data without retraining.

RAG

A typical RAG implementation uses embeddings, which are numerical vectors from an embedding model that capture text meaning. Similarity search retrieves related passages even if their wording differs. For example, a financial question using denied may retrieve a policy about refused transactions. While this aids discovery, semantic similarity does not indicate policy authority or business applicability. The closest passage may be outdated, from a different product, or inadequate to answer the question.

This limitation does not mean standard RAG is inherently inaccurate. RAG pipelines can incorporate metadata filtering, access checks, and application logic. However, architects must determine where these responsibilities should reside. If a search result is accepted as final evidence without validating its business context, relevance may be mistaken for correctness. This distinction informs the next design.

Introducing a Second Retrieval Stage

The approach is straightforward: divide retrieval into two stages. The first stage uses semantic similarity to identify candidate knowledge. The second stage maps these candidates to authoritative business entities and applies domain rules before providing information to the LLM. Rather than relying solely on a textual search result, the application verifies whether the associated enterprise object is valid for the request.

Second retrieval stage

Here, two-stage retrieval refers to semantic discovery, followed by entity retrieval and business validation. In information-retrieval literature, this phrase often means initial retrieval followed by reranking. Our approach is similar but not identical. This distinction is important because retrieving an entity again does not improve results on its own. The second stage adds value when it enforces meaningful rules, expands relationships, or checks authoritative state missing from the vector result.

This approach also shifts the architecture's ownership boundaries. Search engines find likely matches, domain entities and application services enforce business constraints, and LLMs generate explanations or recommendations from the provided evidence. Assigning these decisions to separate components makes them easier to test and evolve. However, why should an enterprise system accept additional lookups and complexity? A versioned financial policy offers a clear answer.

A Business Scenario: The Right Policy at the Right Time

Consider a financial institution developing an internal AI assistant for support staff. Employees inquire about unauthorized card transactions, fraud investigations, and identity-verification procedures. The knowledge base retains historical policy revisions because past transactions may need to be evaluated under the rules in effect at the time, not under current rules.

Suppose the institution's fictional card-dispute policy initially allows customers to report unauthorized transactions within 30 days. On July 1, 2026, a revised policy extends this window to 60 days. Both documents address the same type of dispute and may appear equally relevant to an employee's question. 

However, a 45-day report may require a different response depending on the applicable business date. Retrieving the most similar revision without verifying its effective period risks applying the wrong rule.In this scenario, each revision has a unique UUID, while a stable business code identifies the policy across revisions. An inclusive effectiveFrom and exclusive effectiveUntil define when a revision applies. The application provides a trusted LocalDate representing the relevant business event. This is intentional: determining whether the transaction date, report date, or another date governs a policy is a domain requirement, not something the LLM can infer from free text.

The workflow consists of two operational processes. Ingestion creates embeddings and stores policies with their attributes. Retrieval embeds the employee's question, searches for candidate IDs, loads the corresponding policy entities, and checks their effective dates. It includes only valid policies in the context provided to the language model. In our demonstration, the vector and policy data share a single Qdrant collection. The two stages represent distinct responsibilities, not separate databases.

Two-stage retrieval

This scenario translates the abstract concern of "better context" into a testable requirement: for the same question type, changing the trusted business date should select a different revision, while an unrelated question should not create a new policy. With this clear decision boundary, we can implement the solution using standard Java domain modeling and persistence APIs.

Building the Java Domain Model and Knowledge Store

We use Java SE, CDI with Weld, MicroProfile Config, LangChain4j, Eclipse JNoSQL 1.2.0, and Qdrant. A Jakarta EE runtime provides platform capabilities, reducing dependencies. The full project includes Maven configuration, local Qdrant setup, and provider settings. Here, we focus on the architecture-relevant components.

Eclipse JNoSQL supports multiple NoSQL data models — including document, key-value, wide-column, graph, time-series, and vector — and builds on Jakarta-oriented programming conventions. The broader Jakarta ecosystem offers complementary abstractions, notably Jakarta Data repositories. This particular example deliberately uses Jakarta NoSQL mapping and the JNoSQL VectorTemplate, so we can focus on a single domain entity and avoid presenting unrelated APIs as prerequisites.

Eclipse JNoSQL implements Jakarta NoSQL's entity-oriented programming model. Its annotations are familiar to developers who have used Jakarta Persistence: @Entity names the collection, @Id identifies a record, and @Column maps its attributes. We define Policy as a Java record to ensure each revision remains immutable as a business fact. The entity also stores a vector representation and specifies its own applicability rule:

Java
 
@Entity("policies")

public record Policy(

        @Id UUID id,

        @Column String policyCode,

        @Column String title,

        @Column String content,

        @Column String department,

        @Column String version,

        @Column LocalDate effectiveFrom,

        @Column @Convert(OpenEndedDateConverter.class)

        LocalDate effectiveUntil,

        @Column Vector embedding) {

 

    public boolean appliesOn(LocalDate date) {

        return !date.isBefore(effectiveFrom)

                && (effectiveUntil == null

                    || date.isBefore(effectiveUntil));

    }

    // Constructor validation and storage adapter omitted.

}


The rule is intentionally simple: verify that the date is not before effectiveFrom and, unless the period is open-ended, ensure it is before effectiveUntil. Ownership is more important than complexity; a Java domain method determines policy applicability, not the LLM. The record’s implementation also validates dates. It uses OpenEndedDateConverter and a storage adapter to address a null-payload interoperability issue in the Qdrant/JNoSQL/LangChain4j integration. Further details are available in the source.

For ingestion, sample definitions are loaded from a JSON resource. In production, the same data may come through a REST endpoint, publishing workflow, or event stream. While the ingestion method may vary, the architectural contract stays the same: produce the embedding, associate it with a business entity, and persist a stable revision. The essential part is:

Java
 
if (template.find(Policy.class, definition.id()).isEmpty()) {
    var embedding = embeddingModel.embed(
            definition.title() + "\n" + definition.content()
    ).content();

 

    var policy = definition.toPolicy(DenseVector.of(embedding.vector()));
    template.insert(policy.forStorage());

}


LangChain4j provides the EmbeddingModel, while VectorTemplate is part of Eclipse JNoSQL. This application uses the local AllMiniLmL6V2 embedding model to generate 384-dimensional vectors and stores both structured policy attributes and vectors using a unified persistence layer. The demonstration omits revisions if the UUID already exists, preventing unintended changes to historical examples. In production, updating knowledge should include a defined revision and lifecycle strategy instead of overwriting policies without review.

While it may be tempting to embed all available attributes, doing so would blur responsibilities. We embed only the title and content for discovery, while retaining effective dates and version as typed fields for validation. Embeddings capture semantic relationships but don't replace exact dates, identity, or permissions. After establishing this separation in storage, the next consideration is how to maintain it during retrieval.

Implementing the Two Retrieval Stages

LangChain4j's ContentRetriever interface defines the integration point between retrieval and the AI service. Instead of allowing a generic retriever to return arbitrary matching text, our PolicyRetriever determines which candidate policies are included as context. CDI injects EmbeddingModel, EmbeddingStore<TextSegment>, and Eclipse JNoSQL's VectorTemplate. Both the embedding store and JNoSQL reference the same Qdrant collection, and both use the same embedding model for ingestion and querying to ensure vector compatibility.

In the first stage, we embed the user's question and use it to search Qdrant. We retain only the matching IDs, not the payload text, as these IDs link to the corresponding enterprise entities:

Java
 
private List<UUID> semanticCandidates(Query query) {

    var embedding = embeddingModel.embed(query.text()).content();
    var request = EmbeddingSearchRequest.builder()
            .queryEmbedding(embedding)
            .maxResults(maxResults)
            .build();
 

    return embeddingStore.search(request).matches().stream()
            .map(EmbeddingMatch::embeddingId)
            .map(UUID::fromString)
            .toList();

}


This is candidate discovery. A returned UUID means the vector is close enough for the search engine to consider it; it does not certify that the associated policy is currently effective or applies to the question. The order of candidates represents semantic relevance, not a ranking of legal authority or organizational precedence.

The second stage crosses the architectural boundary. For each candidate ID, Eclipse JNoSQL retrieves the mapped Policy. The pipeline removes missing records, invokes the temporal rule, and converts only applicable entities to LangChain4j content:

Java
 
@Override

public List<Content> retrieve(Query query) {

    LocalDate businessDate = businessDate(query);

    return semanticCandidates(query).stream()
            .map(id -> template.find(Policy.class, id))
            .flatMap(Optional::stream)
            .filter(policy -> policy.appliesOn(businessDate))
            .map(PolicyRetriever::toContent)
            .toList();
}


A few lines reflect key architectural decisions. template.find() restores the Java business entity. appliesOn() enforces a deterministic domain invariant. toContent() compiles the policy's title, version, effective period, department, and text for the LLM. This conversion is more than formatting; it marks the point where selected domain knowledge becomes model context. Excluded revisions do not cross this boundary.

The date is provided by InvocationParameters as a LocalDate from the calling application. This approach avoids parsing dates from generated text and creates a clear testing seam: for the same question, changing the business date should make a different revision eligible. In other industries, the second stage may validate tenant ownership, region, consent, product eligibility, confidentiality, or state transitions. The core principle remains: business rules must operate on authoritative typed data before answer generation.

This separation also introduces a limitation. Stage two cannot recover a policy that stage one did not return. A low maxResults value may exclude the relevant revision, especially when many historical versions are similar. Increasing maxResults without consideration raises cost and noise. Production designs should measure candidate recall, use metadata prefilters or oversampling as needed, and determine whether to hydrate records individually or in batches. Domain validation improves candidate selection but does not ensure completeness.

Once the retrieval contract is established, LLM integration serves as a thin layer rather than embedding business validation within prompt text.

Keeping the AI Service Thin

The LangChain4j CDI extension implements the annotated PolicyAssistant interface and links it to the specified retriever. The assistant receives a question and typed invocation parameters, then returns a structured PolicyResponse with an answer, recommendations, and a requiresHumanReview flag. The following excerpt illustrates the contract:

Java
 
@RegisterAIService(

        scope = ApplicationScoped.class,
        contentRetrieverName = "policyRetriever")

public interface PolicyAssistant {

 
    @SystemMessage("""
        Answer using only the retrieved policies.
        Never invent policies, procedures, or deadlines.
        If evidence is insufficient, require human review.
        """)

    @UserMessage("{{question}}")
    PolicyResponse analyze(@V("question") String question,
                           InvocationParameters parameters);

}


The actual project uses more detailed guidance, including an important warning: similarity is not evidence. Such instructions can help the LLM handle ambiguity, but they are not equivalent to an application-enforced rule. We should not claim that prompting prevents hallucinations or that a structured JSON response proves business correctness. The most defensible boundary remains the domain check performed before assembling the context.

Invoking the service is ordinary Java code. The application passes the relevant date with the question; LangChain4j uses it when executing our ContentRetriever:

Java
 
var parameters = InvocationParameters.from(
        PolicyRetriever.BUSINESS_DATE,
        LocalDate.of(2026, 5, 15));

 

PolicyResponse response = assistant.analyze(
        "A customer reported an unauthorized card "
        + "transaction after 20 days in May 2026. "
        + "What should support do?",
        parameters);


In the demonstration, a May 2026 case selects the historical 30-day revision and excludes the later 60-day one. An August 2026 question about a report after 45 days selects the newer revision. A third question asks how to reverse an international wire transfer. Since the available card-dispute and fraud policies do not define this procedure, the assistant reports insufficient knowledge and requests human review rather than inventing a deadline. These are fictional sample policies and illustrative outcomes, not financial advice.

The third scenario is particularly instructive for architects. Even after temporal filtering, a semantically related policy may not answer the question. The retrieval layer can determine whether an entity is eligible under known rules, but assessing whether it provides sufficient evidence is a separate issue. High-stakes applications may require explicit evidence checks, authorization, human oversight, and audit records, along with a carefully designed system prompt. These trade-offs determine whether the design fits a production architecture.

Architectural Trade-offs and Production Boundaries

The main reason to adopt this design is not that two database calls are more sophisticated than one. Rather, enterprise applications often have trusted domain models, lifecycle rules, and persistence contracts. Reusing these rules makes them testable and keeps the retrieval system aligned with the rest of the software. This pattern is valuable when knowledge is versioned, permissioned, regulated, or linked to other business entities. For small, static document collections, standard RAG and metadata filtering may be sufficient.

An evaluation plan should address both stages, not just the final LLM answer. For stage one, create questions with known expected policy identifiers and applicable revisions, then check if the relevant IDs appear in the candidate set. For stage two, explicitly test effective-period boundaries, including when an old revision expires and a new one begins. For the AI service, evaluate unsupported and ambiguous questions, as well as answers that require human review. Without these independent checks, a plausible generated answer may hide a retrieval or validation defect.

There are real costs. Resolving candidates can require additional database requests and increase latency. If authorization is checked only after vector discovery, the design must still prevent sensitive data from leaking through retrieval metadata, logs, or generated context. Concurrent policy changes can create consistency concerns between vector indexes and authoritative records. Observable systems should record which revision IDs were selected or rejected, which rules ran, and what evidence reached the model, while avoiding indiscriminate logging of sensitive customer data.


It is also important not to overclaim uniqueness. Conventional RAG systems can support metadata filters, effective dates, and domain validation; JNoSQL is not the only route to this architecture. Nor does “two-stage retrieval” inherently improve factual accuracy. It introduces a defined place to enforce business applicability and to expand context through entity relationships. Retrieval evaluations, scenario tests, and production measurements must establish whether that improves outcomes.

In our Java implementation, the main benefit is the clear division of responsibilities: LangChain4j handles AI integration and semantic discovery, Eclipse JNoSQL maps and retrieves business entities, Qdrant stores their vectors and attributes, and Java domain methods determine applicability. The generative model receives a narrower, better-governed evidence set. This is primarily a software design choice, with AI integration as a secondary consideration.

Conclusion

RAG enables an LLM to access knowledge beyond its training data, but the closest document is not always the right one for a decision. By resolving semantic candidates into typed Java entities and applying business rules before generation, two-stage retrieval places context validation where enterprise engineers can test, evolve, and audit it. Our financial-policy example demonstrates the difference between retrieving a relevant revision and selecting one that actually applies.

This pattern involves extra lookups, candidate-recall challenges, and governance responsibilities. These costs are justified when business meaning cannot safely be left to vector similarity or prompts alone. The broader lesson, familiar from software architecture, is to let each component own the decisions it is equipped to make and provide the LLM only the evidence it is meant to interpret.

References and Source Code

  • Complete runnable Java example 
  • Eclipse JNoSQL
  • Jakarta NoSQL
  • Jakarta Data
  • LangChain4j documentation
  • Qdrant documentation
Java (programming language) RAG

Opinions expressed by DZone contributors are their own.

Related

  • Building a Retrieval-Augmented Generation (RAG) System in Java With Spring AI, Vertex AI, and BigQuery
  • Building a Simple RAG Application With Java and Quarkus
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
  • Why Your RAG Pipeline, Not Your LLM, Is Causing Hallucinations

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook