Build a Smart Elasticsearch Agent with LangGraph and Google Gemini

Build a smart Elasticsearch agent with LangGraph and Google Gemini. Convert natural language queries into DSL for AI-powered search, automation, and data insights.

Build a smart Elasticsearch agent with LangGraph and Google Gemini

How do you allow users to search Elasticsearch data using natural language?

Glass skyscrapers lit at dusk in a city skyline under a cloudy sky

Build an agent that interprets user intent and generates precise Elasticsearch queries. This guide outlines a smart Elasticsearch agent using LangGraph for orchestration and Google Gemini for natural language understanding and query generation. The agent translates natural language into DSL queries, enabling broader access to data and analytics.

The system uses two core technologies. LangGraph provides the orchestration framework. It defines the multi-step workflow for flexibility and scalability. Google Gemini, a large language model (LLM), handles natural language understanding and generates Elasticsearch DSL. This combination creates an efficient, user-friendly search interface.

A smart Elasticsearch agent is a LangGraph workflow that uses Google Gemini to turn a natural language query into Elasticsearch DSL, runs the DSL on the Elasticsearch cluster and summarizes the results.

.

Purpose of an Elasticsearch Agent

Elasticsearch provides high performance, but its Query DSL is complex. An agent allows users to input queries in natural language. It returns accurate results without requiring users to learn the syntax. This abstraction replaces manual DSL construction with natural conversation. It lowers the barrier to entry for non-technical users.

LangGraph: Core Orchestration Layer for the Elasticsearch Agent

LangGraph orchestration layer for the Elasticsearch agent

LangGraph uses a graph-based architecture. Each node represents a specific task, such as a database query or LLM call. Edges define the flow of data and context between nodes. This structure supports complex workflow construction. It enables parallel execution. It supports conditional branching. It allows rejoining of paths based on predefined logic. The entire workflow remains visible within a single graph.

LangChain integrates large language models (LLMs) into workflows. It excels at sequential tasks, or prompt chaining, and connects to external data sources. LangGraph builds on LangChain. It supports complex, agent-based workflows with high task dependency. LangGraph manages state and control for dynamic, multi-agent interactions. It does not replace LangChain. It extends LangChain. LangGraph requires LangChain to operate.

LangGraph uses a stateful, graph-based architecture. It moves agent development beyond sequential processing. The system handles adaptive, resilient, and collaborative decisions. It defines complex paths and manages internal state. It supports cyclical behavior, such as reflection. The Elasticsearch Agent adjusts strategies based on intermediate results or failures. If DSL generation fails, the system re-evaluates, retries, or branches. This design handles unexpected inputs and system states. LangGraph supports multi-agent systems. It assigns specialized roles to agents. Examples include query normalization, DSL generation, and summarization. Shared state allows agents to pass context. This modularity enables efficient collaboration. This architecture builds sophisticated AI copilots. It replaces single monolithic LLM calls with distributed, intelligent systems.

Gemini Powers Natural Language Understanding and Elasticsearch DSL Generation

Gemini generating Elasticsearch DSL from a natural language query

Google Gemini interprets natural language queries. It translates them into structured, executable formats. Specifically, it generates Elasticsearch DSL. This mirrors Gemini in BigQuery. That tool generates SQL from natural language prompts. It also refines and summarizes queries. This parallels the need for an Elasticsearch Agent to generate accurate DSL.

The Gemini API defaults to unstructured text. You can configure it for structured output, such as JSON. This is critical because Elasticsearch DSL is JSON. Two methods achieve this:

Defining a responseSchema ensures output adheres to a specific structure. This reduces post-processing. It enables direct data extraction. This setup reliably parses generated DSL and summaries. Supported MIME types include application/json and text/x.enum. These types control the output format.

Gemini produces constrained, structured output. Precise prompt engineering transforms the LLM from a general text generator into a reliable component. Defining a response schema enforces JSON output with specific keys. This makes Gemini a predictable element in the agent workflow. Reliable automation requires consistent valid JSON. The pipeline fails if the DSL generation step produces invalid output. Structured output allows the Elasticsearch client to parse data. This reduces the need for fragile post-processing. Schemas and precise prompts reduce invalid DSL or irrelevant structures. This increases trust in the agent output. The design suits production environments that require consistency and accuracy.

