OneCompiler

Elasticsearch basic queries

343

Install Elasticsearch

  1. Install ElasticSearch

brew install elasticsearch

  1. Start Elasticsearch by assigning a name to cluster and node

./elasticsearch -Ecluster.name=my_cluster -Enode.name=my_node

Check Health

  1. Check node and cluster info

http://localhost:9200/ link

  1. Check the health of the cluster

http://localhost:9200/_cat/health?v link

  1. Get list of nodes of a cluster

http://localhost:9200/_cat/nodes?v link

  1. Get all indexes of a cluster

http://localhost:9200/_cat/indices?v link

Install Kibana

  1. Install Kibana

brew install kibana

  1. Start Kibana

brew services start kibana

After installing Kibana (UI tool for Elasticsearch), go to DevTools, There is a console section.

CRUD Operations

Note 1: Insert Data or Indexing is only possible in primary shards, but search request or querying data is taken care of both primary shards and replica shards.

Note 2: By default elasticsearch cluster will create 5 primary shards and 1 replica for each shard, so totally it creates 10 shards (5 primary shards + 5 replica shards), primary shard and replica shard should not be present in the same node.

Note 3: In a single node cluster, each index it creates 5 primary shards in the same node, but replica shards won't create up to add one more node to cluster, so the status of an index will be yellow because of no replicas present.

Get all indexes

  1. Get all indexes
 GET /_cat/indices?v
 curl -X GET "localhost:9200/_cat/indices?v" 

Create Index

We can create an index from the REST call or from the console also.

  1. Create Index with name 'students' (Remember all index names must be lower case only)
PUT /students?pretty

curl -X PUT "localhost:9200/students?pretty" 



### Insert data to Index

** Note: ** If we not create an index, and try to insert data into a non-existing index, cluster automatically creates an index.

11. Insert document with id

 ```json
PUT /student/_doc/1?pretty
{
  "name": "Foo"
}

```json 
 curl -X PUT "localhost:9200/student/_doc/1?pretty" 
 -H 'Content-Type: application/json' -d
 '{
   "name": "Foo"
 }'

Get data from Index

  1. Get the document by Id

GET /student/_doc/1?pretty

curl -X GET "localhost:9200/student/_doc/1?pretty"

Delete an Index

  1. Delete index
DELETE /student?pretty
curl -X DELETE "localhost:9200/student?pretty"

All Sample Queries of CRUD

PUT /student
PUT /student/_doc/1
{
 "name": "Foo"
}
GET /student/_doc/1
DELETE /student