- Elastic Cloud Serverless
- Elasticsearch
- Elastic Observability
- Get started
- Observability overview
- Elastic Observability Serverless billing dimensions
- Create an Observability project
- Quickstart: Monitor hosts with Elastic Agent
- Quickstart: Monitor your Kubernetes cluster with Elastic Agent
- Quickstart: Monitor hosts with OpenTelemetry
- Quickstart: Unified Kubernetes Observability with Elastic Distributions of OpenTelemetry (EDOT)
- Quickstart: Collect data with AWS Firehose
- Quickstart: Send data to the Elastic Cloud Managed OTLP Endpoint
- Get started with dashboards
- Applications and services
- Application performance monitoring (APM)
- Get started with traces and APM
- Learn about data types
- Collect application data
- View and analyze data
- Act on data
- Use APM securely
- Reduce storage
- Managed intake service event API
- Troubleshooting
- Synthetic monitoring
- Get started
- Scripting browser monitors
- Configure lightweight monitors
- Manage monitors
- Work with params and secrets
- Analyze monitor data
- Monitor resources on private networks
- Use the CLI
- Configure a Synthetics project
- Multifactor Authentication for browser monitors
- Configure Synthetics settings
- Grant users access to secured resources
- Manage data retention
- Scale and architect a deployment
- Synthetics Encryption and Security
- Troubleshooting
- Visualize OTLP data
- Application performance monitoring (APM)
- Infrastructure and hosts
- Logs
- Inventory
- Incident management
- Data set quality
- Observability AI Assistant
- Machine learning
- Reference
- Get started
- Elastic Security
- Elastic Security overview
- Security billing dimensions
- Create a Security project
- Elastic Security requirements
- Elastic Security UI
- AI for Security
- Ingest data
- Configure endpoint protection with Elastic Defend
- Manage Elastic Defend
- Endpoints
- Policies
- Trusted applications
- Event filters
- Host isolation exceptions
- Blocklist
- Optimize Elastic Defend
- Event capture and Elastic Defend
- Endpoint protection rules
- Identify antivirus software on your hosts
- Allowlist Elastic Endpoint in third-party antivirus apps
- Elastic Endpoint self-protection features
- Elastic Endpoint command reference
- Endpoint response actions
- Cloud Security
- Explore your data
- Dashboards
- Detection engine overview
- Rules
- Alerts
- Advanced Entity Analytics
- Investigation tools
- Asset management
- Manage settings
- Troubleshooting
- Manage your project
- Changelog
Get started with the Java client
editGet started with the Java client
editThis page guides you through the installation process of the Java client, shows you how to initialize the client, and how to perform basic Elasticsearch operations with it.
See the Java client documentation for more detailed usage instructions.
The same client is used for Elasticsearch Serverless, on-premise and managed Elasticsearch. Some API endpoints are however not available in Elasticsearch Serverless.
Requirements
edit- Java 8 or later.
- A JSON object mapping library to allow seamless integration of your application classes with the Elasticsearch API. The examples below show usage with Jackson.
Installation
editYou can add the Java client to your Java project using either Gradle or Maven.
Use the version with the highest version number found on Maven Central, like 8.16.1
. We refer to it as elasticVersion
in the configuration examples below.
Using Gradle
editYou can install the Java client as a Gradle dependency:
dependencies { implementation "co.elastic.clients:elasticsearch-java:${elasticVersion}" implementation "com.fasterxml.jackson.core:jackson-databind:2.17.0" }
Using Maven
editYou can install the Java client as a Maven dependency, add
the following to the pom.xml
of your project:
<project> <dependencies> <dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>${elasticVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.17.0</version> </dependency> </dependencies> </project>
Initialize the client
editInitialize the client using your API key and Elasticsearch endpoint:
// URL and API key String serverUrl = "https://...elastic.cloud"; String apiKey = "VnVhQ2ZHY0JDZGJrU..."; // Create the low-level client RestClient restClient = RestClient .builder(HttpHost.create(serverUrl)) .setDefaultHeaders(new Header[]{ new BasicHeader("Authorization", "ApiKey " + apiKey) }) .build(); // Create the transport with a Jackson mapper ElasticsearchTransport transport = new RestClientTransport( restClient, new JacksonJsonpMapper()); // And create the API client ElasticsearchClient esClient = new ElasticsearchClient(transport);
To get API keys for the Elasticsearch endpoint for a project, see Get started.
Using the API
editAfter you initialized the client, you can start ingesting documents.
Creating an index and ingesting documents
editThe following is an example of indexing a document, here a Product
application
object in the products
index:
Product product = new Product("bk-1", "City bike", 123.0); IndexResponse response = esClient.index(i -> i .index("products") .id(product.getSku()) .document(product) ); logger.info("Indexed with version " + response.version());
Searching
editNow that some data is available, you can search your documents using the
search
API:
String searchText = "bike"; SearchResponse<Product> response = esClient.search(s -> s .index("products") .query(q -> q .match(t -> t .field("name") .query(searchText) ) ), Product.class );
A few things to note in the above example:
- The search query is built using a hierarchy of lambda expressions that closely follows the Elasticsearch HTTP API. Lambda expressions allows you to be guided by your IDE’s autocompletion, without having to import (or even know!) the actual classes representing a query.
-
The last parameter
Product.class
instructs the client to return results asProduct
application objects instead of raw JSON.
Updating
editYou can update your documents using the update
API:
Product product = new Product("bk-1", "City bike", 123.0); esClient.update(u -> u .index("products") .id("bk-1") .upsert(product), Product.class );
Delete
editYou can also delete documents:
esClient.delete(d -> d.index("products").id("bk-1"));
Deleting an index
editesClient.indices().delete(d -> d.index("products"));
On this page