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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Creating Scalable OpenAI GPT Applications in Java
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • How To Set Up a Scalable and Highly-Available GraphQL API in Minutes
  • How To Build Web Service Using Spring Boot 2.x

Trending

  • How To Aim for High GC Throughput
  • A Complete Guide to Open-Source LLMs
  • OneStream Fast Data Extracts APIs
  • How To Start a Successful Career in DevOps
  1. DZone
  2. Data Engineering
  3. Databases
  4. ElasticSearch: Java API

ElasticSearch: Java API

ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object.

Hüseyin Akdoğan user avatar by
Hüseyin Akdoğan
CORE ·
Sep. 30, 13 · Tutorial
Like (4)
Save
Tweet
Share
136.63K Views

Join the DZone community and get the full member experience.

Join For Free

ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object. Client object can execute the operations in bulk, cumulatively. Java API can be used internally in order to execute all APIs in ElasticSearch.

In this tutorial, we will consider how to carry out some operations with Java API in a standalone Java application that is similar to the ones we made in the previous article with the console. 

Dependency

ElasticSearch is hosted on Maven central. In your Maven Project, you can define which ElasticSearch version you want to use in your pom.xml file as shown below:

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>0.90.3</version>
</dependency>

Client

Using client, you can perform administrative tasks in a running cluster, and some operations, such as standard index, get, delete and search operations, in an existing cluster. Also, you can launch all of the nodes. 

The most common way of obtaining an ElasticSearch client is creating an embedded node which acts like a node in a cluster and then requesting a client from that embedded node. 

Another way of obtaining a client is creating a TransportClient (it connects from remote by using transport module) which connects to a cluster. 

One should consider using the same version of client and cluster while using Java API. The difference between client and cluster versions may cause some incompatibilities.

Node Client

The simplest way of getting a client instance is the node based client. 

Node node  = nodeBuilder().node();
Client client = node.client();

When a node is started, it joins to the "elasticsearch" cluster. You can create different clusters using the cluster.name setting or clusterName method in the /src/main/resources directory and in elasticsearch.yml file in your project:

cluster.name: yourclustername

Or in Java code:

Node node = nodeBuilder().clusterName("yourclustername").node();
Client client = node.client();

Creating Index

The Index API allows you to type a JSON document into a specific index, and makes it searchable. There are different ways of generating JSON documents. Here we used map, which represents JSON structure very well. 

public static Map<String, Object> putJsonDocument(String title, String content, Date postDate, 
                                                      String[] tags, String author){

        Map<String, Object> jsonDocument = new HashMap<String, Object>();

        jsonDocument.put("title", title);
        jsonDocument.put("conten", content);
        jsonDocument.put("postDate", postDate);
        jsonDocument.put("tags", tags);
        jsonDocument.put("author", author);

        return jsonDocument;
    }
Node node    = nodeBuilder().node();
Client client   = node.client();

client.prepareIndex("kodcucom", "article", "1")
              .setSource(putJsonDocument("ElasticSearch: Java API",
                                         "ElasticSearch provides the Java API, all operations "
                                         + "can be executed asynchronously using a client object.",
                                         new Date(),
                                         new String[]{"elasticsearch"},
                                         "Hüseyin Akdoğan")).execute().actionGet();

        node.close();

With the above code, we generate an index by the name of kodcucom and a type by the name of article with standard settings and a record (we don’t have to give an ID here) whose ID value of 1 is stored to ElasticSearch. 

Getting Document

The Get API allows you to get a typed JSON document, based on the ID, from the index. 

GetResponse getResponse = client.prepareGet("kodcucom", "article", "1").execute().actionGet();

Map<String, Object> source = getResponse.getSource();

System.out.println("------------------------------");
System.out.println("Index: " + getResponse.getIndex());
System.out.println("Type: " + getResponse.getType());
System.out.println("Id: " + getResponse.getId());
System.out.println("Version: " + getResponse.getVersion());
System.out.println(source);
System.out.println("------------------------------");

Search

The Search API allows you to execute a search query and get the matched results. The query can be executed across more than one indices and types. The query can be provided by using query Java API or filter Java API. Below you can see an example whose body of search request is built by using SearchSourceBuilder. 

public static void searchDocument(Client client, String index, String type,
                                      String field, String value){

        SearchResponse response = client.prepareSearch(index)
                                        .setTypes(type)
                                        .setSearchType(SearchType.QUERY_AND_FETCH)
                                        .setQuery(fieldQuery(field, value))
                                        .setFrom(0).setSize(60).setExplain(true)
                                        .execute()
                                        .actionGet();

        SearchHit[] results = response.getHits().getHits();

        System.out.println("Current results: " + results.length);
        for (SearchHit hit : results) {
            System.out.println("------------------------------");
            Map<String,Object> result = hit.getSource();   
            System.out.println(result);
        }

    }


searchDocument(client, "kodcucom", "article", "title", "ElasticSearch");

Updating

Below you can see an example of a field update.

public static void updateDocument(Client client, String index, String type, 
                                      String id, String field, String newValue){

        Map<String, Object> updateObject = new HashMap<String, Object>();
        updateObject.put(field, newValue);

        client.prepareUpdate(index, type, id)
              .setScript("ctx._source." + field + "=" + field)
              .setScriptParams(updateObject).execute().actionGet();
    }
updateDocument(client, "kodcucom", "article", "1", "tags", "big-data");

Deleting

The delete API allows you to delete a document whose ID value is specified. You can see below an example of deleting a document whose index, type and value is specified. 

public static void deleteDocument(Client client, String index, String type, String id){

        DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
        System.out.println("Information on the deleted document:");
        System.out.println("Index: " + response.getIndex());
        System.out.println("Type: " + response.getType());
        System.out.println("Id: " + response.getId());
        System.out.println("Version: " + response.getVersion());
    }
deleteDocument(client, "kodcucom", "article", "1");

See the sample application here.

API Java (programming language) Elasticsearch cluster Database

Published at DZone with permission of Hüseyin Akdoğan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating Scalable OpenAI GPT Applications in Java
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • How To Set Up a Scalable and Highly-Available GraphQL API in Minutes
  • How To Build Web Service Using Spring Boot 2.x

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: