Chris
Chris

Reputation: 18876

Elasticsearch Java API Index Document

  1. Downloaded .90.6, Unpacked, moved Elastic Search to /usr/share/elasticsearch (with chmod 777 -R permissions on centosx64 6.4), renamed cluster to somethingstupid and started server.

  2. Installed plugins ESHead and ESBrowser b/c Im new and need it (am used to Solr's nice ui). This way I know the server is running too.

  3. I can create an index via curl : curl -XPOST 'http://localhost:9200/testindex' and delete it too: curl -XDELETE 'http://localhost:9200/testindex'

When I try creating a new index and indexing a document of type article and viewing it via Java API, eclipse runs the code, shows basic logging in the console, and then closes with no errors. Also, inside my logs the latest line just shows that I have started up elastic search but nothing else. Its like the code isnt even reaching elastic search. No indexes or articles show up after I run the java api. What am I missing?

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

import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;

import static org.elasticsearch.node.NodeBuilder.*;

public class PostES {

    public static void main (String args[]){
        PostES p = new PostES();
        p.postElasticSearch();
    }


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

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

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

            return jsonDocument;
    }


    private void postElasticSearch(){

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

            client.prepareIndex("testindex", "article")
                      .setSource(putJsonDocument("Example Title",
                                                 "This description is so important. You don't even know!",
                                                 new Date(),
                                                 "J.R."))
                                                 .execute().actionGet();

            node.close();
        }


}

My Source: http://java.dzone.com/articles/elasticsearch-java-api. Everything else including the elastic documentation failed one way or another....(The method jsonBuilder() is undefined for the type PostES).

According to documentation I should be able to do this. But it does nothing either:

import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;


public class TestPostMethod2 {

    public static void main(String[] args) {
        Node node = nodeBuilder().local(true).node();
        Client client = node.client();

            String json = 
                    "{\"user\":\"kimchy\"," +
                    "\"postDate\":\"2013-01-30\"," +
                    "\"message\":\"trying out Elastic Search\"}";              

            IndexResponse response = client.prepareIndex("testindex", "article")
                    .setSource(json)
                    .execute()
                    .actionGet();
    }

}

Upvotes: 2

Views: 23241

Answers (5)

Sunil Prakash
Sunil Prakash

Reputation: 31

I would suggest anyone to use rest client(jest) instead of transport client, remember to add all dependencies specified in link-1 & link-2

replace "index_name" = with your index name

creating simple index and inserting data using java,

public void setData(String data)
{           
    try

    {
     // Construct a new Jest client according to configuration via factory
     JestClientFactory factory = new JestClientFactory();
     factory.setHttpClientConfig(new HttpClientConfig
                            .Builder("http://localhost:9200")
                            .multiThreaded(true)
                            .build());
     JestClient client = factory.getObject();

client.execute(new CreateIndex.Builder("index_name").build());



        String source = jsonBuilder()
                .startObject()
                .field("data", data)
                 //other data
                .endObject().string();
        System.out.println(source); // verify data

        Index index = new Index.Builder(source).index("index_name").type("_type").build();
        client.execute(index);


    }
    catch(IOException i)
    {
        i.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
 }

Upvotes: 0

isapir
isapir

Reputation: 23503

Why not use the Transport Client with a 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 java.util.*;

public class Test {

    public static Client getTransportClient(String host, int port) {

        return new TransportClient()
                .addTransportAddress(new InetSocketTransportAddress(host, port));
    }

    public static IndexResponse doIndex(Client client, String index, String type, String id, Map<String, Object> data) {

        return client.prepareIndex(index, type, id)
                .setSource(data)
                .execute()
                .actionGet();
    }

    public static void main(String[] args) {

        Client client = getTransportClient("localhost", 9300);

        String index  = "twitter";
        String type   = "tweet";
        String id     = null;        // set id here if you want to

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("text", "Posted from Java @ " + System.currentTimeMillis());
        data.put("user", "Igal");
        data.put("date", new Date());

        IndexResponse result = doIndex(client, index, type, id, data);

        System.out.println((result.isCreated() ? "created" : "updated") + " document " + result.getId() );

        client.close();
    }
}

Upvotes: 0

javanna
javanna

Reputation: 60205

You need to specify your cluster name when creating a node and specify it is a client node, or use the transport client.

What you are currently doing in both cases is starting a new node that creates a new cluster with default name, while you would like to have a client node to join your existing cluster.

Node node = nodeBuilder().clusterName("somethingstupid").client(true).node();

Upvotes: 1

Chris
Chris

Reputation: 18876

1 way I can get the api to work is by not using it:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


public class PostHttpClient {

    public static void main(String[] args) {
        try{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(
            "http://localhost:9200/testindex/article");

        StringEntity input = new StringEntity("{\"name\":\"ES JAVA API WorkAround\",\"category\":\"Garbage\"}");
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();

      } catch (Exception e) {

        e.printStackTrace();

      } 

    }

}

Upvotes: 0

Алексей
Алексей

Reputation: 1847

not sure if this is related, but when originally i were trying to connect to running ES cluster from eclipse i had to add this to the arguments of my tomcat:

-Delasticsearch -Des.path.home=/usr/local/opt/elasticsearch

where elasticsearch is the name that you have defined in elasticsearch.yml and of course the path where you have installed ES

Upvotes: 0

Related Questions