Reputation: 1343
I'm using Elasticsearch 6 with PHP.
My document has a nested field like this:
"prices" : {
"type" : "nested",
"properties" : {
"date" : {
"type" : "date"
},
"duration" : {
"type" : "short"
},
"persons" : {
"type" : "short"
},
"pets" : {
"type" : "short"
},
"price" : {
"type" : "float"
}
}
Basically every document has a lot of prices, but I know that only one price per document will match the filter/query.
I use this to search and sort, adapted from the tutorial here: https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-sorting.html (sorry for PHP array format):
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
'nested' => [
'path' => 'prices',
'query' => [
'bool' => [
'must' => [
['match' => ['prices.duration' => 14]],
['match' => ['prices.date' => '2018-09-01']],
['match' => ['prices.pets' => 2]],
['match' => ['prices.persons' => 2,]]
]
]
]
]
],
'sort' => [
'prices.price' => [
'order' => 'asc',
'mode' => 'min',
'nested_filter' => [
'bool' => [
'must' => [
['match' => ['prices.duration' => 14]],
['match' => ['prices.date' => '2018-09-01']],
['match' => ['prices.pets' => 2]],
['match' => ['prices.persons' => 2]]
]
]
]
]
]
]
];
I get the correct results, but the documents are not sorted by price. How can I correctly sort them? The documents should be sorted by the one price that matches the filter.
Upvotes: 5
Views: 2406
Reputation: 1343
Apparently I was using an old documentation. The correct sort part of the query above is:
'sort' => [
'prices.price' => [
'order' => 'asc',
'mode' => 'avg',
'nested' => [
'path' => 'prices',
'filter' => [
'bool' => [
'must' => [
['match' => ['prices.duration' => 14]],
['match' => ['prices.date' => '2018-09-01']],
['match' => ['prices.pets' => 2]],
['match' => ['prices.persons' => 2]]
]
]
]
]
]
]
Upvotes: 4