Gopal
Gopal

Reputation: 31

Sorting on field which in text data type but integer will be store in Elastic Search

we have a field in index - TempNo which has to be text type but all values in this field are number (integer)

When i am doing sorting (desc) on this field , sort does not happen correctly. I am not getting result in desc order of TempNo.

It seems it is because of text type . How can I sort it correctly ? (type is text but sorting should happen based on Number)

Thanks, Gopal

Upvotes: 0

Views: 752

Answers (1)

YouXiang-Wang
YouXiang-Wang

Reputation: 1127

Actually, if the type is text, ElasticSearch does not do any Sort/Agg operations for you.

There are 2 ways to make some changes.

1. Change the TempNo from text to integer directly. (It will sort correctly)

2. Add Raw type for TempNo if you must use the text,(https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html), and then use the painless for sorting by number.

GET my_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "Number",
      "order": "desc",
      "script": {
        "lang": "painless",
        "source": """
        String s = doc['TempNo'].value;
          int tdvalue = Integer.parseInt(s);
          return tdvalue;
        """
      }
    }
  }
}

Upvotes: 1

Related Questions