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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Reactive Elasticsearch With Quarkus
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Aggregating REST APIs Calls Using Apache Camel

Trending

  • How to Submit a Post to DZone
  • A Complete Guide to Modern AI Developer Tools
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Automatic Code Transformation With OpenRewrite
  1. DZone
  2. Data Engineering
  3. Big Data
  4. Java High-Level REST Client: Elasticsearch

Java High-Level REST Client: Elasticsearch

Learn about using a Java high-level REST client with Elasticsearch to use API-specific methods that accept request objects as an argument and return response objects.

By 
Divya Dua user avatar
Divya Dua
·
Feb. 07, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
83.2K Views

Join the DZone community and get the full member experience.

Join For Free

Elasticsearch is an open-source, highly scalable full-text search and analytics engine. Using it, you can easily store, search, and analyze a large amount of data in real time. The Java REST client is the official client for Elasticsearch and comes in two flavors:

  1. Java low-level REST client: It allows communicating with an Elasticsearch cluster through HTTP and leaves requests marshaling and responses un-marshaling to users.
  2. Java high-level REST client: It is based on a low-level client and exposes API-specific methods, taking care of requests marshaling and responses un-marshaling.

Our focus here will be to learn about the high-level REST client. I hope you are clear with the basics of Elasticsearch; if not, you can go through its documentation here.

Introduction

The Java high-level REST client works on top of a Java low-level REST client. It is forward-compatible. It allows one to use API-specific methods that accept request objects as an argument and return response objects. Serialization and deserialization of request and response objects is handled by the client itself. Each API can be called either synchronously or asynchronously.

Let's discuss how we can use a high-level REST client in our Scala-SBT application.

Following is the dependency you need to add to build.sbt for using the client:

"org.elasticsearch.client" % "elasticsearch-rest-high-level-client" % "6.1.2"

Since the high-level REST client depends on the Elasticsearch core, don't forget to add an Elasticsearch core dependency.

"org.elasticsearch" % "elasticsearch" % "6.1.2"

Initialization

The REST high-level client instance can be built as follows:

val client = new RestHighLevelClient(
  RestClient.builder(new HttpHost(HOST, PORT, "http")))

Here, you can replace HOST with the IP address on which Elasticsearch is running. 9200 is the port to send REST requests to for that node.

The Java high-level REST client supports various APIs — Index, Update, Search, Get, Delete, and Bulk are some of those APIs, and there are many more.

CRUD and Search Operations

With the help of a REST client, we can perform CRUD (Create, Read, Update, and Delete) and search operations against our indexes. Let's just have a quick review of these features.

Index a Document in Elasticsearch

To insert a document, first, we need to create an IndexRequest — which requires index, type, and document Id as arguments. After that, the document source should be provided with the request in JSON and other supported formats. Here's an example:

val request = new IndexRequest(index_name, type_name, id)
request.source(jsonString, XContentType.JSON)

(jsonString refers to the data you want to insert in Elasticsearch.)

Then, you can execute the request with the help of the client you created before.

client.index(request)

Update an Existing Document

To update a document, you need to prepare an UpdateRequest passing index, type, and ID as arguments and then use a script or a partial document for updating. Then, execute the update request through the client.

val updateRequest = new UpdateRequest(index_name, type_name, id)

val builder = XContentFactory.jsonBuilder
builder.startObject
builder.field(fieldName, value)
builder.endObject

updateRequest.doc(builder)
client.update(updateRequest)

Delete Operation

Deleting a document just requires two lines of code. Create a DeleteRequest and then execute it via the REST client.

val deleteRequest = new DeleteRequest(index_name, type_name, id)
client.delete(deleteRequest)

Deleting the index is also a simple task. Following is the example for that:

val request = new DeleteIndexRequest(index_name)
client.indices().deleteIndex(request)

Search Documents

SearchRequest is used for any operation that has to do with searching documents, aggregations, and suggestions, and also offers ways of requesting highlighting on the resulting documents.
First, create a SearchRequest passing the index name as the argument.

val searchRequest = new SearchRequest(index_name)

After that, SearchSourceBuilder needs to be created. Add to it the query you want to execute.

val searchSourceBuilder = new SearchSourceBuilder
searchSourceBuilder.query(QueryBuilders.matchAllQuery())
searchRequest.source(searchSourceBuilder)

Lastly, execute the SearchRequest through the REST client.

client.search(searchRequest)

There are several other operations you can execute via a high-level REST client. Also, You can use Kibana to search, view, and interact with data stored in Elasticsearch indices. To understand Kibana, you can go through the documentation.

The complete demo code is available here. You can check the README.md file for instructions to run the application.

References

  • Java High-Level REST Client

Happy blogging!

REST Web Protocols Elasticsearch Java (programming language)

Published at DZone with permission of Divya Dua, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Reactive Elasticsearch With Quarkus
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Aggregating REST APIs Calls Using Apache Camel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!