Prompt engineering guides LLM responses for specific tasks. It shapes output through structured input instructions. For the Elasticsearch Agent, prompts act as a blueprint. They define how Gemini normalizes queries, generates DSL, and summarizes results. Advanced techniques improve DSL accuracy. One method adds the language grammar to the prompt. It uses Extended Backus-Naur Form (EBNF). This clarifies the expected syntax for the model.

Agent Workflow Overview

The agent operates in defined steps. LangGraph defines the workflow. This structure supports future modification and extension.

  1. User Input: The user provides a natural language query. Example: "Show me recent error logs related to authentication."
  2. Query Normalization. System corrects spelling and removes redundant terms to prepare input for translation.
  3. DSL Generation. System sends normalized query to Gemini. Gemini converts input to valid Elasticsearch DSL.
  4. Elasticsearch Search. System executes generated DSL query on the Elasticsearch cluster.
  5. Response Summarization. System converts raw results into a concise, readable format.
  6. Final Output. System presents summarized results to the user.

How agents drive enterprise value

Implementation Steps

Build the agent using these steps:

Prerequisites

BASH
01pip install langchain langgraph google-generativeai python-dotenv requests

2. Project Setup:

  1. Create a Project Directory: Create a new directory for the agent project (e.g., es_agent).

Create a .env file in your project directory. This file stores your sensitive credentials: the API key and Elasticsearch URL. Add the following lines, replacing placeholders with your actual values:

.ENV
01GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
02ES_URL="YOUR_ELASTICSEARCH_URL" # e.g., "https://localhost:9200/_search"
  1. Create three text files in your project directory. These files hold LLM prompts for the graph states: - query_normalizer_prompt.txt - es_dsl_formation_prompt.txt - generic_es_response_summariser.txt

3. Core Code (es_agent.py)

Create es_agent.py in your project directory. This file contains the agent's main code.

