Sunday 20 December 2015

Create Elasticsearch index using RESTFul Service and Java API


Elasticsearch is used for faster retrieval of data from a stored index. An index can be created either by using the RESTFul service or Java APIs exposed by Elasticsearch. In this blog, let us see what an index is and how to create it.

Basically, an Elasticsearch index is more like a database with multiple types (tables) in it. In relational model, an index can be related to database and type can be related to a table in the database. All the documents that are indexed are similar to the rows in a database table.
An elastic search cluster can have more than one index.

The below code will create an index with name ‘simplyjava’ in the Elasticsearch cluster. We can add our own settings in the created index. By settings, I mean that the type of analyzers, number of shards and number of replicas to be used by index. This will be covered in upcoming posts.

Creating an index using Elasticsearch RESTFul service:

$ curl -XPUT 'http://localhost:9200/simplyjava/'

Creating an index using Elasticsearch Java API:

Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch").build();
TransportClient transportClient = new TransportClient(settings);
transportClient = transportClient.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
Client  client = (Client) transportClient;
CreateIndexRequestBuilder createIndex = client.admin().indices().prepareCreate("simplyjava");
CreateIndexResponse response = createIndex.execute().actionGet();


Note : Even though both the codes do the same functionality you can see that the port value used is different. That is because, 9300 is the port where the TransportClient resides and 9200 is the http port configured in Elasticsearch.

No comments:

Post a Comment