sort.asciidoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. [[sort-search-results]]
  2. == Sort search results
  3. Allows you to add one or more sorts on specific fields. Each sort can be
  4. reversed as well. The sort is defined on a per field level, with special
  5. field name for `_score` to sort by score, and `_doc` to sort by index order.
  6. Assuming the following index mapping:
  7. [source,console]
  8. --------------------------------------------------
  9. PUT /my-index-000001
  10. {
  11. "mappings": {
  12. "properties": {
  13. "post_date": { "type": "date" },
  14. "user": {
  15. "type": "keyword"
  16. },
  17. "name": {
  18. "type": "keyword"
  19. },
  20. "age": { "type": "integer" }
  21. }
  22. }
  23. }
  24. --------------------------------------------------
  25. [source,console]
  26. --------------------------------------------------
  27. GET /my-index-000001/_search
  28. {
  29. "sort" : [
  30. { "post_date" : {"order" : "asc"}},
  31. "user",
  32. { "name" : "desc" },
  33. { "age" : "desc" },
  34. "_score"
  35. ],
  36. "query" : {
  37. "term" : { "user" : "kimchy" }
  38. }
  39. }
  40. --------------------------------------------------
  41. // TEST[continued]
  42. NOTE: `_doc` has no real use-case besides being the most efficient sort order.
  43. So if you don't care about the order in which documents are returned, then you
  44. should sort by `_doc`. This especially helps when <<request-body-search-scroll,scrolling>>.
  45. [discrete]
  46. === Sort Values
  47. The sort values for each document returned are also returned as part of
  48. the response.
  49. [discrete]
  50. === Sort Order
  51. The `order` option can have the following values:
  52. [horizontal]
  53. `asc`:: Sort in ascending order
  54. `desc`:: Sort in descending order
  55. The order defaults to `desc` when sorting on the `_score`, and defaults
  56. to `asc` when sorting on anything else.
  57. [discrete]
  58. === Sort mode option
  59. Elasticsearch supports sorting by array or multi-valued fields. The `mode` option
  60. controls what array value is picked for sorting the document it belongs
  61. to. The `mode` option can have the following values:
  62. [horizontal]
  63. `min`:: Pick the lowest value.
  64. `max`:: Pick the highest value.
  65. `sum`:: Use the sum of all values as sort value. Only applicable for
  66. number based array fields.
  67. `avg`:: Use the average of all values as sort value. Only applicable
  68. for number based array fields.
  69. `median`:: Use the median of all values as sort value. Only applicable
  70. for number based array fields.
  71. The default sort mode in the ascending sort order is `min` -- the lowest value
  72. is picked. The default sort mode in the descending order is `max` --
  73. the highest value is picked.
  74. [discrete]
  75. ==== Sort mode example usage
  76. In the example below the field price has multiple prices per document.
  77. In this case the result hits will be sorted by price ascending based on
  78. the average price per document.
  79. [source,console]
  80. --------------------------------------------------
  81. PUT /my-index-000001/_doc/1?refresh
  82. {
  83. "product": "chocolate",
  84. "price": [20, 4]
  85. }
  86. POST /_search
  87. {
  88. "query" : {
  89. "term" : { "product" : "chocolate" }
  90. },
  91. "sort" : [
  92. {"price" : {"order" : "asc", "mode" : "avg"}}
  93. ]
  94. }
  95. --------------------------------------------------
  96. [discrete]
  97. === Sorting numeric fields
  98. For numeric fields it is also possible to cast the values from one type
  99. to another using the `numeric_type` option.
  100. This option accepts the following values: [`"double", "long", "date", "date_nanos"`]
  101. and can be useful for searches across multiple data streams or indices where the sort field is mapped differently.
  102. Consider for instance these two indices:
  103. [source,console]
  104. --------------------------------------------------
  105. PUT /index_double
  106. {
  107. "mappings": {
  108. "properties": {
  109. "field": { "type": "double" }
  110. }
  111. }
  112. }
  113. --------------------------------------------------
  114. [source,console]
  115. --------------------------------------------------
  116. PUT /index_long
  117. {
  118. "mappings": {
  119. "properties": {
  120. "field": { "type": "long" }
  121. }
  122. }
  123. }
  124. --------------------------------------------------
  125. // TEST[continued]
  126. Since `field` is mapped as a `double` in the first index and as a `long`
  127. in the second index, it is not possible to use this field to sort requests
  128. that query both indices by default. However you can force the type to one
  129. or the other with the `numeric_type` option in order to force a specific
  130. type for all indices:
  131. [source,console]
  132. --------------------------------------------------
  133. POST /index_long,index_double/_search
  134. {
  135. "sort" : [
  136. {
  137. "field" : {
  138. "numeric_type" : "double"
  139. }
  140. }
  141. ]
  142. }
  143. --------------------------------------------------
  144. // TEST[continued]
  145. In the example above, values for the `index_long` index are casted to
  146. a double in order to be compatible with the values produced by the
  147. `index_double` index.
  148. It is also possible to transform a floating point field into a `long`
  149. but note that in this case floating points are replaced by the largest
  150. value that is less than or equal (greater than or equal if the value
  151. is negative) to the argument and is equal to a mathematical integer.
  152. This option can also be used to convert a `date` field that uses millisecond
  153. resolution to a `date_nanos` field with nanosecond resolution.
  154. Consider for instance these two indices:
  155. [source,console]
  156. --------------------------------------------------
  157. PUT /index_double
  158. {
  159. "mappings": {
  160. "properties": {
  161. "field": { "type": "date" }
  162. }
  163. }
  164. }
  165. --------------------------------------------------
  166. [source,console]
  167. --------------------------------------------------
  168. PUT /index_long
  169. {
  170. "mappings": {
  171. "properties": {
  172. "field": { "type": "date_nanos" }
  173. }
  174. }
  175. }
  176. --------------------------------------------------
  177. // TEST[continued]
  178. Values in these indices are stored with different resolutions so sorting on these
  179. fields will always sort the `date` before the `date_nanos` (ascending order).
  180. With the `numeric_type` type option it is possible to set a single resolution for
  181. the sort, setting to `date` will convert the `date_nanos` to the millisecond resolution
  182. while `date_nanos` will convert the values in the `date` field to the nanoseconds resolution:
  183. [source,console]
  184. --------------------------------------------------
  185. POST /index_long,index_double/_search
  186. {
  187. "sort" : [
  188. {
  189. "field" : {
  190. "numeric_type" : "date_nanos"
  191. }
  192. }
  193. ]
  194. }
  195. --------------------------------------------------
  196. // TEST[continued]
  197. [WARNING]
  198. To avoid overflow, the conversion to `date_nanos` cannot be applied on dates before
  199. 1970 and after 2262 as nanoseconds are represented as longs.
  200. [discrete]
  201. [[nested-sorting]]
  202. === Sorting within nested objects.
  203. Elasticsearch also supports sorting by
  204. fields that are inside one or more nested objects. The sorting by nested
  205. field support has a `nested` sort option with the following properties:
  206. `path`::
  207. Defines on which nested object to sort. The actual
  208. sort field must be a direct field inside this nested object.
  209. When sorting by nested field, this field is mandatory.
  210. `filter`::
  211. A filter that the inner objects inside the nested path
  212. should match with in order for its field values to be taken into account
  213. by sorting. Common case is to repeat the query / filter inside the
  214. nested filter or query. By default no `filter` is active.
  215. `max_children`::
  216. The maximum number of children to consider per root document
  217. when picking the sort value. Defaults to unlimited.
  218. `nested`::
  219. Same as top-level `nested` but applies to another nested path within the
  220. current nested object.
  221. NOTE: Elasticsearch will throw an error if a nested field is defined in a sort without
  222. a `nested` context.
  223. [discrete]
  224. ==== Nested sorting examples
  225. In the below example `offer` is a field of type `nested`.
  226. The nested `path` needs to be specified; otherwise, Elasticsearch doesn't know on what nested level sort values need to be captured.
  227. [source,console]
  228. --------------------------------------------------
  229. POST /_search
  230. {
  231. "query" : {
  232. "term" : { "product" : "chocolate" }
  233. },
  234. "sort" : [
  235. {
  236. "offer.price" : {
  237. "mode" : "avg",
  238. "order" : "asc",
  239. "nested": {
  240. "path": "offer",
  241. "filter": {
  242. "term" : { "offer.color" : "blue" }
  243. }
  244. }
  245. }
  246. }
  247. ]
  248. }
  249. --------------------------------------------------
  250. In the below example `parent` and `child` fields are of type `nested`.
  251. The `nested.path` needs to be specified at each level; otherwise, Elasticsearch doesn't know on what nested level sort values need to be captured.
  252. [source,console]
  253. --------------------------------------------------
  254. POST /_search
  255. {
  256. "query": {
  257. "nested": {
  258. "path": "parent",
  259. "query": {
  260. "bool": {
  261. "must": {"range": {"parent.age": {"gte": 21}}},
  262. "filter": {
  263. "nested": {
  264. "path": "parent.child",
  265. "query": {"match": {"parent.child.name": "matt"}}
  266. }
  267. }
  268. }
  269. }
  270. }
  271. },
  272. "sort" : [
  273. {
  274. "parent.child.age" : {
  275. "mode" : "min",
  276. "order" : "asc",
  277. "nested": {
  278. "path": "parent",
  279. "filter": {
  280. "range": {"parent.age": {"gte": 21}}
  281. },
  282. "nested": {
  283. "path": "parent.child",
  284. "filter": {
  285. "match": {"parent.child.name": "matt"}
  286. }
  287. }
  288. }
  289. }
  290. }
  291. ]
  292. }
  293. --------------------------------------------------
  294. Nested sorting is also supported when sorting by
  295. scripts and sorting by geo distance.
  296. [discrete]
  297. === Missing Values
  298. The `missing` parameter specifies how docs which are missing
  299. the sort field should be treated: The `missing` value can be
  300. set to `_last`, `_first`, or a custom value (that
  301. will be used for missing docs as the sort value).
  302. The default is `_last`.
  303. For example:
  304. [source,console]
  305. --------------------------------------------------
  306. GET /_search
  307. {
  308. "sort" : [
  309. { "price" : {"missing" : "_last"} }
  310. ],
  311. "query" : {
  312. "term" : { "product" : "chocolate" }
  313. }
  314. }
  315. --------------------------------------------------
  316. NOTE: If a nested inner object doesn't match with
  317. the `nested.filter` then a missing value is used.
  318. [discrete]
  319. === Ignoring Unmapped Fields
  320. By default, the search request will fail if there is no mapping
  321. associated with a field. The `unmapped_type` option allows you to ignore
  322. fields that have no mapping and not sort by them. The value of this
  323. parameter is used to determine what sort values to emit. Here is an
  324. example of how it can be used:
  325. [source,console]
  326. --------------------------------------------------
  327. GET /_search
  328. {
  329. "sort" : [
  330. { "price" : {"unmapped_type" : "long"} }
  331. ],
  332. "query" : {
  333. "term" : { "product" : "chocolate" }
  334. }
  335. }
  336. --------------------------------------------------
  337. If any of the indices that are queried doesn't have a mapping for `price`
  338. then Elasticsearch will handle it as if there was a mapping of type
  339. `long`, with all documents in this index having no value for this field.
  340. [discrete]
  341. [[geo-sorting]]
  342. === Geo Distance Sorting
  343. Allow to sort by `_geo_distance`. Here is an example, assuming `pin.location` is a field of type `geo_point`:
  344. [source,console]
  345. --------------------------------------------------
  346. GET /_search
  347. {
  348. "sort" : [
  349. {
  350. "_geo_distance" : {
  351. "pin.location" : [-70, 40],
  352. "order" : "asc",
  353. "unit" : "km",
  354. "mode" : "min",
  355. "distance_type" : "arc",
  356. "ignore_unmapped": true
  357. }
  358. }
  359. ],
  360. "query" : {
  361. "term" : { "user" : "kimchy" }
  362. }
  363. }
  364. --------------------------------------------------
  365. `distance_type`::
  366. How to compute the distance. Can either be `arc` (default), or `plane` (faster, but inaccurate on long distances and close to the poles).
  367. `mode`::
  368. What to do in case a field has several geo points. By default, the shortest
  369. distance is taken into account when sorting in ascending order and the
  370. longest distance when sorting in descending order. Supported values are
  371. `min`, `max`, `median` and `avg`.
  372. `unit`::
  373. The unit to use when computing sort values. The default is `m` (meters).
  374. `ignore_unmapped`::
  375. Indicates if the unmapped field should be treated as a missing value. Setting it to `true` is equivalent to specifying
  376. an `unmapped_type` in the field sort. The default is `false` (unmapped field cause the search to fail).
  377. NOTE: geo distance sorting does not support configurable missing values: the
  378. distance will always be considered equal to +Infinity+ when a document does not
  379. have values for the field that is used for distance computation.
  380. The following formats are supported in providing the coordinates:
  381. [discrete]
  382. ==== Lat Lon as Properties
  383. [source,console]
  384. --------------------------------------------------
  385. GET /_search
  386. {
  387. "sort" : [
  388. {
  389. "_geo_distance" : {
  390. "pin.location" : {
  391. "lat" : 40,
  392. "lon" : -70
  393. },
  394. "order" : "asc",
  395. "unit" : "km"
  396. }
  397. }
  398. ],
  399. "query" : {
  400. "term" : { "user" : "kimchy" }
  401. }
  402. }
  403. --------------------------------------------------
  404. [discrete]
  405. ==== Lat Lon as String
  406. Format in `lat,lon`.
  407. [source,console]
  408. --------------------------------------------------
  409. GET /_search
  410. {
  411. "sort": [
  412. {
  413. "_geo_distance": {
  414. "pin.location": "40,-70",
  415. "order": "asc",
  416. "unit": "km"
  417. }
  418. }
  419. ],
  420. "query": {
  421. "term": { "user": "kimchy" }
  422. }
  423. }
  424. --------------------------------------------------
  425. [discrete]
  426. ==== Geohash
  427. [source,console]
  428. --------------------------------------------------
  429. GET /_search
  430. {
  431. "sort": [
  432. {
  433. "_geo_distance": {
  434. "pin.location": "drm3btev3e86",
  435. "order": "asc",
  436. "unit": "km"
  437. }
  438. }
  439. ],
  440. "query": {
  441. "term": { "user": "kimchy" }
  442. }
  443. }
  444. --------------------------------------------------
  445. [discrete]
  446. ==== Lat Lon as Array
  447. Format in `[lon, lat]`, note, the order of lon/lat here in order to
  448. conform with http://geojson.org/[GeoJSON].
  449. [source,console]
  450. --------------------------------------------------
  451. GET /_search
  452. {
  453. "sort": [
  454. {
  455. "_geo_distance": {
  456. "pin.location": [ -70, 40 ],
  457. "order": "asc",
  458. "unit": "km"
  459. }
  460. }
  461. ],
  462. "query": {
  463. "term": { "user": "kimchy" }
  464. }
  465. }
  466. --------------------------------------------------
  467. [discrete]
  468. === Multiple reference points
  469. Multiple geo points can be passed as an array containing any `geo_point` format, for example
  470. [source,console]
  471. --------------------------------------------------
  472. GET /_search
  473. {
  474. "sort": [
  475. {
  476. "_geo_distance": {
  477. "pin.location": [ [ -70, 40 ], [ -71, 42 ] ],
  478. "order": "asc",
  479. "unit": "km"
  480. }
  481. }
  482. ],
  483. "query": {
  484. "term": { "user": "kimchy" }
  485. }
  486. }
  487. --------------------------------------------------
  488. and so forth.
  489. The final distance for a document will then be `min`/`max`/`avg` (defined via `mode`) distance of all points contained in the document to all points given in the sort request.
  490. [discrete]
  491. === Script Based Sorting
  492. Allow to sort based on custom scripts, here is an example:
  493. [source,console]
  494. --------------------------------------------------
  495. GET /_search
  496. {
  497. "query": {
  498. "term": { "user": "kimchy" }
  499. },
  500. "sort": {
  501. "_script": {
  502. "type": "number",
  503. "script": {
  504. "lang": "painless",
  505. "source": "doc['field_name'].value * params.factor",
  506. "params": {
  507. "factor": 1.1
  508. }
  509. },
  510. "order": "asc"
  511. }
  512. }
  513. }
  514. --------------------------------------------------
  515. [discrete]
  516. === Track Scores
  517. When sorting on a field, scores are not computed. By setting
  518. `track_scores` to true, scores will still be computed and tracked.
  519. [source,console]
  520. --------------------------------------------------
  521. GET /_search
  522. {
  523. "track_scores": true,
  524. "sort" : [
  525. { "post_date" : {"order" : "desc"} },
  526. { "name" : "desc" },
  527. { "age" : "desc" }
  528. ],
  529. "query" : {
  530. "term" : { "user" : "kimchy" }
  531. }
  532. }
  533. --------------------------------------------------
  534. [discrete]
  535. === Memory Considerations
  536. When sorting, the relevant sorted field values are loaded into memory.
  537. This means that per shard, there should be enough memory to contain
  538. them. For string based types, the field sorted on should not be analyzed
  539. / tokenized. For numeric types, if possible, it is recommended to
  540. explicitly set the type to narrower types (like `short`, `integer` and
  541. `float`).