Sorting in elasticsearch

Posted By : Tarun Tyagi | 29-Jun-2016

If you want to sort your data in albhabetical older on the bases of particular field then you need to following these steps:

Step 1. You need to do setting of  your index.

curl -XPUT 'http://localhost:9200/your_index_name' -d '{
  "settings": {
    "analysis": {
      "analyzer": {
        "case_insensitive_sort": {
          "tokenizer": "keyword",    
          "filter":  [ "lowercase" ] 
        }
      }
    }
  }
}'
 

 

Step 2 . After update the settings you need to do mapping for your data

for example we have data of students:

{"name":"titu","address":"ghaziabad","rollNo":20}

{"name":"Sonu","address":"agra","rollNo":1}

{"name":"anu","address":"delhi","rollNo":10}

Now we want to sort our data on the bases of name .So mapping is
 curl -XPUT 'http://localhost:9200/your_index_name/_mapping/students' -d '{  
   "properties":{  
      "name":{  
         "type":"string",
         "fields":{  
            "lower_case_sort":{  
               "type":"string",
               "analyzer":"case_insensitive_sort"
            }
         },
         "address":{  
            "type":"string"
         },
         "rollNo":{  
            "type":"long"
         }
      }
   }
}'
 

 

Step 3. After update the maping insert data into elasticsearch

insert data using this api : http://localhost:9200/your_index_name/students/uniqueId

curl -XPUT 'http://localhost:9200/your_index_name/students/1' -d '{"name":"titu","address":"ghaziabad","rollNo":20}'
curl -XPUT 'http://localhost:9200/your_index_name/students/2' -d '{"name":"Sonu","address":"agra","rollNo":1}'
curl -XPUT 'http://localhost:9200/your_index_name/students/3' -d '{"name":"anu","address":"delhi","rollNo":10}'
 

 

Step 4. Get your data in sorting order

 curl -XGET 'http://localhost:9200/your_index_name/students/_search?sort=name.lower_case_sort'
 

 

THANKS

About Author

Author Image
Tarun Tyagi

Tarun is a bright Java developer with experience in MEAN stack and Grails frameworks. Other than programming his area of interest are listening music and reading novels.

Request for Proposal

Name is required

Comment is required

Sending message..