Skip to content

Commit

Permalink
feat(specs): add recommend batch rules endpoint (generated)
Browse files Browse the repository at this point in the history
algolia/api-clients-automation#3782

Co-authored-by: algolia-bot <[email protected]>
Co-authored-by: Raed <[email protected]>
Co-authored-by: Pierre Millot <[email protected]>
Co-authored-by: Clément Vannicatte <[email protected]>
  • Loading branch information
4 people committed Sep 27, 2024
1 parent 16ac3ca commit 7d03f02
Show file tree
Hide file tree
Showing 4 changed files with 322 additions and 1 deletion.
187 changes: 187 additions & 0 deletions algoliasearch/recommend/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
)
from algoliasearch.recommend.models.recommend_models import RecommendModels
from algoliasearch.recommend.models.recommend_rule import RecommendRule
from algoliasearch.recommend.models.recommend_updated_at_response import (
RecommendUpdatedAtResponse,
)
from algoliasearch.recommend.models.search_recommend_rules_params import (
SearchRecommendRulesParams,
)
Expand Down Expand Up @@ -129,6 +132,98 @@ async def set_client_api_key(self, api_key: str) -> None:
"""Sets a new API key to authenticate requests."""
self._transporter._config.set_client_api_key(api_key)

async def batch_recommend_rules_with_http_info(
self,
index_name: Annotated[
StrictStr,
Field(description="Name of the index on which to perform the operation."),
],
model: Annotated[
RecommendModels,
Field(
description="[Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). "
),
],
recommend_rule: Optional[List[RecommendRule]] = None,
request_options: Optional[Union[dict, RequestOptions]] = None,
) -> ApiResponse[str]:
"""
Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn't require a facet value placeholder (it tries to match the data source item's attributes instead).
Required API Key ACLs:
- editSettings
:param index_name: Name of the index on which to perform the operation. (required)
:type index_name: str
:param model: [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). (required)
:type model: RecommendModels
:param recommend_rule:
:type recommend_rule: List[RecommendRule]
:param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
:return: Returns the raw algoliasearch 'APIResponse' object.
"""

if index_name is None:
raise ValueError(
"Parameter `index_name` is required when calling `batch_recommend_rules`."
)

if model is None:
raise ValueError(
"Parameter `model` is required when calling `batch_recommend_rules`."
)

_data = {}
if recommend_rule is not None:
_data = recommend_rule

return await self._transporter.request(
verb=Verb.POST,
path="/1/indexes/{indexName}/{model}/recommend/rules/batch".replace(
"{indexName}", quote(str(index_name), safe="")
).replace("{model}", quote(str(model), safe="")),
request_options=self._request_options.merge(
data=dumps(bodySerializer(_data)),
user_request_options=request_options,
),
use_read_transporter=False,
)

async def batch_recommend_rules(
self,
index_name: Annotated[
StrictStr,
Field(description="Name of the index on which to perform the operation."),
],
model: Annotated[
RecommendModels,
Field(
description="[Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). "
),
],
recommend_rule: Optional[List[RecommendRule]] = None,
request_options: Optional[Union[dict, RequestOptions]] = None,
) -> RecommendUpdatedAtResponse:
"""
Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn't require a facet value placeholder (it tries to match the data source item's attributes instead).
Required API Key ACLs:
- editSettings
:param index_name: Name of the index on which to perform the operation. (required)
:type index_name: str
:param model: [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). (required)
:type model: RecommendModels
:param recommend_rule:
:type recommend_rule: List[RecommendRule]
:param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
:return: Returns the deserialized response in a 'RecommendUpdatedAtResponse' result object.
"""
resp = await self.batch_recommend_rules_with_http_info(
index_name, model, recommend_rule, request_options
)
return resp.deserialize(RecommendUpdatedAtResponse, resp.raw_data)

