> ## Documentation Index
> Fetch the complete documentation index at: https://www.algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# (Beta) Query a numeric distribution

> Beta: this endpoint is under active development and may change without notice.

Buckets one or more numeric fields into histograms and returns an object keyed by `histogram<Field>`,
each mapping a bin label to a count. `distributions` and `parameters` are required; `filters` is
optional. Discover valid field kinds per domain with `/3/patterns/fields`.

**Required ACL:** `analytics`


## OpenAPI

````yaml specs/searchstats.yml post /3/patterns/distribution
openapi: 3.1.0
info:
  title: Analytics API
  summary: >-
    The Analytics API gives you access to metrics related to your Algolia search
    experience
  description: >
    ## Base URLs


    Base URLs for the Analytics API:


    - `https://analytics.us.algolia.com`

    - `https://analytics.de.algolia.com`

    - `https://analytics.algolia.com` (alias of `analytics.us.algolia.com`)


    Use the URL that matches your [analytics
    region](https://dashboard.algolia.com/account/infrastructure/analytics).


    **All requests must use HTTPS.**


    ## Availability and authentication


    Access to the Analytics API is available as part of the [Premium or Elevate
    plans](https://www.algolia.com/pricing).


    Add these headers to authenticate requests:


    - `x-algolia-application-id`. Your Algolia application ID.

    - `x-algolia-api-key`. An API key with the necessary permissions to make the
    request.
      The required access control list (ACL) to make a request is listed in each endpoint's reference.

    You can find your application ID and API key in the [Algolia
    dashboard](https://dashboard.algolia.com/account/api-keys).


    ## Rate limits


    You can make up to **100 requests per minute per app** to the Analytics API.

    The response includes headers with information about the limits.


    ## Parameters


    Query parameters must be
    [URL-encoded](https://developer.mozilla.org/en-US/docs/Glossary/Percent-encoding).

    Non-ASCII characters must be UTF-8 encoded.

    Plus characters (`+`) are interpreted as spaces.


    ## Response status and errors


    The Analytics API returns JSON responses.

    Since JSON doesn't guarantee any specific ordering, don't rely on the order
    of attributes in the API response.


    - Successful responses return a `2xx` status

    - Client errors return a `4xx` status

    - Server errors are indicated by a `5xx` status.


    Error responses have a `message` property with more information.


    ## Version


    The current version of the Analytics API is version 2, indicated by the
    `/2/` in each endpoint's URL.


    A Beta semantic patterns framework is also available under `/3/patterns/*`
    for building custom

    analytics queries. These endpoints are under active development and may
    change without notice.


    ## Query aggregation


    Algolia accepts queries on each keystroke.

    To ensure you have relevant analytics data, however, the series of
    keystrokes is aggregated to keep only the latest (final) user query.

    This is called "prefix" aggregation.


    For more information, see [Query agggregation and
    processing](https://www.algolia.com/doc/guides/search-analytics/concepts/query-aggregation).


    See the analytics implementation overview for more information about query
    aggregation.
  version: 2.0.0
servers:
  - url: https://analytics.{region}.algolia.com
    variables:
      region:
        description: The region where your Algolia application is hosted.
        enum:
          - us
          - de
        default: us
  - url: https://analytics.algolia.com
security:
  - appId: []
    apiKey: []
tags:
  - name: click
    x-displayName: Clicks
    description: |
      Metrics related to click and conversion events,
      such as click and conversion rates for your search results.
  - name: filter
    x-displayName: Filters
    description: |
      Metrics related to filters.
  - name: pattern
    x-displayName: Patterns (Beta)
    description: >
      Beta — the semantic patterns query framework (`/3/patterns/*`).

      Build custom analytics queries from metrics, groupBy, filters, and
      parameters.

      These endpoints are under active development and may change without
      notice.
  - name: revenue
    x-displayName: Revenue
    description: |
      Metrics related to revenue.
  - name: search
    x-displayName: Searches
    description: |
      Metrics related to searches and search results,
      such as the no-results rate or the most frequent search queries.
  - name: status
    x-displayName: Status
    description: Check the status of the Analytics API.
  - name: user
    x-displayName: Users
    description: Metrics related to the users of your search.
externalDocs:
  url: https://www.algolia.com/doc/guides/search-analytics/overview
  description: Search analytics.
paths:
  /3/patterns/distribution:
    post:
      tags:
        - pattern
      summary: (Beta) Query a numeric distribution
      description: >
        **Beta**: this endpoint is under active development and may change
        without notice.


        Buckets one or more numeric fields into histograms and returns an object
        keyed by `histogram<Field>`,

        each mapping a bin label to a count. `distributions` and `parameters`
        are required; `filters` is

        optional. Discover valid field kinds per domain with
        `/3/patterns/fields`.
      operationId: queryPatternsDistribution
      parameters:
        - $ref: '#/components/parameters/IndexQuery'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DistributionPayload'
      responses:
        '200':
          description: OK
          headers:
            x-ratelimit-limit:
              $ref: '#/components/headers/x-ratelimit-limit'
            x-ratelimit-remaining:
              $ref: '#/components/headers/x-ratelimit-remaining'
            x-ratelimit-reset:
              $ref: '#/components/headers/x-ratelimit-reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DistributionResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '402':
          $ref: '#/components/responses/FeatureNotEnabled'
        '403':
          $ref: '#/components/responses/MethodNotAllowed'
        '404':
          $ref: '#/components/responses/IndexNotFound'
      x-codeSamples:
        - lang: csharp
          label: C#
          source: |-
            // Initialize the client
            var client = new AnalyticsClient(
              new AnalyticsConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY", "ALGOLIA_APPLICATION_REGION")
            );

            // Call the API
            var response = await client.QueryPatternsDistributionAsync(
              new DistributionPayload
              {
                Distributions = new List<DistributionDefinition>
                {
                  new DistributionDefinition
                  {
                    Kind = "clickPosition",
                    Bins = new List<BinEdge>
                    {
                      new BinEdge(1),
                      new BinEdge(2),
                      new BinEdge(3),
                      new BinEdge(4),
                      new BinEdge(5),
                    },
                  },
                },
                Parameters = new List<ParameterDefinition>
                {
                  new ParameterDefinition
                  {
                    Kind = "indices",
                    Value = new ParameterValue(new List<string> { "index" }),
                  },
                },
              },
              "index"
            );

            // print the response
            Console.WriteLine(response);
        - lang: go
          label: Go
          source: >-
            // Initialize the client with your application region, eg.
            analytics.ALGOLIA_APPLICATION_REGION

            client, err := analytics.NewClient("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY", analytics.US)

            if err != nil {
              // The client can fail to initialize if you pass an invalid parameter.
              panic(err)
            }


            // Call the API

            response, err :=
            client.QueryPatternsDistribution(client.NewApiQueryPatternsDistributionRequest(

              analytics.NewEmptyDistributionPayload().SetDistributions(
                []analytics.DistributionDefinition{*analytics.NewEmptyDistributionDefinition().SetKind("clickPosition").SetBins(
                  []analytics.BinEdge{*analytics.Int32AsBinEdge(1), *analytics.Int32AsBinEdge(2), *analytics.Int32AsBinEdge(3), *analytics.Int32AsBinEdge(4), *analytics.Int32AsBinEdge(5)})}).SetParameters(
                []analytics.ParameterDefinition{
                  *analytics.NewEmptyParameterDefinition().SetKind("indices").SetValue(analytics.ArrayOfStringAsParameterValue(
                    []string{"index"})),
                }),
            ).WithIndex("index"))

            if err != nil {
              // handle the eventual error
              panic(err)
            }



            // print the response

            print(response)
        - lang: java
          label: Java
          source: >-
            // Initialize the client

            AnalyticsClient client = new
            AnalyticsClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY",
            "ALGOLIA_APPLICATION_REGION");


            // Call the API

            Map response = client.queryPatternsDistribution(
              new DistributionPayload()
                .setDistributions(
                  Arrays.asList(
                    new DistributionDefinition()
                      .setKind("clickPosition")
                      .setBins(Arrays.asList(BinEdge.of(1), BinEdge.of(2), BinEdge.of(3), BinEdge.of(4), BinEdge.of(5)))
                  )
                )
                .setParameters(Arrays.asList(new ParameterDefinition().setKind("indices").setValue(ParameterValue.of(Arrays.asList("index"))))),
              "index"
            );


            // print the response

            System.out.println(response);
        - lang: javascript
          label: JavaScript
          source: >-
            // Initialize the client

            // Replace 'us' with your Algolia Application Region

            const client = algoliasearch('ALGOLIA_APPLICATION_ID',
            'ALGOLIA_API_KEY').initAnalytics({ region: 'us' });


            // Call the API

            const response = await client.queryPatternsDistribution({
              distributionPayload: {
                distributions: [{ kind: 'clickPosition', bins: [1, 2, 3, 4, 5] }],
                parameters: [{ kind: 'indices', value: ['index'] }],
              },
              index: 'index',
            });



            // print the response

            console.log(response);
        - lang: kotlin
          label: Kotlin
          source: |-
            // Initialize the client
            val client =
              AnalyticsClient(
                appId = "ALGOLIA_APPLICATION_ID",
                apiKey = "ALGOLIA_API_KEY",
                region = "ALGOLIA_APPLICATION_REGION",
              )

            // Call the API
            var response =
              client.queryPatternsDistribution(
                distributionPayload =
                  DistributionPayload(
                    distributions =
                      listOf(
                        DistributionDefinition(
                          kind = "clickPosition",
                          bins =
                            listOf(
                              BinEdge.of(1),
                              BinEdge.of(2),
                              BinEdge.of(3),
                              BinEdge.of(4),
                              BinEdge.of(5),
                            ),
                        )
                      ),
                    parameters =
                      listOf(
                        ParameterDefinition(kind = "indices", value = ParameterValue.of(listOf("index")))
                      ),
                  ),
                index = "index",
              )


            // print the response
            println(response)
        - lang: php
          label: PHP
          source: >-
            // Initialize the client

            $client = AnalyticsClient::create('ALGOLIA_APPLICATION_ID',
            'ALGOLIA_API_KEY', 'ALGOLIA_APPLICATION_REGION');


            // Call the API

            $response = $client->queryPatternsDistribution(
                ['distributions' => [
                    ['kind' => 'clickPosition',
                        'bins' => [
                            1,

                            2,

                            3,

                            4,

                            5,
                        ],
                    ],
                ],
                    'parameters' => [
                        ['kind' => 'indices',
                            'value' => [
                                'index',
                            ],
                        ],
                    ],
                ],
                'index',
            );



            // print the response

            var_dump($response);
        - lang: python
          label: Python
          source: >-
            # Initialize the client

            # In an asynchronous context, you can use AnalyticsClient instead,
            which exposes the exact same methods.

            client = AnalyticsClientSync(
                "ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY", "ALGOLIA_APPLICATION_REGION"
            )


            # Call the API

            response = client.query_patterns_distribution(
                distribution_payload={
                    "distributions": [
                        {
                            "kind": "clickPosition",
                            "bins": [
                                1,
                                2,
                                3,
                                4,
                                5,
                            ],
                        },
                    ],
                    "parameters": [
                        {
                            "kind": "indices",
                            "value": [
                                "index",
                            ],
                        },
                    ],
                },
                index="index",
            )



            # print the response

            print(response)
        - lang: ruby
          label: Ruby
          source: >-
            # Initialize the client

            client = Algolia::AnalyticsClient.create("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY", "ALGOLIA_APPLICATION_REGION")


            # Call the API

            response = client.query_patterns_distribution(
              Algolia::Analytics::DistributionPayload.new(
                distributions: [Algolia::Analytics::DistributionDefinition.new(kind: "clickPosition", bins: [1, 2, 3, 4, 5])],
                parameters: [Algolia::Analytics::ParameterDefinition.new(kind: "indices", value: ["index"])]
              ),
              "index"
            )



            # print the response

            puts(response)
        - lang: scala
          label: Scala
          source: |-
            // Initialize the client
            val client = AnalyticsClient(
              appId = "ALGOLIA_APPLICATION_ID",
              apiKey = "ALGOLIA_API_KEY",
              region = Option("ALGOLIA_APPLICATION_REGION")
            )

            // Call the API
            val response = Await.result(
              client.queryPatternsDistribution(
                distributionPayload = DistributionPayload(
                  distributions = Seq(
                    DistributionDefinition(
                      kind = "clickPosition",
                      bins = Seq(BinEdge(1), BinEdge(2), BinEdge(3), BinEdge(4), BinEdge(5))
                    )
                  ),
                  parameters = Seq(
                    ParameterDefinition(
                      kind = "indices",
                      value = ParameterValue(Seq("index"))
                    )
                  )
                ),
                index = Some("index")
              ),
              Duration(100, "sec")
            )

            // print the response
            println(response)
        - lang: swift
          label: Swift
          source: >-
            // Initialize the client

            let client = try AnalyticsClient(appID: "ALGOLIA_APPLICATION_ID",
            apiKey: "ALGOLIA_API_KEY", region: .us)


            // Call the API

            let response = try await client.queryPatternsDistribution(
                distributionPayload: DistributionPayload(distributions: [DistributionDefinition(
                    kind: "clickPosition",
                    bins: [BinEdge.int(1), BinEdge.int(2), BinEdge.int(3), BinEdge.int(4), BinEdge.int(5)]
                )], parameters: [ParameterDefinition(kind: "indices", value: ParameterValue.arrayOfString(["index"]))]),
                index: "index"
            )


            // print the response

            print(response)
        - lang: cURL
          label: curl
          source: |-
            curl --request POST \
              --url 'https://analytics.us.algolia.com/3/patterns/distribution?index=lorem' \
              --header 'accept: application/json' \
              --header 'content-type: application/json' \
              --header 'x-algolia-api-key: ALGOLIA_API_KEY' \
              --header 'x-algolia-application-id: ALGOLIA_APPLICATION_ID' \
              --data '
            {
              "domain": "core",
              "distributions": [
                {
                  "domain": "lorem",
                  "kind": "clickPosition",
                  "continuous": false,
                  "bins": [
                    1,
                    2,
                    3,
                    4,
                    5,
                    6,
                    7,
                    8,
                    9,
                    10,
                    11,
                    21,
                    -1
                  ]
                }
              ],
              "filters": [
                {
                  "domain": "lorem",
                  "kind": "country",
                  "operator": "=",
                  "parameter": {
                    "domain": "core",
                    "kind": "country"
                  }
                }
              ],
              "parameters": [
                {
                  "domain": "lorem",
                  "kind": "indices",
                  "value": "lorem"
                }
              ]
            }
            '
components:
  parameters:
    IndexQuery:
      in: query
      name: index
      required: false
      description: >
        Comma-separated list of indices the request runs on, used for
        authorization. Required for index-restricted API keys and must match the
        indices supplied in the request body's `indices` parameter; optional for
        unrestricted keys.
      schema:
        type: string
  schemas:
    DistributionPayload:
      type: object
      title: Distribution query
      additionalProperties: false
      required:
        - distributions
        - parameters
      properties:
        distributions:
          type: array
          description: Histogram specifications.
          items:
            $ref: '#/components/schemas/DistributionDefinition'
        parameters:
          type: array
          description: Literal values referenced by the query.
          items:
            $ref: '#/components/schemas/ParameterDefinition'
        domain:
          type: string
          description: Default domain propagated to entries that omit their own.
          example: core
        filters:
          type: array
          description: Filter conditions.
          items:
            $ref: '#/components/schemas/FilterDefinition'
    DistributionResponse:
      type: object
      title: Distribution response
      description: Object keyed by `histogram<Field>`, each mapping a bin label to a count.
      additionalProperties: true
    DistributionDefinition:
      type: object
      title: Distribution definition
      additionalProperties: false
      required:
        - kind
        - bins
      properties:
        bins:
          type: array
          description: Bin edges.
          items:
            $ref: '#/components/schemas/binEdge'
          example:
            - 1
            - 2
            - 3
            - 4
            - 5
            - 6
            - 7
            - 8
            - 9
            - 10
            - 11
            - 21
            - -1
        kind:
          type: string
          description: Numeric field to bucket into a histogram.
          example: clickPosition
        continuous:
          type: boolean
          default: false
          description: Set to true for continuous kinds; use float bins.
        domain:
          type: string
          description: Domain the field belongs to.
    ParameterDefinition:
      type: object
      title: Parameter definition
      additionalProperties: false
      required:
        - kind
        - value
      properties:
        kind:
          type: string
          description: >-
            Parameter identifier, for example `indices`, `startDate`, `endDate`,
            `tags`, or `country`.
          example: indices
        value:
          $ref: '#/components/schemas/parameterValue'
        domain:
          type: string
          description: Domain the parameter belongs to.
    FilterDefinition:
      type: object
      title: Filter definition
      additionalProperties: false
      required:
        - kind
      properties:
        kind:
          type: string
          description: Field to filter on. With no `operator`, the field must be boolean.
          example: country
        domain:
          type: string
          description: Domain the field belongs to.
        operator:
          $ref: '#/components/schemas/filterOperator'
        parameter:
          $ref: '#/components/schemas/ParameterReference'
    ErrorBase:
      description: Error.
      type: object
      x-keep-model: true
      additionalProperties: true
      properties:
        message:
          type: string
          example: Invalid Application-Id or API-Key
    binEdge:
      description: >-
        A histogram bin edge. Use integers for discrete distributions and
        floating-point values for continuous ones.
      oneOf:
        - type: integer
        - type: number
          format: double
    parameterValue:
      description: >-
        Literal value. Its JSON type depends on `kind` (array of strings for
        `indices`, string for dates, tags, and country, number for numeric
        operands, and so on).
      oneOf:
        - type: string
        - type: number
          format: double
        - type: boolean
        - type: array
          items:
            type: string
    filterOperator:
      type: string
      description: >-
        Comparison operator applied to a filter field, one of: `=`, `!=`, `>`,
        `<`, `>=`, `<=`, `IN`, `TAG_TREE`, `CONTAINS`, `STARTS_WITH`,
        `CONTAINS_PREFIX`. Requires a `parameter` to carry the operand.
      example: '='
    ParameterReference:
      type: object
      title: Parameter reference
      additionalProperties: false
      required:
        - kind
      properties:
        kind:
          type: string
          description: >-
            Parameter identifier that resolves to a value supplied in
            `parameters`.
          example: country
        domain:
          type: string
          description: Domain the parameter belongs to.
          example: core
  headers:
    x-ratelimit-limit:
      description: Number of allowed requests per one minute.
      example: 100
      schema:
        type: integer
    x-ratelimit-remaining:
      description: Number of remaining requests in the current period.
      example: 99
      schema:
        type: integer
    x-ratelimit-reset:
      description: >-
        Timestamp when the rate limit will reset, measured in seconds since the
        Unix epoch.
      example: 1710682486
      schema:
        type: integer
  responses:
    BadRequest:
      description: Bad request or request arguments.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    FeatureNotEnabled:
      description: This feature is not enabled on your Algolia account.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    MethodNotAllowed:
      description: Method not allowed with this API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    IndexNotFound:
      description: Index not found.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
  securitySchemes:
    appId:
      type: apiKey
      in: header
      name: x-algolia-application-id
      description: Your Algolia application ID.
    apiKey:
      type: apiKey
      in: header
      name: x-algolia-api-key
      description: >
        Your Algolia API key with the necessary permissions to make the request.

        Permissions are controlled through access control lists (ACL) and access
        restrictions.

        The required ACL to make a request is listed in each endpoint's
        reference.

````