问题
So, i have 1 field, we can call it timeInt. the type value is integer. The value is counted from 0. And i want to sort it with priority condition. 0 / 1 will be placed on the top then the bigger value is placed after value 0 / 1. Ex:
0 1 100 99 98 etc...
I don't know how can i achieve that, i already search on google, and still stucked, i just try query sort like this:
sort:[{timeInt:{'order':'asc'}}]
but it just ascending sort
let newQuery = {
index: `${config.get('/indexElastic').needAction}`,
type: 'notification',
body: {
from: from, size: size,
query: match_all: {},
sort:[{timeInt:{'order':'asc'}}]
}
};
Expected result:
0 1 100 99 98 etc...
Current result:
0 1 2 3 4 etc...
回答1:
You can apply boost to the values 0
and 1
in a should and then modify your sort query by including _score
field as shown below.
Also looking at your expected result, the sorting order for timeInt
would be desc
and not asc
.
POST <your_index_name>/_search
{
"query": {
"bool": {
"should": [
{
"match_all": {}
},
{
"match": {
"timeInt": {
"query": 0,
"boost": 3
}
}
},
{
"match": {
"timeInt": {
"query": 1,
"boost": 2
}
}
}
]
}
},
"sort": [
{ "_score": "desc"},
{
"timeInt": {
"order": "desc"
}
}
]
}
Below is how your results would appear:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 5,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "myintindex",
"_type" : "_doc",
"_id" : "2",
"_score" : 4.0,
"_source" : {
"timeInt" : 0
},
"sort" : [
4.0,
0
]
},
{
"_index" : "myintindex",
"_type" : "_doc",
"_id" : "1",
"_score" : 3.0,
"_source" : {
"timeInt" : 1
},
"sort" : [
3.0,
1
]
},
{
"_index" : "myintindex",
"_type" : "_doc",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"timeInt" : 99
},
"sort" : [
1.0,
99
]
},
{
"_index" : "myintindex",
"_type" : "_doc",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"timeInt" : 98
},
"sort" : [
1.0,
98
]
},
{
"_index" : "myintindex",
"_type" : "_doc",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"timeInt" : 97
},
"sort" : [
1.0,
97
]
}
]
}
}
Note: All the other documents have the _score
of 1
, because of the match_all query.
Let me know if this helps!
来源:https://stackoverflow.com/questions/57518283/elastic-sorting-value-with-priority