Sufi Nawaz

I build stuff
SpringBootApp
0

Spring Boot Starter App with Elasticsearch

Posted by in Apps, Code Snippets

This weekend, I needed to set up a quick backend service with RESTful API that uses Elasticsearch as the datasource. I’d been working with Spring framework for a while but haven’t had to use Spring boot for anything related to my work. So, I read up on the latest Spring Boot documentation and went over to https://start.spring.io/ to create a barebone Spring Boot app that uses Elasticsearch. The whole process took a matter of few minutes, once I gathered the proper information to set up a starter app. Here’s a short outline of what I did.

Spring initializr to create a starter Spring Boot app
  1. Go over to https://start.spring.io/ and set up the project with the settings above. I am including lombok (for convenience of property accessers), Spring web and elasticsearch.
  2. In my macOS, I am using docker to run elasticsearch locally as follows:
    brew install docker
    docker pull elasticsearch:6.6.2
    docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:6.6.2
    As a sidenote, if you’re on macOS, I would recommend installing everything (when possible) using brew. As convenient as brew makes life, it’s also a nightmare when packages are installed natively and then again through brew for a different version. So as a general rule of thumb, I use brew for maintaining all my OS applications and packages when possible.
  3. If you want to run elasticsearch locally instead of using docker, you can use brew to install elasticsearch and run that accordingly. However, I chose to to go with docker since I can reuse the docker container and share that around as a stateful container if I so desire.
  4. You can check to see if the cluster is running and healthy by running:
    curl http://localhost:9200/_cluster/state
  5. Once pulled down, I have added a resource class, a service class and a repository class for a sample User model. You could use this as a sample to create more relevant POJOs.
  6. Once completed, you can run mvn clean package and run the App.
  7. To create a user, you can curl as follows:
    curl -sXPOST http://localhost:8080/user -H "Content-Type: application/json" -d '{"username":"sufinawaz", "firstName": "Sufi", "lastName": "Nawaz"}'
  8. To fetch a user, you can curl as follows:
    curl -sXGET http://localhost:8080/user/username/USERNAME

Full source code is available in github.