Elasticsearch in Go

Rajat Yadav
3 min readSep 6, 2021

In this article, we are going to study implementation of Elasticsearch in Golang.

Elasticsearch is NoSQL database written in Java and it is a real-time, distributed, and analysis engine based on the Lucene library.

Elasticsearch Installation

Before installing Elasticsearch, Java must be installed on your system on which you are going to use Elasticsearch.

You can download Elasticsearch from official website Link. At the time of writing this article, I am using Elasticsearch version v8.0.0.

To run Elasticsearch, cd .\bin\ and run elasticsearch.bat file. This will take time start Elasticsearch service. You can check by requesting localhost:9200 with GET method, 9200 is default port for Elasticsearch service.

Now we will create one Index (similar to database) named employees by firing the query localhost:9200/{database_name} eg. localhost:9200/employees.

Lets get started with Go!

First, we will initialize our ES Client connection. you can set the URL configuration using config struct.

Initialization of Elasticsearch

For setting custom config.

We need to make a struct for our model, here we are going to use Employee struct.

Insert Operations

For Inserting one single document in Elasticsearch, we will marshal our data then configure the Index API request using IndexRequest and execute the request.

For inserting multiple documents, we can use same request in loop. In this article, we are going to insert 1000 record in one go. so we needed a JSON file containing such entries.

Lets create one function to read a file and return array of struct EmployeeDetails.

Now lets insert multiple documents.

Search Operations

Now we can search for any document, for that we need to create a search query first and then create an request then execute that request.

Now you can check the response!

You can find the entire source code of this application in the Github Repository.

Thank you !!! .. Feedback will be highly appreciated.

--

--