ES_AGENT.PY
01import os
02import json
03import requests
04import logging
05from dotenv import load_dotenv
06import google.generativeai as genai
07from langgraph.graph import StateGraph, END
08from langchain_core.runnables import RunnableLambda
09
10# ─── Logging Configuration ─────────────────────────────────────────────────────
11logging.basicConfig(
12 level=logging.INFO,
13 format="%(asctime)s %(levelname)s %(name)s ─ %(message)s",
14 datefmt="%Y-%m-%d %H:%M:%S"
15)
16logger = logging.getLogger(__name__)
17load_dotenv()
18
19# ─── Load environment variables ─────────────────────────────────────────────────
20GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
21ES_ENDPOINT = os.getenv("ES_URL")
22
23
24# ─── Load prompt files ───────────────────────────────────────────────────────────
25def load_prompt(filename):
26 base_dir = os.path.dirname(os.path.abspath(__file__))
27 full_path = os.path.join(base_dir, filename)
28 try:
29 with open(full_path, "r") as f:
30 text = f.read()
31 logger.info(f"Loaded prompt from '{full_path}' ({len(text)} bytes).")
32 return text
33 except Exception as e:
34 logger.error(f"Error loading prompt file '{full_path}': {e}")
35 return ""
36
37
38NORMALIZER_PROMPT = load_prompt("query_normalizer_prompt.txt")
39DSL_PROMPT = load_prompt("es_dsl_formation_prompt.txt")
40SUMMARY_PROMPT = load_prompt("generic_es_response_summariser.txt")
41
42# ─── Configure Gemini ────────────────────────────────────────────────────────────
43if not GEMINI_API_KEY:
44 logger.warning("GEMINI_API_KEY is not set in environment; model calls will fail.")
45genai.configure(api_key=GEMINI_API_KEY)
46model = genai.GenerativeModel("gemini-2.0-flash")
47
48
49# ─── Shared utility ─────────────────────────────────────────────────────────────
50def strip_fences(text: str) -> str:
51 """
52 Remove markdown json fences (```json ... ```).
53 """
54 original = text
55 text = text.strip()
56 if text.startswith("```json"):
57 text = text[7:]
58 if text.endswith("```"):
59 text = text[:-3]
60 stripped = text.strip()
61 if original != stripped:
62 logger.debug("Stripped markdown fences from Gemini output.")
63 return stripped
64
65
66# ─── Step 1: Normalize Query ─────────────────────────────────────────────────────
67def normalize_query(state: dict) -> dict:
68 nl_query = state.get("query", "")
69 logger.info(f"[NormalizeQuery] Received query: '{nl_query}'")
70 try:
71 prompt = NORMALIZER_PROMPT.format(user_query=nl_query)
72 logger.debug(f"[NormalizeQuery] Prompt sent to Gemini (length {len(prompt)}).")
73 response = model.generate_content(prompt)
74 normalized = strip_fences(response.text)
75 logger.info(f"[NormalizeQuery] Normalized query: '{normalized}'")
76 return {**state, "normalized_query": normalized}
77 except Exception as e:
78 logger.error(f"[NormalizeQuery] Error during normalization: {e}")
79 return {**state, "error": f"Normalization failed: {e}"}
80
81
82# ─── Step 2: NL to DSL ────────────────────────────────────────────────────────────
83def generate_es_dsl(state: dict) -> dict:
84 normalized = state.get("normalized_query", "")
85 logger.info(f"[GenerateDSL] Converting normalized query to DSL: '{normalized}'")
86 try:
87 prompt = DSL_PROMPT.format(nl_query=normalized)
88 logger.debug(f"[GenerateDSL] Prompt sent to Gemini (length {len(prompt)}).")
89 response = model.generate_content(prompt)
90 dsl_string = strip_fences(response.text)
91 logger.debug(f"[GenerateDSL] Gemini returned DSL string: {dsl_string[:100]}{'...' if len(dsl_string) > 100 else ''}")
92 dsl = json.loads(dsl_string)
93 logger.info("[GenerateDSL] Parsed DSL JSON successfully.")
94 logger.info(dsl_string)
95 return {**state, "es_dsl": dsl}
96 except json.JSONDecodeError as e:
97 logger.error(f"[GenerateDSL] JSON parsing error: {e}. Raw DSL: {dsl_string}")
98 return {**state, "error": f"Failed to parse DSL JSON: {e}"}
99 except Exception as e:
100 logger.error(f"[GenerateDSL] Unexpected error: {e}")
101 return {**state, "error": f"DSL generation failed: {e}"}
102
103
104# ─── Step 3: Search Elasticsearch ────────────────────────────────────────────────
105def search_elasticsearch(state: dict) -> dict:
106 es_dsl = state.get("es_dsl")
107 if not es_dsl:
108 logger.warning("[QueryES] No DSL found in state; skipping Elasticsearch call.")
109 return {**state, "error": "No DSL to execute."}
110 logger.info(f"[QueryES] Sending DSL to Elasticsearch endpoint: {ES_ENDPOINT}")
111 truncated_payload = json.dumps(es_dsl)[:100] + ("..." if len(json.dumps(es_dsl)) > 100 else "")
112 logger.debug(f"[QueryES] DSL payload (truncated): {truncated_payload}")
113 try:
114 res = requests.post(
115 ES_ENDPOINT,
116 json=es_dsl,
117 headers={"Content-Type": "application/json"},
118 verify=False
119 )
120 res.raise_for_status()
121 es_response = res.json()
122 hits = es_response.get("hits", {}).get("total", {}).get("value", "unknown")
123 logger.info(f"[QueryES] Elasticsearch returned {hits} hits.")
124 return {**state, "es_raw_response": es_response}
125 except requests.exceptions.RequestException as e:
126 logger.error(f"[QueryES] HTTP error: {e}")
127 return {**state, "error": f"Elasticsearch HTTP error: {e}"}
128 except json.JSONDecodeError as e:
129 logger.error(f"[QueryES] JSON decode error on ES response: {e}")
130 return {**state, "error": f"ES response JSON decode failed: {e}"}
131 except Exception as e:
132 logger.error(f"[QueryES] Unexpected error: {e}")
133 return {**state, "error": f"Elasticsearch search failed: {e}"}
134
135
136# ─── Step 4: Summarize ────────────────────────────────────────────────────────────
137def summarize_response(state: dict) -> dict:
138 if "es_raw_response" not in state:
139 logger.warning("[Summarize] No ES response found; skipping summarization.")
140 return state
141 raw = state["es_raw_response"]
142 logger.info("[Summarize] Summarizing Elasticsearch response with Gemini.")
143 try:
144 prompt = SUMMARY_PROMPT.format(
145 es_response=json.dumps(raw),
146 nl_query=state.get("query", "")
147 )
148 logger.debug(f"[Summarize] Prompt sent to Gemini (length {len(prompt)}).")
149 response = model.generate_content(prompt)
150 summary_text = strip_fences(response.text)
151 logger.debug(f"[Summarize] Raw summary text (truncated): {summary_text[:100]}{'...' if len(summary_text) > 100 else ''}")
152 try:
153 summary_json = json.loads(summary_text)
154 logger.info("[Summarize] Parsed summary JSON successfully.")
155 return {**state, "summary": summary_json}
156 except json.JSONDecodeError:
157 logger.warning("[Summarize] Summary is not valid JSON; returning raw string.")
158 return {**state, "summary": summary_text}
159 except Exception as e:
160 logger.error(f"[Summarize] Error during summarization: {e}")
161 return {**state, "error": f"Summarization failed: {e}"}
162
163
164# ─── Step 5: Final Output ────────────────────────────────────────────────────────
165def output_result(state: dict) -> dict:
166 logger.info("[Output] Generating final output.")
167 return {**state, "output": json.dumps(state.get("summary", state.get("error")), indent=2)}
168
169
170# ─── Build the graph (use plain dict as the state type) ──────────────────────────
171graph = StateGraph(dict)
172graph.add_node("NormalizeQuery", RunnableLambda(normalize_query))
173graph.add_node("GenerateDSL", RunnableLambda(generate_es_dsl))
174graph.add_node("QueryES", RunnableLambda(search_elasticsearch))
175graph.add_node("Summarize", RunnableLambda(summarize_response))
176graph.add_node("Output", RunnableLambda(output_result))
177
178# Define edges
179graph.set_entry_point("NormalizeQuery")
180graph.add_edge("NormalizeQuery", "GenerateDSL")
181graph.add_edge("GenerateDSL", "QueryES")
182graph.add_edge("QueryES", "Summarize")
183graph.add_edge("Summarize", "Output")
184graph.add_edge("Output", END)
185
186# ─── Compile the graph ───────────────────────────────────────────────────────────
187graph_executor = graph.compile()
188
189
190# ─── Expose a helper function to run the agent ───────────────────────────────────
191def es_search_agent(nl_query: str):
192 """
193 Invoke the LangGraph agent with a natural-language query string.
194 """
195 logger.info(f"[run_query] Invoking agent with query: '{nl_query}'")
196 result_state = graph_executor.invoke({"query": nl_query})
197 return json.loads(result_state["output"])

