valuecount-aggregation.asciidoc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. [[search-aggregations-metrics-valuecount-aggregation]]
  2. === Value Count Aggregation
  3. A `single-value` metrics aggregation that counts the number of values that are extracted from the aggregated documents.
  4. These values can be extracted either from specific fields in the documents, or be generated by a provided script. Typically,
  5. this aggregator will be used in conjunction with other single-value aggregations. For example, when computing the `avg`
  6. one might be interested in the number of values the average is computed over.
  7. [source,js]
  8. --------------------------------------------------
  9. POST /sales/_search?size=0
  10. {
  11. "aggs" : {
  12. "types_count" : { "value_count" : { "field" : "type" } }
  13. }
  14. }
  15. --------------------------------------------------
  16. // CONSOLE
  17. // TEST[setup:sales]
  18. Response:
  19. [source,js]
  20. --------------------------------------------------
  21. {
  22. ...
  23. "aggregations": {
  24. "types_count": {
  25. "value": 7
  26. }
  27. }
  28. }
  29. --------------------------------------------------
  30. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  31. The name of the aggregation (`types_count` above) also serves as the key by which the aggregation result can be
  32. retrieved from the returned response.
  33. ==== Script
  34. Counting the values generated by a script:
  35. [source,js]
  36. --------------------------------------------------
  37. POST /sales/_search?size=0
  38. {
  39. "aggs" : {
  40. "type_count" : {
  41. "value_count" : {
  42. "script" : {
  43. "source" : "doc['type'].value"
  44. }
  45. }
  46. }
  47. }
  48. }
  49. --------------------------------------------------
  50. // CONSOLE
  51. // TEST[setup:sales]
  52. This will interpret the `script` parameter as an `inline` script with the `painless` script language and no script parameters. To use a stored script use the following syntax:
  53. [source,js]
  54. --------------------------------------------------
  55. POST /sales/_search?size=0
  56. {
  57. "aggs" : {
  58. "types_count" : {
  59. "value_count" : {
  60. "script" : {
  61. "id": "my_script",
  62. "params" : {
  63. "field" : "type"
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. --------------------------------------------------
  71. // CONSOLE
  72. // TEST[setup:sales,stored_example_script]