Java ElasticSearch 5 examples with node index and mapping - running local

In this tutorial I will present how you can test Elasticsearch 5 on your project, we will create a Index and add a mapping. At the end we will delete the index and all files created by elasticsearch.

First of all we need to add dependecies to our maven project



We will create NodeBuilder wich has a static propery "theNode", and we will define the getNode method, I know NodeBuilder is not enymore in the elasticsearch java API.

path.home in our case will be "./target/newtutorials"

    static Node theNode;
    public static Node getNode(String tempFolder, String clusterName, boolean isClientNode) throws NodeValidationException {
        if (theNode!=null)
            return theNode;
        Settings settings = Settings.builder()
                .put("path.home", tempFolder)
                .put("", clusterName)
                .put("transport.type", "local")
                .put("http.enabled", false)
        theNode = new Node(settings).start();

        return theNode;

Now we should have a node started in our project after start()

let define all methods used in this tutorial 

After the node is started we may want to create the index :

    private static void createIndex(String index, Client client) throws NodeValidationException, InterruptedException, ExecutionException {
        ActionFuture<IndicesExistsResponse> indicesExistsResponseAction = client.admin().indices().exists(new IndicesExistsRequest(index));
        IndicesExistsResponse indicesExistsResponse = indicesExistsResponseAction.actionGet();
        if (!indicesExistsResponse.isExists())
            ActionFuture<CreateIndexResponse> createIndexResponseAction = client.admin().indices().create(new CreateIndexRequest(index));
            CreateIndexResponse createIndexResponse = createIndexResponseAction.get();
            if (!createIndexResponse.isAcknowledged()) {
                throw new IllegalStateException("Failed to create index " + index);

Implementation for deleteing an elasticsearch index

    private static void deleteIndex(String index, Client client) throws NodeValidationException, InterruptedException, ExecutionException {

A method to encapsulate the putMapping 

    private static void putMapping(String index, Client client, String type, String mappingSource) throws NodeValidationException {
        PutMappingResponse mappingResponse = client.admin().indices().preparePutMapping(index)
        if (!mappingResponse.isAcknowledged()) {
            throw new IllegalStateException("Failed to create type " + index);

now we will define a method to create documents

    private static XContentBuilder createDocumentXContent(String title, String author, int pages) throws IOException {
        return XContentFactory.jsonBuilder()
                        .field("title", title)
                        .field("author", author)
                        .field("pages", pages)

At the end we are ready to test everything , we will write the main method :

    public static void main(String[] args) throws NodeValidationException, IOException, ExecutionException, InterruptedException {
        try {
            Node node = NodeBuilder.getNode(NodeBuilder.TEMP_FOLDER, NodeBuilder.CLUSTER_NAME, false);

node will be a reference to a Node object , we will use it to get the Client node.client()

            final String indexName = "newtutorials-examples";

new we have the index ready, then we can put the mapping for few fields

            final String documentsType = "documents";
                    , documentsType
                    , "{\"properties\":{\"title\":{\"type\":\"string\"},\"author\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}");

the mapping should be now in place , lets add a document

            XContentBuilder document = createDocumentXContent("Test document", "Elastic Search", 100);
            IndexResponse response = node.client().prepareIndex(indexName, documentsType)

The document is added with id "1" , after this we will fetch it using Get: 

            if (response.status().getStatus() == RestStatus.CREATED.getStatus())
                GetResponse getResponse = node.client().prepareGet(indexName,documentsType,"1").get();

We are cheking the result status , if it is CREATED then we will query it , and we will se the response :

	"_index": "newtutorials-examples",
	"_type": "documents",
	"_id": "1",
	"_version": 1,
	"found": true,
	"_source": {
		"title": "Test document",
		"author": "Elastic Search",
		"pages": 100

We had a lot of fun , let do the dirty job , and we will delete the index and close the node

        }catch (Exception e){
        } finally {

on finally we will delete the folder created by elasticsearch 

 as a note , if you have the server you can get the client like this :

    public static TransportClient createElasticSearchClient(String host,int port, String clusterName) throws UnknownHostException

        Settings settings = Settings.builder()
                .put("", clusterName)
                .put("client.transport.sniff", true)
                .put("client.transport.ping_timeout", 20, TimeUnit.SECONDS)
        return new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(Inet4Address.getByName(host), port));

Download sources from github : elasticsearch examples

Category: Java Tutorials