4. Define Prompts

Define prompts to control Gemini behavior. Effective prompts drive accuracy. Use this structure for your prompt files:

QUERY_NORMALIZER_PROMPT.TXT
01You are a query normalizer. Your task is to take a user's search query and normalize it to improve search accuracy. This includes correcting spelling mistakes, removing irrelevant words (like "please" or "thank you"), and standardizing terminology.
02
03User Query: {user_query}
04Normalized Query:
ES_DSL_FORMATION_PROMPT.TXT
01You are an expert in Elasticsearch DSL (Domain Specific Language). Your task is to translate a natural language search query into a valid Elasticsearch DSL query in JSON format. The DSL query should be as specific as possible to accurately reflect the user's intent. You must enclose the valid JSON object with markdown fences.
02
03Natural Language Query: {nl_query}
04Elasticsearch DSL Query:
GENERIC_ES_RESPONSE_SUMMARISER.TXT
01You are a summarization expert. Your task is to summarize the results of an Elasticsearch query in a concise and informative way for a user. You must enclose the valid JSON object with markdown fences. Only answer in JSON format with the key `summary`.
02
03Natural Language Query: {nl_query}
04Elasticsearch Response: {es_response}
05Summary:

Prompting Guidelines:

5. Run the agent

Test the agent. Add the following code to the end of es_agent.py:

PYTHON
01if __name__ == "__main__":
02 query = "Show me recent error logs"
03 result = es_search_agent(query)
04 print(json.dumps(result, indent=2))

The agent performs these steps:

6. Secure the Agent

Glowing shield with a padlock whose keyhole sits in a circuit-board pattern

7. Next Steps and Improvements

