nested-aggregation.asciidoc 2.3 KB

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