Rob Rob - 2 years ago 147
Java Question

elasticsearch insert objects into index

I am new to elasticsearch and looking for a bit of help using the Java API. I have some domain objects


public class BasicActivity {

private String activityName;
private FullActivity activity;
// Getters and setters

I have created a transport client connected to a node

Client client = new TransportClient()
.addTransportAddress(new InetSocketTransportAddress("",9300));

Is there and easy way to insert my object straight into elasticsearch?

I have seen this

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elastic Search")

But to do that I would have to convert every object into json, which while possible is not my ideal situation.

If I have a misunderstanding of how it works (architecturally) then please let me know, I am here to learn!


Answer Source

I think your on the right track. The Java API can be hard to get at times when you're not used to it. I think over time it will get better.

You do have to convert your objects to Json to send them to your ElasticSearch cluster. Gson is one of many popular libraries out there that can do that for you.

The code you shown above will create an index. Now to add a document to that index, run something like this.

   Tweet tweet = new Tweet();

   IndexRequest indexRequest = new IndexRequest("twitter","tweet", tweet.getId());
   indexRequest.source(new Gson().toJson(tweet));
   IndexResponse response = client.index(indexRequest).actionGet();

Check out BulkRequest for indexing several items at once. Once your objects get more complex, you'll need to create Mappings.

I have found great examples in the Guide, but usually more detailed examples in the ES Google Group.

I have to recommend the Head front end too. It shows you existing indices and items.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download