Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support batches API #1062

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .code-samples.meilisearch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -742,3 +742,7 @@ update_localized_attribute_settings_1: |-
])
reset_localized_attribute_settings_1: |-
client.index('INDEX_NAME').reset_localized_attributes()
get_all_batches_1: |-
client.get_batches()
get_batch_1: |-
client.get_batch(BATCH_UID)
42 changes: 41 additions & 1 deletion meilisearch/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from meilisearch.errors import MeilisearchError
from meilisearch.index import Index
from meilisearch.models.key import Key, KeysResults
from meilisearch.models.task import Task, TaskInfo, TaskResults
from meilisearch.models.task import Batch, BatchResults, Task, TaskInfo, TaskResults
from meilisearch.task import TaskHandler


Expand Down Expand Up @@ -611,6 +611,46 @@ def wait_for_task(
"""
return self.task_handler.wait_for_task(uid, timeout_in_ms, interval_in_ms)

def get_batches(self, parameters: Optional[MutableMapping[str, Any]] = None) -> BatchResults:
"""Get all batches.

Parameters
----------
parameters (optional):
parameters accepted by the get batches route: https://www.meilisearch.com/docs/reference/api/batches#get-batches.

Returns
-------
batch:
BatchResult instance containing limit, from, next and results containing a list of all batches.

Raises
------
MeilisearchApiError
An error containing details about why Meilisearch can't process your request. Meilisearch error codes are described here: https://www.meilisearch.com/docs/reference/errors/error_codes#meilisearch-errors
"""
return self.task_handler.get_batches(parameters=parameters)

def get_batch(self, uid: int) -> Batch:
"""Get one tasks batch.

Parameters
----------
uid:
Identifier of the batch.

Returns
-------
batch:
Batch instance containing information about the progress of the asynchronous batch.

Raises
------
MeilisearchApiError
An error containing details about why Meilisearch can't process your request. Meilisearch error codes are described here: https://www.meilisearch.com/docs/reference/errors/error_codes#meilisearch-errors
"""
return self.task_handler.get_batch(uid)

def generate_tenant_token(
self,
api_key_uid: str,
Expand Down
1 change: 1 addition & 0 deletions meilisearch/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Paths:
version = "version"
index = "indexes"
task = "tasks"
batch = "batches"
stat = "stats"
search = "search"
facet_search = "facet-search"
Expand Down
43 changes: 43 additions & 0 deletions meilisearch/models/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,46 @@ def __init__(self, resp: Dict[str, Any]) -> None:
self.total: int = resp["total"]
self.from_: int = resp["from"]
self.next_: int = resp["next"]


class Batch(CamelBase):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept this class mostly the same as the Task model, including (some) of the validations.

I used Optional[*] instead of the Union[*, None] which was widely used in Task.

uid: int
details: Optional[Dict[str, Any]] = None
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if any of this is legacy syntax, I tried to maintain the same style as Task as much as possible.

Copy link
Contributor Author

@ellnix ellnix Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though in the previous PR I would have just done:

details: Dict[str, Any]

Additionally, I'm assuming Dict is fine here (instead of Mapping) since we know that we get Dicts as responses from web requests.

stats: Optional[Dict[str, Union[int, Dict[str, Any]]]] = None
duration: Optional[str] = None
started_at: Optional[datetime] = None
finished_at: Optional[datetime] = None
progress: Optional[Dict[str, Union[float, List[Dict[str, Any]]]]] = None

if is_pydantic_2():

@pydantic.field_validator("started_at", mode="before") # type: ignore[attr-defined]
@classmethod
def validate_started_at(cls, v: str) -> Optional[datetime]: # pylint: disable=invalid-name
return iso_to_date_time(v)

@pydantic.field_validator("finished_at", mode="before") # type: ignore[attr-defined]
@classmethod
def validate_finished_at(cls, v: str) -> Optional[datetime]: # pylint: disable=invalid-name
return iso_to_date_time(v)

else: # pragma: no cover

@pydantic.validator("started_at", pre=True)
@classmethod
def validate_started_at(cls, v: str) -> Optional[datetime]: # pylint: disable=invalid-name
return iso_to_date_time(v)

@pydantic.validator("finished_at", pre=True)
@classmethod
def validate_finished_at(cls, v: str) -> Optional[datetime]: # pylint: disable=invalid-name
return iso_to_date_time(v)


class BatchResults:
def __init__(self, resp: Dict[str, Any]) -> None:
self.results: List[Batch] = [Batch(**batch) for batch in resp["results"]]
self.total: int = resp["total"]
self.limit: int = resp["limit"]
self.from_: int = resp["from"]
self.next_: int = resp["next"]
49 changes: 48 additions & 1 deletion meilisearch/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from meilisearch._httprequests import HttpRequests
from meilisearch.config import Config
from meilisearch.errors import MeilisearchTimeoutError
from meilisearch.models.task import Task, TaskInfo, TaskResults
from meilisearch.models.task import Batch, BatchResults, Task, TaskInfo, TaskResults


class TaskHandler:
Expand All @@ -27,6 +27,53 @@ def __init__(self, config: Config):
self.config = config
self.http = HttpRequests(config)

def get_batches(self, parameters: Optional[MutableMapping[str, Any]] = None) -> BatchResults:
"""Get all task batches.

Parameters
----------
parameters (optional):
parameters accepted by the get batches route: https://www.meilisearch.com/docs/reference/api/batches#get-batches.

Returns
-------
batch:
BatchResults instance contining limit, from, next and results containing a list of all batches.

Raises
------
MeilisearchApiError
An error containing details about why Meilisearch can't process your request. Meilisearch error codes are described here: https://www.meilisearch.com/docs/reference/errors/error_codes#meilisearch-errors
"""
if parameters is None:
parameters = {}
for param in parameters:
if isinstance(parameters[param], list):
parameters[param] = ",".join(parameters[param])
batches = self.http.get(f"{self.config.paths.batch}?{parse.urlencode(parameters)}")
return BatchResults(batches)

def get_batch(self, uid: int) -> Batch:
"""Get one tasks batch.

Parameters
----------
uid:
Identifier of the batch.

Returns
-------
task:
Batch instance containing information about the progress of the asynchronous batch.

Raises
------
MeilisearchApiError
An error containing details about why Meilisearch can't process your request. Meilisearch error codes are described here: https://www.meilisearch.com/docs/reference/errors/error_codes#meilisearch-errors
"""
batch = self.http.get(f"{self.config.paths.batch}/{uid}")
return Batch(**batch)

def get_tasks(self, parameters: Optional[MutableMapping[str, Any]] = None) -> TaskResults:
"""Get all tasks.

Expand Down
30 changes: 30 additions & 0 deletions tests/client/test_client_task_meilisearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,33 @@ def test_get_tasks_in_reverse(client):
reverse_tasks = client.get_tasks({"reverse": "true"})

assert reverse_tasks.results[0] == tasks.results[-1]


def test_get_batches_default(client):
"""Tests getting the batches."""
batches = client.get_batches()
assert len(batches.results) >= 1


@pytest.mark.usefixtures("create_tasks")
def test_get_batches_with_parameters(client):
"""Tests getting batches with a parameter (empty or otherwise)."""
rev_batches = client.get_batches({"reverse": "true"})
batches = client.get_batches({})

assert len(batches.results) > 1
assert rev_batches.results[0].uid == batches.results[-1].uid


def test_get_batch(client):
"""Tests getting the details of a batch."""
batches = client.get_batches({"limit": 1})
batch = client.get_batch(batches.results[0].uid)
batch_dict = batch.__dict__
assert "uid" in batch_dict
assert "details" in batch_dict
assert "stats" in batch_dict
assert "duration" in batch_dict
assert "started_at" in batch_dict
assert "finished_at" in batch_dict
assert "progress" in batch_dict
Loading