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

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.3.0</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.3.6</version>
        </dependency>
    </dependencies>

 

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("cluster.name", clusterName)
                .put("transport.type", "local")
                .put("http.enabled", false)
                .build();
        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 {
        client.admin().indices().prepareDelete(index).get();
    }

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)
                .setType(type)
                .setSource(mappingSource)
                .get();
        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()
                        .startObject()
                        .field("title", title)
                        .field("author", author)
                        .field("pages", pages)
                        .endObject();
    }

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";
            createIndex(indexName,node.client());

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

            final String documentsType = "documents";
            putMapping(indexName,node.client()
                    , 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)
                    .setId("1")
                    .setSource(document).get();

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();
                System.out.println(getResponse.toString());
            }

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

            deleteIndex(indexName,node.client());
            node.close();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            FileUtil.deleteFolder(NodeBuilder.TEMP_FOLDER);
        }
    }

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("cluster.name", clusterName)
                .put("client.transport.sniff", true)
                .put("client.transport.ping_timeout", 20, TimeUnit.SECONDS)
                .build();
        return new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(Inet4Address.getByName(host), port));
    }

Download sources from github : elasticsearch examples

Category: Java Tutorials