I'm looking to perform some 'post query' processing on my result set.
I have documents like this:
{
"name": "John Smith",
"levels": [
{
"name": "Gold",
"order": 4.0
},
{
"name": "Bronze",
"order": 2.0
},
{
"name": "Silver",
"order": 3.0
}
]
}
A person can have one or more 'levels' and those levels have an 'order' stored with them.
The idea is, we want to order ALL results by levels.order
DESC (so those Platinum and Gold people come before Silver / Bronze) However, in the results, I want to order the source value ASC (so Bronze is first)
For example, say there's two documents in the index:
[
{
"name": "Craig Jones",
"levels": [
{
"name": "Silver",
"order": 3.0
},
{
"name": "Bronze",
"order": 2.0
}
]
},
{
"name": "John Smith",
"levels": [
{
"name": "Silver",
"order": 3.0
},
{
"name": "Gold",
"order": 4.0
},
{
"name": "Bronze",
"order": 2.0
}
]
}
]
When I hit the _search
api with a sort (but no query)
{
"sort": [
{
"levels.order": {
"nested": {
"path": "levels"
},
"order": "desc"
}
}
]
}
... get my results back (sort of) as expected:
[
{
"name": "John Smith",
"levels": [
{
"name": "Gold",
"order": 4.0
},
{
"name": "Silver",
"order": 3.0
},
{
"name": "Bronze",
"order": 2.0
}
]
},
{
"name": "Craig Jones",
"levels": [
{
"name": "Silver",
"order": 3.0
},
{
"name": "Bronze",
"order": 2.0
}
]
}
]
John Smith, then Craig Jones (because John has Gold) Then, the levels
collection is sorted.
However, what I want to do, is return the hits in the same order, but have the nested levels
collection ordered ASCENDING, so my intended result would be (note the order of `levels is reversed)
[
{
"name": "John Smith",
"levels": [
{
"name": "Bronze",
"order": 2.0
},
{
"name": "Silver",
"order": 3.0
},
{
"name": "Gold",
"order": 4.0
},
]
},
{
"name": "Craig Jones",
"levels": [
{
"name": "Silver",
"order": 3.0
},
{
"name": "Bronze",
"order": 2.0
}
]
}
]
Is this possible to do, or would I need to script this?
Also, possibly related, if I add a query, for example MUST have 'Gold' level, then the ordering of the levels collection isn't respected in the sort:
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "levels",
"query": {
"bool": {
"must": [
{
"term": {
"levels.name.keyword": {
"value": "Gold"
}
}
}
]
}
}
}
}
]
}
},
"size": 10,
"sort": [
{
"levels.order": {
"nested": {
"path": "levels"
},
"order": "desc"
}
}
]
}
The resulting levels collection of the first doc is in the order they were inserted:
"levels": [
{
"name": "Silver",
"order": 3.0
},
{
"name": "Gold",
"order": 4.0
},
{
"name": "Bronze",
"order":
The mapping for this index is below:
{
"index-name": {
"mappings": {
"properties": {
"levels": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"order": {
"type": "double"
}
}
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "case_insensitive_normalizer"
}
}
},
}
}
}
}