Key use cases for a smart Elasticsearch Agent include:

Advanced Elasticsearch Agent Considerations

Secure the Elasticsearch Agent

Security is essential for production applications, particularly those handling sensitive data. Disabling SSL certificate verification (verify=False) creates a critical security risk. Do not use this setting in production. This configuration exposes data to eavesdropping and man-in-the-middle attacks.

Implement the following security measures for the Elasticsearch Agent:

Configure SSL/TLS for node-to-node transport and client HTTP connections. Set xpack.security.transport.ssl.enabled to true. Set xpack.security.http.ssl.enabled to true.

Network Security

Restrict node access by IP address. Use xpack.security.transport.filter.allow and xpack.security.http.filter.allow. Configure firewalls to open only ports 9200 (HTTP) and 9300 (transport). Restrict access to management interfaces. Isolate Elasticsearch from public internet access unless required.

Data Protection

Restrict access to sensitive document fields, such as ssn and credit_card.

Implement document-level security. Filter results based on user context. Users access only authorized data.

Enable audit logging. Set xpack.security.audit.enabled: true. Track security events, including failed authentication attempts, privilege escalation attempts, and unusual access patterns.

Apply these security measures systematically. This ensures the agent functions as a trusted enterprise component. Strong security supports compliance with data protection regulations. It also builds user confidence. Data security is mandatory for production systems handling sensitive information.

Summary

Developing a smart Elasticsearch agent improves data usability. Combine LangGraph, Google Gemini, and precise prompts to create an effective assistant. This design helps users search and analyze data efficiently. Prioritize security. Iterate on prompts to optimize performance. Review the linked resource for details on custom AI agents. Build an Elastic agent for your enterprise.

Related reading: LangChain MCP integration for multi-tool AI agents and LangGraph for multi-agent systems in LangChain.

Contact

FAQs

1. What is a smart Elasticsearch agent? Why use one? A smart Elasticsearch agent converts natural language into Elasticsearch DSL. It removes the need to learn syntax. Users can run complex queries easily. This boosts team productivity.

2. How do LangGraph and Google Gemini work together? LangGraph controls the workflow. It manages query normalization, DSL generation, and summarization. Google Gemini interprets user input. It generates accurate DSL in JSON. The combination creates a scalable search assistant.

3. Can I search Elasticsearch using natural language? Yes. The agent accepts plain text, such as “Show me recent authentication errors.” It normalizes the query, builds the DSL, and runs the search. It returns clear, readable results. This allows non-technical users to access Elasticsearch.

4. Which security measures are essential? Security is critical. Enable SSL/TLS. Implement authentication and authorization. Filter sensitive fields. Control document-level access. Enable audit logging. These steps ensure safe enterprise deployment.

5. How does SquareShift help build a smart Elasticsearch agent? SquareShift uses LangGraph and Google Gemini to design enterprise-ready agents. We manage workflow orchestration, DSL generation, and summarization. Teams can search data in natural language. They do not need to learn complex queries.

6. Can SquareShift customize agents for specific industries? Yes. SquareShift adapts prompts, workflows, and DSL logic for specific use cases. This applies to IT operations, cybersecurity, customer support, and analytics. We align results with your business data.

7. What are the benefits of partnering with SquareShift? Enterprises gain faster insights. Productivity improves. Reliance on technical teams decreases. SquareShift delivers secure, scalable, and reliable agents. You unlock the full value of your data.

How does the smart Elasticsearch agent work step by step? The user enters a natural language query. The agent normalizes it, sends it to Gemini to generate Elasticsearch DSL, runs the DSL on the Elasticsearch cluster, summarizes the response and presents the final output. LangGraph defines this workflow, which supports later changes and extensions.

What do you need to build an Elasticsearch agent with LangGraph and Gemini? You need Python 3.7 or later, the langchain, langgraph, google-generativeai, python-dotenv and requests libraries, a Google Gemini API key with the Gemini API enabled, and access to an Elasticsearch cluster. You also create three prompt files for query normalization, DSL formation and response summarization.

Why does the agent use structured JSON output from Gemini? Elasticsearch DSL is JSON, so the pipeline needs valid JSON. Defining a response schema on the model gives higher quality and determinism than putting a schema in the prompt. It reduces post-processing and lets the agent parse generated DSL and summaries reliably.