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

# Search for rules

> Searches for Recommend rules.

Use an empty query to list all rules for this recommendation scenario.

**Required ACL:** `settings`


## OpenAPI

````yaml specs/recommend.yml post /1/indexes/{indexName}/{model}/recommend/rules/search
openapi: 3.1.0
info:
  title: Recommend API
  summary: >-
    The Recommend API lets you retrieve recommendations from one of Algolia's AI
    recommendation models that you previously trained on your data
  description: >
    ## Client libraries


    Use Algolia's API clients and libraries to reliably integrate Algolia's APIs
    with your apps.

    The official API clients are covered by Algolia's [Service Level
    Agreement](https://www.algolia.com/policies/sla).


    For more information, see [Algolia's
    ecosystem](https://www.algolia.com/doc/libraries).


    ## Base URLs


    Base URLs for the Recommend API:


    - `https://{APPLICATION_ID}.algolia.net`

    - `https://{APPLICATION_ID}-dsn.algolia.net`.
      If your subscription includes a [Distributed Search Network](https://dashboard.algolia.com/infra),
      this ensures that requests are sent to servers closest to users.

    Both URLs provide high availability by distributing requests with load
    balancing.


    **All requests must use HTTPS.**


    ## Retry strategy


    To guarantee a high availability, implement a retry strategy for all API
    requests using the URLs of your servers as fallbacks:


    - `https://{APPLICATION_ID}-1.algolianet.com`

    - `https://{APPLICATION_ID}-2.algolianet.com`

    - `https://{APPLICATION_ID}-3.algolianet.com`


    These URLs use a different DNS provider than the primary URLs.

    Randomize this list to ensure an even load across the three servers.


    All Algolia API clients implement this retry strategy.


    ## Authentication


    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).


    ## Request format


    Request bodies must be JSON objects.


    ## Response status and errors


    The Recommend 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 `2xx` statuses. Client errors return `4xx`
    statuses. Server errors return `5xx` statuses.

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


    ## Version


    The current version of the Recommend API is version 1, indicated by the
    `/1/` in each endpoint's URL.
  version: 1.0.0
servers:
  - url: https://{appId}.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-1.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-2.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-3.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-dsn.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
security:
  - appId: []
    apiKey: []
tags:
  - name: recommendations
    x-displayName: Recommendations
    description: >-
      Retrieve recommendations from a pre-trained AI model. You can train models
      in the [Algolia dashboard](https://dashboard.algolia.com/recommend).
    externalDocs:
      url: https://www.algolia.com/doc/guides/algolia-recommend/overview
      description: Algolia Recommend.
  - name: rules
    x-displayName: Rules
    description: Curate your recommendations with rules, which are _if_-_then_ statements.
    externalDocs:
      url: https://www.algolia.com/doc/guides/algolia-recommend/how-to/rules
      description: Recommend Rules.
paths:
  /1/indexes/{indexName}/{model}/recommend/rules/search:
    post:
      tags:
        - rules
      summary: Search for rules
      description: |
        Searches for Recommend rules.

        Use an empty query to list all rules for this recommendation scenario.
      operationId: searchRecommendRules
      parameters:
        - $ref: '#/components/parameters/IndexName'
        - $ref: '#/components/parameters/Models'
      requestBody:
        content:
          application/json:
            schema:
              title: searchRecommendRulesParams
              type: object
              description: Recommend rules parameters.
              additionalProperties: false
              properties:
                context:
                  type: string
                  description: Only search for rules with matching context.
                  example: mobile
                enabled:
                  type: boolean
                  description: >
                    Whether to only show rules where the value of their
                    `enabled` property matches this parameter.

                    If absent, show all rules, regardless of their `enabled`
                    property.
                facets:
                  type: array
                  description: >-
                    Include facets and facet values in the response. Use `['*']`
                    to include all facets.
                  example:
                    - '*'
                  items:
                    type: string
                    description: Facet name for rule objects or `*` as wildcard character.
                    example: condition.context
                filters:
                  type: string
                  description: >-
                    Filter expression. This only searches for rules matching the
                    filter expression.
                  example: objectID:rr-123456
                hitsPerPage:
                  $ref: '#/components/schemas/parameters_hitsPerPage'
                maxValuesPerFacet:
                  type: integer
                  description: Maximum number of values to return for each facet.
                  minimum: 1
                  maximum: 1000
                page:
                  $ref: '#/components/schemas/parameters_page'
                query:
                  $ref: '#/components/schemas/parameters_query'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                title: searchRecommendRulesResponse
                type: object
                additionalProperties: false
                required:
                  - hits
                  - nbHits
                  - page
                  - nbPages
                properties:
                  hits:
                    type: array
                    description: Recommend rules that match the search criteria.
                    items:
                      $ref: '#/components/schemas/RecommendRule'
                  nbHits:
                    $ref: '#/components/schemas/nbHits'
                  nbPages:
                    $ref: '#/components/schemas/nbPages'
                  page:
                    $ref: '#/components/schemas/page'
        '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 RecommendClient(
              new RecommendConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
            );

            // Call the API
            var response = await client.SearchRecommendRulesAsync(
              "<YOUR_INDEX_NAME>",
              Enum.Parse<RecommendModels>("RelatedProducts")
            );

            // print the response
            Console.WriteLine(response);
        - lang: dart
          label: Dart
          source: |-
            // Initialize the client
            final client = RecommendClient(
                appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

            // Call the API
            final response = await client.searchRecommendRules(
              indexName: "<YOUR_INDEX_NAME>",
              model: RecommendModels.fromJson("related-products"),
            );

            // print the response
            print(response);
        - lang: go
          label: Go
          source: >-
            // Initialize the client

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

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


            // Call the API

            response, err :=
            client.SearchRecommendRules(client.NewApiSearchRecommendRulesRequest(
              "<YOUR_INDEX_NAME>", recommend.RecommendModels("related-products")))
            if err != nil {
              // handle the eventual error
              panic(err)
            }



            // print the response

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

            RecommendClient client = new
            RecommendClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");


            // Call the API

            SearchRecommendRulesResponse response =
            client.searchRecommendRules("<YOUR_INDEX_NAME>",
            RecommendModels.RELATED_PRODUCTS);


            // print the response

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

            const client = algoliasearch('ALGOLIA_APPLICATION_ID',
            'ALGOLIA_API_KEY').initRecommend();


            // Call the API

            const response = await client.searchRecommendRules({ indexName:
            'indexName', model: 'related-products' });



            // print the response

            console.log(response);
        - lang: kotlin
          label: Kotlin
          source: >-
            // Initialize the client

            val client = RecommendClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            var response =
              client.searchRecommendRules(
                indexName = "<YOUR_INDEX_NAME>",
                model = RecommendModels.entries.first { it.value == "related-products" },
              )


            // print the response

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

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


            // Call the API

            $response = $client->searchRecommendRules(
                '<YOUR_INDEX_NAME>',
                'related-products',
            );



            // print the response

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

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

            client = RecommendClientSync("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")


            # Call the API

            response = client.search_recommend_rules(
                index_name="<YOUR_INDEX_NAME>",
                model="related-products",
            )



            # print the response

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

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


            # Call the API

            response = client.search_recommend_rules("<YOUR_INDEX_NAME>",
            "related-products")



            # print the response

            puts(response)
        - lang: scala
          label: Scala
          source: >-
            // Initialize the client

            val client = RecommendClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            val response = Await.result(
              client.searchRecommendRules(
                indexName = "<YOUR_INDEX_NAME>",
                model = RecommendModels.withName("related-products")
              ),
              Duration(100, "sec")
            )


            // print the response

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

            let client = try RecommendClient(appID: "ALGOLIA_APPLICATION_ID",
            apiKey: "ALGOLIA_API_KEY")


            // Call the API

            let response = try await client.searchRecommendRules(
                indexName: "<YOUR_INDEX_NAME>",
                model: RecommendModels.relatedProducts
            )


            // print the response

            print(response)
        - lang: cURL
          label: curl
          source: |-
            curl --request POST \
              --url https://algolia_application_id.algolia.net/1/indexes/ALGOLIA_INDEX_NAME/related-products/recommend/rules/search \
              --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 '
            {
              "query": "",
              "context": "mobile",
              "page": 0,
              "hitsPerPage": 20,
              "enabled": true,
              "filters": "objectID:rr-123456",
              "facets": [
                "*"
              ],
              "maxValuesPerFacet": 1
            }
            '
components:
  parameters:
    IndexName:
      name: indexName
      in: path
      description: Name of the index on which to perform the operation.
      required: true
      schema:
        type: string
        example: ALGOLIA_INDEX_NAME
    Models:
      in: path
      name: model
      required: true
      description: >
        [Recommend
        model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
      schema:
        $ref: '#/components/schemas/recommendModels'
  schemas:
    parameters_hitsPerPage:
      type: integer
      default: 20
      minimum: 1
      maximum: 1000
      description: >
        Maximum number of hits per page.


        Algolia uses `page` and `hitsPerPage` to control how search results are
        displayed
        ([paginated](https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/pagination/js)).


        - `hitsPerPage`: sets the number of search results (_hits_) displayed
        per page.

        - `page`: specifies the page number of the search results you want to
        retrieve. Page numbering starts at 0, so the first page is `page=0`, the
        second is `page=1`, and so on.


        For example, to display 10 results per page starting from the third
        page, set `hitsPerPage` to 10 and `page` to 2.
    parameters_page:
      type: integer
      minimum: 0
      description: >
        Requested page of the API response.


        Algolia uses `page` and `hitsPerPage` to control how search results are
        displayed
        ([paginated](https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/pagination/js)).


        - `hitsPerPage`: sets the number of search results (_hits_) displayed
        per page.

        - `page`: specifies the page number of the search results you want to
        retrieve. Page numbering starts at 0, so the first page is `page=0`, the
        second is `page=1`, and so on.


        For example, to display 10 results per page starting from the third
        page, set `hitsPerPage` to 10 and `page` to 2.
    parameters_query:
      type: string
      description: Search query.
      default: ''
    RecommendRule:
      type: object
      description: Recommend rule.
      additionalProperties: false
      properties:
        _metadata:
          title: ruleMetadata
          type: object
          description: Rule metadata.
          properties:
            lastUpdate:
              $ref: '#/components/schemas/updatedAt'
        condition:
          $ref: '#/components/schemas/Condition'
        consequence:
          $ref: '#/components/schemas/Consequence'
        description:
          type: string
          description: >-
            Description of the rule's purpose. This can be helpful for display
            in the Algolia dashboard.
          example: Boost on-sale items
        enabled:
          type: boolean
          default: true
          description: >-
            Indicates whether to enable the rule. If it isn't enabled, it isn't
            applied at query time.
        objectID:
          $ref: '#/components/schemas/ruleID'
        validity:
          type: array
          description: Time periods when the rule is active.
          items:
            $ref: '#/components/schemas/timeRange'
    nbHits:
      type: integer
      description: Number of results (hits).
      example: 20
    nbPages:
      type: integer
      description: Number of pages of results.
      example: 1
    page:
      type: integer
      description: Page of search results to retrieve.
      default: 0
      minimum: 0
      x-categories:
        - Pagination
    recommendModels:
      type: string
      enum:
        - related-products
        - bought-together
        - trending-facets
        - trending-items
    updatedAt:
      type: string
      example: '2023-07-04T12:49:15Z'
      description: Date and time when the object was updated, in RFC 3339 format.
    Condition:
      type: object
      description: |
        Condition that triggers the rule.
        If not specified, the rule is triggered for all recommendations.
      properties:
        context:
          $ref: '#/components/schemas/context'
        filters:
          $ref: '#/components/schemas/filters'
    Consequence:
      type: object
      description: Effect of the rule.
      properties:
        hide:
          $ref: '#/components/schemas/HideConsequence'
        params:
          $ref: '#/components/schemas/ParamsConsequence'
        promote:
          $ref: '#/components/schemas/PromoteConsequence'
    ruleID:
      title: objectID
      type: string
      description: Unique identifier of a rule object.
    timeRange:
      type: object
      additionalProperties: false
      properties:
        from:
          type: integer
          format: int64
          description: >-
            Timestamp when the rule should start to be active, measured in
            seconds since the Unix epoch.
        until:
          type: integer
          format: int64
          description: >-
            Timestamp when the rule should stop to be active, measured in
            seconds since the Unix epoch.
    ErrorBase:
      description: Error.
      type: object
      x-keep-model: true
      additionalProperties: true
      properties:
        message:
          type: string
          example: Invalid Application-Id or API-Key
    context:
      type: string
      pattern: '[A-Za-z0-9_-]+'
      description: >
        An additional restriction that only triggers the rule, when the search
        has the same value as `ruleContexts` parameter.

        For example, if `context: mobile`, the rule is only triggered when the
        search request has a matching `ruleContexts: mobile`.

        A rule context must only contain alphanumeric characters.
      example: mobile
    filters:
      type: string
      description: >
        Filter expression to only include items that match the filter criteria
        in the response.


        You can use these filter expressions:


        - **Numeric filters.** `<facet> <op> <number>`, where `<op>` is one of
        `<`, `<=`, `=`, `!=`, `>`, `>=`.

        - **Ranges.** `<facet>:<lower> TO <upper>`, where `<lower>` and
        `<upper>` are the lower and upper limits of the range (inclusive).

        - **Facet filters.** `<facet>:<value>`, where `<facet>` is a facet
        attribute (case-sensitive) and `<value>` a facet value.

        - **Tag filters.** `_tags:<value>` or just `<value>` (case-sensitive).

        - **Boolean filters.** `<facet>: true | false`.


        You can combine filters with `AND`, `OR`, and `NOT` operators with the
        following restrictions:


        - You can only combine filters of the same type with `OR`.
          **Not supported:** `facet:value OR num > 3`.
        - You can't use `NOT` with combinations of filters.
          **Not supported:** `NOT(facet:value OR facet:value)`
        - You can't combine conjunctions (`AND`) with `OR`.
          **Not supported:** `facet:value OR (facet:value AND facet:value)`

        Use quotes if the facet attribute name or facet value contains spaces,
        keywords (`OR`, `AND`, `NOT`), or quotes.

        If a facet attribute is an array, the filter matches if it matches at
        least one element of the array.


        For more information, see
        [Filters](https://www.algolia.com/doc/guides/managing-results/refine-results/filtering).
      example: (category:Book OR category:Ebook) AND _tags:published
      x-categories:
        - Filtering
    HideConsequence:
      type: array
      description: Exclude items from recommendations.
      minItems: 1
      items:
        $ref: '#/components/schemas/HideConsequenceObject'
    ParamsConsequence:
      type: object
      description: Filter or boost recommendations matching a facet filter.
      properties:
        automaticFacetFilters:
          type: array
          description: >-
            Filter recommendations that match or don't match the same
            `facet:facet_value` combination as the viewed item.
          items:
            $ref: '#/components/schemas/AutoFacetFilter'
        filters:
          $ref: '#/components/schemas/filters'
        optionalFilters:
          type: array
          description: >
            Filters to promote or demote records in the search results.


            Optional filters work like facet filters, but they don't exclude
            records from the search results.

            Records that match the optional filter rank before records that
            don't match.

            Matches with higher weights (`<score=N>`) rank before matches with
            lower weights.

            If you're using a negative filter `facet:-value`, matching records
            rank after records that don't match.
          items:
            type: string
          example:
            - category:books<score=1>
            - category:-movies<score=1>
    PromoteConsequence:
      type: array
      description: Place items at specific positions in the list of recommendations.
      minItems: 1
      items:
        $ref: '#/components/schemas/PromoteConsequenceObject'
    HideConsequenceObject:
      type: object
      description: Object ID of the recommendation you want to exclude.
      properties:
        objectID:
          $ref: '#/components/schemas/objectID'
    AutoFacetFilter:
      type: object
      description: >-
        Facet attribute. Only recommendations with the same value (or only
        recommendations with a different value) as the original viewed item are
        included.
      properties:
        facet:
          type: string
          description: Facet attribute.
        negative:
          type: boolean
          description: >
            Whether the filter is negative.

            If true, recommendations must not have the same value for the
            `facet` attribute.

            If false, recommendations must have the same value for the `facet`
            attribute.
    PromoteConsequenceObject:
      type: object
      description: Object ID and position of the recommendation you want to pin.
      properties:
        objectID:
          $ref: '#/components/schemas/objectID'
        position:
          type: integer
          description: Index in the list of recommendations where to place this item.
          minimum: 0
    objectID:
      type: string
      description: Unique record identifier.
      example: test-record-123
  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.

````