Babilu Daniel
Babilu Daniel

Reputation: 53

How to sort the fields when the numbers are entered as strings,in elasticsearch?

This is a sample of the document I have indexed using elasticsearch.

{

"itemName": "refridgirator"
"brand": "samsung"
"price": "1600"
"emi": "40"
"location":"Brisbane"
}

As you can see from the above document that,all the numerical fields such as "price" and "emi" are entered as strings. Now as I need to sort my indexed documents in the basis of this value,Im not able to do that. How can I make it done?

Upvotes: 3

Views: 4566

Answers (2)

Vineeth Mohan
Vineeth Mohan

Reputation: 19253

In the mapping , you need to specify this as long or int. That way , the number would be stored as long in the reverse index and field data cache and actual number sort will work out -

curl -X PUT "http://$hostname:9200/your_index/your_type/_mapping" -d '{
  "yout_type": {
    "properties": {
      "price": {
        "type": "long"
      }
    }
  }
}'

You can find more info here. Also an alternate method by parsing string values have been discussed in detail in this blog

Upvotes: 4

Val
Val

Reputation: 217314

In your mapping, you need to declare the price and emi fields as number type (double, float, integer, etc) like this:

// remove the current index
curl -XDELETE localhost:9200/your_index

// create the index anew
curl -XPUT localhost:9200/your_index -d '
{
  "mappings": {
    "your_type": {
      "properties": {
        "itemName": {
          "type": "string"
        },
        "brand": {
          "type": "string"
        },
        "price": {
          "type": "double"
        },
        "emi": {
          "type": "integer"
        },
        "location": {
          "type": "string"
        }
      }
    }
  }
}'

And then when you re-index your documents, make sure the price and emi fields in your JSON are numbers as well and not strings (i.e. without the double quotes):

curl -XPOST localhost:9200/your_index/your_type/123 -d '
{
  "itemName": "refridgirator",
  "brand": "samsung",
  "price": 1600,
  "emi": 40,
  "location": "Brisbane"
}'

Upvotes: 1

Related Questions