In this tutorial, we will learn how to create index, mappings, save, retrieve, update, delete data in Elasticsearch.
Elasticsearch is an open-source, distributed, full-text search and analytics engine. Elasticsearch is built on Apache Lucene Library and is developed in Java. The first version of Elasticsearch was released in 2010.
Elasticsearch is used for log analytics, application performance monitoring, geospatial data analysis and visualization, business analysis, security analysis, etc.
Data retrieval from relational databases are comparatively slow when it comes to large data. Elasticsearch is fast and scalable. One of the main reasons for using Elasticsearch is that it promotes quick retrieval of data.
Elasticsearch is one of the components of Elastic Stack. Elastic Stack also known as ELK Stack (Elasticsearch Logstash Kibana) is a set of open source tools for data ingestion, storage, analysis and visualization.
Logstash is a free tool that can be used for ingesting data into the Elasticsearch.
Kibana is a free tool that sits on top of the Elastic Stack. It provides search and data visualization capabilities for data indexed in Elasticsearch.
Follow the steps below to complete this tutorial:
An Elasticsearch index is a collecton of documents with related data. In other words, an index is a table of a database. In Elasticsearch, data are stored as JSON documents.
Index mapping is the process of defining a document with fields. Each document is a collection of fields having their own data type.
To create an Elasticsearch index with mappings, do the following:
Note: Once index is created, we cannot change the type of a field. To change the type of a field, we need to delete the existing index and create a new one.
PUT /user
{
"settings": {
"number_of_shards": 10,
"number_of_replicas": 2
},
"mappings": {
"properties": {
"first_name": {
"type": "text",
"store": true
},
"last_name": {
"type": "text",
"store": true
},
"balance": {
"type": "double"
},
"age": {
"type": "integer"
},
"location": {
"type": "geo_point"
},
"is_active": {
"type": "boolean"
},
"create_date": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ssZZZZZ"
}
}
}
}
Refer to the image below for example:
To add data to your Elasticsearch index, send POST request with body as shown below:
POST user/_doc/1
{
"first_name": "Danny",
"last_name": "Test",
"balance": "2066643.27",
"location": {
"lat": 41.12,
"lon": -71.34
},
"is_active": false,
"create_date": "2021-05-07 14:11:44+00:00"
}
To retrieve data all data, make GET request as shown below:
GET user/_search
To retrieve data by id, make GET request as shown below:
GET user/_search?q=_id:1
To retrieve data by balance having value 0 to 3000000 value, make GET request as shown below:
GET user/_search?q=balance:["0" TO "3000000"]
To retrieve data by date range value, make GET request as shown below:
GET user/_search?q=create_date["2021-05-03" TO *]
To delete index in Elasticsearch, make DELETE request as shown below:
DELETE user