nested-aggregation.asciidoc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. [[search-aggregations-bucket-nested-aggregation]]
  2. === Nested aggregation
  3. ++++
  4. <titleabbrev>Nested</titleabbrev>
  5. ++++
  6. A special single bucket aggregation that enables aggregating nested documents.
  7. For example, lets say we have an index of products, and each product holds the list of resellers - each having its own
  8. price for the product. The mapping could look like:
  9. [source,console,id=nested-aggregation-example]
  10. --------------------------------------------------
  11. PUT /products
  12. {
  13. "mappings": {
  14. "properties": {
  15. "resellers": { <1>
  16. "type": "nested",
  17. "properties": {
  18. "reseller": { "type": "text" },
  19. "price": { "type": "double" }
  20. }
  21. }
  22. }
  23. }
  24. }
  25. --------------------------------------------------
  26. <1> `resellers` is an array that holds nested documents.
  27. The following request adds a product with two resellers:
  28. [source,console]
  29. --------------------------------------------------
  30. PUT /products/_doc/0
  31. {
  32. "name": "LED TV", <1>
  33. "resellers": [
  34. {
  35. "reseller": "companyA",
  36. "price": 350
  37. },
  38. {
  39. "reseller": "companyB",
  40. "price": 500
  41. }
  42. ]
  43. }
  44. --------------------------------------------------
  45. // TEST[s/PUT \/products\/_doc\/0/PUT \/products\/_doc\/0\?refresh/]
  46. // TEST[continued]
  47. <1> We are using a dynamic mapping for the `name` attribute.
  48. The following request returns the minimum price a product can be purchased for:
  49. [source,console]
  50. --------------------------------------------------
  51. GET /products/_search
  52. {
  53. "query": {
  54. "match": { "name": "led tv" }
  55. },
  56. "aggs": {
  57. "resellers": {
  58. "nested": {
  59. "path": "resellers"
  60. },
  61. "aggs": {
  62. "min_price": { "min": { "field": "resellers.price" } }
  63. }
  64. }
  65. }
  66. }
  67. --------------------------------------------------
  68. // TEST[s/GET \/products\/_search/GET \/products\/_search\?filter_path=aggregations/]
  69. // TEST[continued]
  70. As you can see above, the nested aggregation requires the `path` of the nested documents within the top level documents.
  71. Then one can define any type of aggregation over these nested documents.
  72. Response:
  73. [source,console-result]
  74. --------------------------------------------------
  75. {
  76. ...
  77. "aggregations": {
  78. "resellers": {
  79. "doc_count": 2,
  80. "min_price": {
  81. "value": 350
  82. }
  83. }
  84. }
  85. }
  86. --------------------------------------------------
  87. // TESTRESPONSE[s/\.\.\.//]
  88. // TESTRESPONSE[s/: [0-9]+/: $body.$_path/]