Hackerss.com

hackerss
hackerss

Posted on

Insert data to a elasticsearch index in Java

Insert data to a elasticsearch index - Java:


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

/**
 * This class insert data to a elasticsearch index with javadoc
 * @author juanjose
 * @version 1.0
 */
public class InsertData {

    /**
     * This method insert data to a elasticsearch index with javadoc
     * @param indexName name of the index to insert data
     * @param typeName name of the type to insert data
     * @param id id of the document to insert data
     * @param fieldName name of the field to insert data
     * @param fieldValue value of the field to insert data
     * @return IndexResponse Obtains the response of the index operation
     */
    public IndexResponse insertData(String indexName, String typeName, String id, String fieldName, String fieldValue) {

        //Variable to store the response of the index operation
        IndexResponse response = null;

        //Create a client to connect to elasticsearch cluster
        Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 9300));

        //Create a json object with the data to insert in the index
        XContentBuilder builder = null;

        try {

            builder = XContentFactory.jsonBuilder().startObject().field(fieldName, fieldValue).endObject();

        } catch (IOException e) {

            e.printStackTrace();

        }

        //Insert the data in the index and obtain the response of the operation
        response = client.prepareIndex(indexName, typeName, id).setSource(builder).execute().actionGet();

        //Close the connection with elasticsearch cluster
        client.close();

        //Return the response of the index operation
        return response;

    }

    /**
     * One Example
     */
    public static void main(String args[]) throws IOException {

        InsertData insertData = new InsertData();

        //Example
        IndexResponse response = insertData.insertData("twitter", "tweet", "1", "user", "juanjose");

        //Output
        System.out.println("response: " + response); //response: IndexResponse[index=twitter,type=tweet,id=1,version=1,created=true]

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)