How to insert documents to Elasticsearch cluster Java - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we will see how to insert documents to Elasticsearch cluster.
Elasticsearch
Java8
Maven
Add the below dependencies to your pom.xml to work with elasticsearch.
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.6.0</version>
</dependency>
Adding JSON documents to an elasticsearch cluster.
I have installed elasticsearch on my windows machine, and HTTP port is running on 9200, transport port is running on 9300.  The below code snippet is to create elasticsearch transport client, it connects with local elasticsearch cluster.
public static Client getClient() throws UnknownHostException {
        Client client = new PreBuiltTransportClient(
                Settings.builder().put("client.transport.sniff", true)
                        .put("cluster.name","elasticsearch").build())
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
        return client;
}
prepareIndex() method is used to store JSON message to an elasticsearch cluster and make it as searchable. It has three parameters which are indexName, type and documentId. In the following example; the indexName is otp, type is items and documentId is 1.
public static void insertJson() throws UnknownHostException {
        String jsonObject = "{\"name\":\"Lenovo\","
                +"\"category\":\"Laptop\","
                +"\"description\":\"Lenovo Laptops\"}";
        IndexResponse response = getClient().prepareIndex("otp", "items","1")
                .setSource(jsonObject, XContentType.JSON).get();
    }
On the above example, we manually created the JSON string. Instead, you can use any of JSON libraries available in the market.
 
If you are not familiar with any of the JSON libraries, you can use elasticsearch helper – XContentFactory to build JSON documents like the following.
XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", "Spring in Action")
                .field("category", "Books")
                .field("description", "Spring Books")
                .endObject();
        IndexResponse response = getClient().prepareIndex("otp", "items","4")
                .setSource(builder).get();
We can also insert the data into Elsticsearch cluster as Java Map like below.
public static void insertMap() throws UnknownHostException {
        Map<String,Object> data = new HashMap<>();
        data.put("name","iPhoneX");
        data.put("category","Mobiles");
        data.put("description","Apple Mobiles");
        IndexResponse response = getClient().prepareIndex("otp", "items","3")
                .setSource(data).get();
    }
package com.onlinetutorialspoint;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class ElasticseachInsert {
    public static void main(String[] args) throws IOException {
        insertAsJsonBuilder();
    }

    public static void insertMap() throws UnknownHostException {
        Map<String,Object> data = new HashMap<>();
        data.put("name","iPhoneX");
        data.put("category","Mobiles");
        data.put("description","Apple Mobiles");
        IndexResponse response = getClient().prepareIndex("otp", "items","3")
                .setSource(data).get();
    }

    public static void insertJson() throws UnknownHostException {
        String jsonObject = "{\"name\":\"Lenovo\","
                +"\"category\":\"Laptop\","
                +"\"description\":\"Lenovo Laptops\"}";
        IndexResponse response = getClient().prepareIndex("otp", "items","1")
                .setSource(jsonObject, XContentType.JSON).get();
    }
    public static void insertAsJsonBuilder() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", "Spring in Action")
                .field("category", "Books")
                .field("description", "Spring Books")
                .endObject();
        IndexResponse response = getClient().prepareIndex("otp", "items","4")
                .setSource(builder).get();
    }

    public static Client getClient() throws UnknownHostException {
        Client client = new PreBuiltTransportClient(
                Settings.builder().put("client.transport.sniff", true)
                        .put("cluster.name","elasticsearch").build())
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
        return client;
    }
}

Elasticsearch insert docs
How to install Elasticsearch on windows 10
Happy Learning 🙂

How to install Elasticsearch on Windows 10
How to convert Java Map to JSON
How to convert JSON to Java Map Object
How to convert JSON to Java Object Example
How to convert Java Object to JSON
JDBC Insert Program Example
Insert an Image using JDBC in Mysql DB
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to Format JSON Output PrettyPrinter Example
Spring Boot Kafka Consume JSON Messages Example
Apache Solr- Delete Documents from Solr using SolrJ
Factory Method Pattern in Java
Apache Solr – How to Add Documents to Solr using SolrJ
How to Install Kubernetes on Ubuntu 18.04

How to install Elasticsearch on Windows 10
How to convert Java Map to JSON
How to convert JSON to Java Map Object
How to convert JSON to Java Object Example
How to convert Java Object to JSON
JDBC Insert Program Example
Insert an Image using JDBC in Mysql DB
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to Format JSON Output PrettyPrinter Example
Spring Boot Kafka Consume JSON Messages Example
Apache Solr- Delete Documents from Solr using SolrJ
Factory Method Pattern in Java
Apache Solr – How to Add Documents to Solr using SolrJ
How to Install Kubernetes on Ubuntu 18.04






Dishant
January 19, 2022 at 4:05 pm - Reply 

how can I run this file? Can you please post a sample curl command to see this code’s working?










Dishant
January 19, 2022 at 4:05 pm - Reply 

how can I run this file? Can you please post a sample curl command to see this code’s working?




how can I run this file? Can you please post a sample curl command to see this code’s working?