async def custom_delete_with_http_info(
self,
path: Annotated[
Expand Down Expand Up @@ -977,6 +1072,98 @@ def set_client_api_key(self, api_key: str) -> None:
"""Sets a new API key to authenticate requests."""
self._transporter._config.set_client_api_key(api_key)

def batch_recommend_rules_with_http_info(
self,
index_name: Annotated[
StrictStr,
Field(description="Name of the index on which to perform the operation."),
],
model: Annotated[
RecommendModels,
Field(
description="[Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). "
),
],
recommend_rule: Optional[List[RecommendRule]] = None,
request_options: Optional[Union[dict, RequestOptions]] = None,
) -> ApiResponse[str]:
"""
Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn't require a facet value placeholder (it tries to match the data source item's attributes instead).
Required API Key ACLs:
- editSettings
:param index_name: Name of the index on which to perform the operation. (required)
:type index_name: str
:param model: [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). (required)
:type model: RecommendModels
:param recommend_rule:
:type recommend_rule: List[RecommendRule]
:param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
:return: Returns the raw algoliasearch 'APIResponse' object.
"""

if index_name is None:
raise ValueError(
"Parameter `index_name` is required when calling `batch_recommend_rules`."
)

if model is None:
raise ValueError(
"Parameter `model` is required when calling `batch_recommend_rules`."
)

_data = {}
if recommend_rule is not None:
_data = recommend_rule

return self._transporter.request(
verb=Verb.POST,
path="/1/indexes/{indexName}/{model}/recommend/rules/batch".replace(
"{indexName}", quote(str(index_name), safe="")
).replace("{model}", quote(str(model), safe="")),
request_options=self._request_options.merge(
data=dumps(bodySerializer(_data)),
user_request_options=request_options,
),
use_read_transporter=False,
)

def batch_recommend_rules(
self,
index_name: Annotated[
StrictStr,
Field(description="Name of the index on which to perform the operation."),
],
model: Annotated[
RecommendModels,
Field(
description="[Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). "
),
],
recommend_rule: Optional[List[RecommendRule]] = None,
request_options: Optional[Union[dict, RequestOptions]] = None,
) -> RecommendUpdatedAtResponse:
"""
Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn't require a facet value placeholder (it tries to match the data source item's attributes instead).
Required API Key ACLs:
- editSettings
:param index_name: Name of the index on which to perform the operation. (required)
:type index_name: str
:param model: [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). (required)
:type model: RecommendModels
:param recommend_rule:
:type recommend_rule: List[RecommendRule]
:param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
:return: Returns the deserialized response in a 'RecommendUpdatedAtResponse' result object.
"""
resp = self.batch_recommend_rules_with_http_info(
index_name, model, recommend_rule, request_options
)
return resp.deserialize(RecommendUpdatedAtResponse, resp.raw_data)

def custom_delete_with_http_info(
self,
path: Annotated[
Expand Down
10 changes: 9 additions & 1 deletion algoliasearch/recommend/models/recommend_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from json import loads
from sys import version_info
from typing import Any, Dict, Optional
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, ConfigDict, Field

Expand All @@ -21,6 +21,7 @@
from algoliasearch.recommend.models.condition import Condition
from algoliasearch.recommend.models.consequence import Consequence
from algoliasearch.recommend.models.rule_metadata import RuleMetadata
from algoliasearch.recommend.models.time_range import TimeRange


class RecommendRule(BaseModel):
Expand All @@ -37,6 +38,8 @@ class RecommendRule(BaseModel):
""" Description of the rule's purpose. This can be helpful for display in the Algolia dashboard. """
enabled: Optional[bool] = Field(default=None, alias="enabled")
""" Indicates whether to enable the rule. If it isn't enabled, it isn't applied at query time. """
validity: Optional[List[TimeRange]] = Field(default=None, alias="validity")
""" Time periods when the rule is active. """

model_config = ConfigDict(
use_enum_values=True,
Expand Down Expand Up @@ -85,5 +88,10 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
if obj.get("consequence") is not None
else None
)
obj["validity"] = (
[TimeRange.from_dict(_item) for _item in obj["validity"]]
if obj.get("validity") is not None
else None
)

return cls.model_validate(obj)
63 changes: 63 additions & 0 deletions algoliasearch/recommend/models/recommend_updated_at_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""

from __future__ import annotations

from json import loads
from sys import version_info
from typing import Any, Dict, Optional

from pydantic import BaseModel, ConfigDict, Field

if version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self


class RecommendUpdatedAtResponse(BaseModel):
"""
Response, taskID, and update timestamp.
"""

task_id: int = Field(alias="taskID")
""" Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task's progress with the [`task` operation](#tag/Indices/operation/getTask) and this `taskID`. """
updated_at: str = Field(alias="updatedAt")
""" Date and time when the object was updated, in RFC 3339 format. """

model_config = ConfigDict(
use_enum_values=True,
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)

def to_json(self) -> str:
return self.model_dump_json(by_alias=True, exclude_unset=True)

@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RecommendUpdatedAtResponse from a JSON string"""
return cls.from_dict(loads(json_str))

def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias."""
return self.model_dump(
by_alias=True,
exclude_none=True,
exclude_unset=True,
)

@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RecommendUpdatedAtResponse from a dict"""
if obj is None:
return None

if not isinstance(obj, dict):
return cls.model_validate(obj)

return cls.model_validate(obj)
63 changes: 63 additions & 0 deletions algoliasearch/recommend/models/time_range.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""

from __future__ import annotations

from json import loads
from sys import version_info
from typing import Any, Dict, Optional

from pydantic import BaseModel, ConfigDict, Field

if version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self


class TimeRange(BaseModel):
"""
TimeRange
"""

var_from: int = Field(alias="from")
""" When the rule should start to be active, in Unix epoch time. """
until: int = Field(alias="until")
""" When the rule should stop to be active, in Unix epoch time. """

model_config = ConfigDict(
use_enum_values=True,
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)

def to_json(self) -> str:
return self.model_dump_json(by_alias=True, exclude_unset=True)

@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of TimeRange from a JSON string"""
return cls.from_dict(loads(json_str))

def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias."""
return self.model_dump(
by_alias=True,
exclude_none=True,
exclude_unset=True,
)

@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of TimeRange from a dict"""
if obj is None:
return None

if not isinstance(obj, dict):
return cls.model_validate(obj)

return cls.model_validate(obj)

0 comments on commit 7d03f02

Please sign in to comment.