问题
I have a Elastic search mapping as below. The filed amount is of type keyword
{
"claims-service":{
"mappings":{
"properties":{
"requestedAmount":{
"properties":{
"amount":{
"type":"keyword"
}
}
}
}
}
}
}
But when i try to sort it using the below mentioned query, it's not sorting the ascending order.
GET /claims-service/_search
{
"size": 770,
"query": {
"match_all": {}
},
"sort": [
{
"requestedAmount.amount": {
"order": "asc"
}
}
]
}
The result i'm getting is like below. As you see clearly i'm trying to sort it in ascending order, but its giving me the wrong result.
{
"_index" : "claims-service",
"_type" : "_doc",
"_id" : "79600",
"_score" : null,
"_source" : {
"id" : "79600",
"requestedAmount" : {
"amount" : "101402.310000"
}
},
"sort" : [
"101402.310000"
]
},
{
"_index" : "claims-service",
"_type" : "_doc",
"_id" : "76800",
"_score" : null,
"_source" : {
"id" : "76800",
"requestedAmount" : {
"amount" : "104.160000"
},
"sort" : [
"104.160000"
]
},
{
"_index" : claims-service",
"_type" : "_doc",
"_id" : "72750",
"_score" : null,
"_source" : {
"id" : "72750",
"requestedAmount" : {
"amount" : "104.391000"
},
"sort" : [
"104.391000"
]
},
{
"_index" : "claims-service",
"_type" : "_doc",
"_id" : "79900",
"_score" : null,
"_source" : {
"id" : "79900",
},
"sort" : [
"104909.340000"
]
}
As you can make out by looking into sort field, the values are actually displayed as ["101402.310000", "104.391000", "104909.340000"]
回答1:
Being of type keyword, the amount field is sorted in lexicographical order (i.e. alphabetic order), which is consistent with what you're seeing.
If you want to sort in numerical order, you need to use a numeric data type, such as double for instance. You can keep your keyword field and add a sub-field of type double. After changing the mapping in that
PUT claims-service/_mapping
{
"properties": {
"requestedAmount": {
"properties": {
"amount": {
"type": "keyword",
"fields": {
"numeric": {
"type": "double"
}
}
}
}
}
}
}
After changing your mapping with the above command, you can run the next
command in order to index the amount.numeric sub-field
POST claims-service/_update_by_query
You'll then be able to use that new field for properly sorting the data.
"sort": [
{
"requestedAmount.amount.numeric": {
"order": "asc"
}
}
]
来源:https://stackoverflow.com/questions/65663222/elastic-search-not-sorting-correctly