1. Overview

Right now in the market, there are two most popular search engines available one is Apache Solr and the second one is Elastic Search. Both these search engines are based on Apache Lucene.

In this article, we will discuss how to index documents in Elastic Search using Elastic Search JAVA Transport Client with an example.

2. Development Environment

Elastic Search: 6.2.4

Java: 1.8.0_65

IDE: IntelliJ Idea

Build Tool: Maven

3. Steps to Index Document using Transport Client

Now we will discuss how to index document using Elastic Search Transport client with details explanations.

Step 1: Create Maven Project

Step 2: Add elastic-search-transport-client dependency in a project.

Elastic Search team provides client APIs to communicate with the elastic search for Java, C# .NET, Python etc… In this article, we will discuss Java client of Elastic Search. Add below dependency in your project.


Step 3: Initialize transport client

TransportClient class is used to communicate with Elastic Search cluster. It connects ES cluster using transport module. Here is the sample code to the initialize client.

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("{HostName_1}"), {PORT})); //1st ES Node host and port
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("{HostName_2"), {PORT}));  //2nd ES Node host and port

Step 4: create an index and Index type and prepare JSON

The next step is to create Index and Index type in Elastic Search. Transport Client automatically index and index type, if it does not exists when you submit any document for indexing.

Step 5: Prepare JSON Document

As per the Elastic Search Index API Documentations, there are several ways to generate JSON document, out of these options in our example we have used JSON Builder to construct the document. Refer below syntax to construct JSON Document.

XContentBuilder builder = jsonBuilder()
        .field("{FIELD_NAME_1}", "{FIELD_VALUE_1}")
        .field("{FIELD_NAME_2}", "{FIELD_VALUE_2}")
        .field("{FIELD_NAME_3}", "{FIELD_VALUE_3}")

4. Example

Here is the complete example of index single document using Elastic Search Transport Client.

Project Structure

Elastic Search Index Document Project Structure

Elastic Search Index Document Project Structure


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <description>Elastic Search Index Document Example</description>

Document Pojo

package javadeveloperzone.pojo;
import java.util.Date;
 * Created by JavaDeveloperZone on 5/13/2018.
public class Document {
    int docId;
    String docTitle;
    int page;
    String docType;
    Date modifiedDate;
    public int getDocId() {
        return docId;
    public void setDocId(int docId) {
        this.docId = docId;
    public String getDocTitle() {
        return docTitle;
    public void setDocTitle(String docTitle) {
        this.docTitle = docTitle;
    public int getPage() {
        return page;
    public void setPage(int page) {
        this.page = page;
    public String getDocType() {
        return docType;
    public void setDocType(String docType) {
        this.docType = docType;
    public Date getModifiedDate() {
        return modifiedDate;
    public void setModifiedDate(Date modifiedDate) {
        this.modifiedDate = modifiedDate;


package javadeveloperzone;
import javadeveloperzone.pojo.Document;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.util.Date;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 * Created by JavaDeveloperZone on 6/16/2018.
public class ESDocumentIndexingMain {
    TransportClient client = null;
    public static void main(String[] args) {
        ESDocumentIndexingMain esExample = new ESDocumentIndexingMain();
        try {
            esExample.initEStransportClinet(); //init transport client
            esExample.indexDocument(); //index one document
            esExample.refreshIndices(); //refresh indices
            esExample.search(); //search indexed document
        }catch (Exception e){
        }finally {
            esExample.closeTransportClient(); //close transport client

    Method used to init Elastic Search Transprt client,
    Return true if it is succesfully intialized otherwise false
    public boolean initEStransportClinet()
        try {
            // un-command this, if you have multiple node
            client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
            return true;
        } catch (Exception ex) {
            //log.error("Exception occurred while getting Client : " + ex, ex);
            return false;
    private boolean indexDocument(Document document){
        try {
            IndexResponse response = client.prepareIndex("document", "document", String.valueOf(document.getDocId()))
                            .field("docTitle", document.getDocTitle())
                            .field("docPage", document.getPage())
                            .field("docType", document.getDocType())
                return false;
            return true;
        }catch (Exception e){
            return false;
    public void indexDocument(){
        Document document = new Document();
        document.setDocTitle("Elastic Search Indexing Example");
        document.setModifiedDate(new Date());
        boolean isIndexed = this.indexDocument(document);
            //further actions like change index status in DB,
            // send notification etc..
    public void refreshIndices(){
                .get(); //Refresh before search, so you will get latest indices result
    public void search(){
        SearchResponse response = client.prepareSearch("document")
        System.out.println("Total Hits : "+response.getHits().getTotalHits());

    public void closeTransportClient(){



Total Hits : 1
               "docTitle":"Elastic Search Indexing Example",

5. Conclusion

In this article, we have discussed how to configure Elastic Search Transport Client in our project and how to index single document using JSON Builder, refresh Elastic  Search indices and get documents count using Match All Doc query.

6. References

Refer below links for more details:

7. Source Code

Elastic Search Index Document Example

You can also download the source code of Elastic Search Index Document Example and other useful examples from our git repository.


Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *