如果你想知道是否可以对数组进行排序,答案是肯定的。使用 sort 处理器,我们可以按升序或降序对元素数组进行排序。对数组的元素进行升序或降序排序。 同构数字数组将按数字排序,而字符串数组或字符串+数字的异构数组将按字典顺序排序。 当字段不是数组时抛出错误。
让我们运行两个示例:字符串数组和数值数组。
数组字符串
在 array_field_to_sort 字段中,我们有值 amber、simon、back,我们将按升序排序以获得排序:amber”、back、simon。
`
1. POST /_ingest/pipeline/_simulate?verbose=true
2. {
3. "pipeline": {
4. "description": "sort array string",
5. "processors": [
6. {
7. "sort": {
8. "field": "array_field_to_sort",
9. "order": "asc"
10. }
11. }
12. ]
13. },
14. "docs": [
15. {
16. "_index": "index",
17. "_id": "id",
18. "_source": {
19. "array_field_to_sort": [
20. "amber", "simon", "back"
21. ]
22. }
23. }
24. ]
25. }
`
上述命令的输出为:
`
1. {
2. "docs": [
3. {
4. "processor_results": [
5. {
6. "processor_type": "sort",
7. "status": "success",
8. "doc": {
9. "_index": "index",
10. "_id": "id",
11. "_version": "-3",
12. "_source": {
13. "array_field_to_sort": [
14. "amber",
15. "back",
16. "simon"
17. ]
18. },
19. "_ingest": {
20. "pipeline": "_simulate_pipeline",
21. "timestamp": "2023-02-03T07:51:04.618494501Z"
22. }
23. }
24. }
25. ]
26. }
27. ]
28. }
`
从输出中,我们可以看出来字符串是安装升序来进行排列的。
数值数组
现在让我们使用一个内部数组。 元素 5、2、1、12 ,20 将按 1、2、5、12 ,20 的升序排序。
`
1. POST /_ingest/pipeline/_simulate?verbose=true
2. {
3. "pipeline": {
4. "description": "sort array numeric",
5. "processors": [
6. {
7. "sort": {
8. "field": "array_field_to_sort",
9. "order": "asc"
10. }
11. }
12. ]
13. },
14. "docs": [
15. {
16. "_index": "index",
17. "_id": "id",
18. "_source": {
19. "array_field_to_sort": [
20. 5,
21. 2,
22. 1,
23. 12,
24. 20
25. ]
26. }
27. }
28. ]
29. }
`
上述命令的输出为:
`
1. {
2. "docs": [
3. {
4. "processor_results": [
5. {
6. "processor_type": "sort",
7. "status": "success",
8. "doc": {
9. "_index": "index",
10. "_id": "id",
11. "_version": "-3",
12. "_source": {
13. "array_field_to_sort": [
14. 1,
15. 2,
16. 5,
17. 12,
18. 20
19. ]
20. },
21. "_ingest": {
22. "pipeline": "_simulate_pipeline",
23. "timestamp": "2023-02-03T07:53:13.517706963Z"
24. }
25. }
26. }
27. ]
28. }
29. ]
30. }
`