From cacc3c3c5da787af6d4e80f5326cd71faa105e45 Mon Sep 17 00:00:00 2001 From: theluckystrike <51033404+theluckystrike@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:31:49 +0800 Subject: [PATCH] fix(documents): type the server's batch_size in import parameters Fixes #124. The batch_size argument of import_ splits the list on the client and is never sent to the server, while the import parameter types had no batch_size key, so the documented server parameter failed the type check. Add DocumentImportWriteParameters with batch_size, use it for the plain import and the return_id/return_doc variants, and document the difference in the import_ docstring. --- src/typesense/async_/documents.py | 13 ++-- src/typesense/sync/documents.py | 13 ++-- src/typesense/types/document.py | 24 +++++-- tests/import_parameters_test.py | 110 ++++++++++++++++++++++++++++++ 4 files changed, 146 insertions(+), 14 deletions(-) create mode 100644 tests/import_parameters_test.py diff --git a/src/typesense/async_/documents.py b/src/typesense/async_/documents.py index 2f155ad..c9626a3 100644 --- a/src/typesense/async_/documents.py +++ b/src/typesense/async_/documents.py @@ -40,8 +40,8 @@ DocumentImportParametersReturnDoc, DocumentImportParametersReturnDocAndId, DocumentImportParametersReturnId, + DocumentImportWriteParameters, DocumentSchema, - DocumentWriteParameters, ImportResponse, ImportResponseFail, ImportResponseSuccess, @@ -178,7 +178,7 @@ async def create_many( return await self.import_( documents, typing.cast( - typing.Optional[DocumentWriteParameters], + typing.Optional[DocumentImportWriteParameters], dirty_values_parameters, ), ) @@ -275,7 +275,7 @@ async def import_( async def import_( self, documents: typing.List[TDoc], - import_parameters: typing.Union[DocumentWriteParameters, None] = None, + import_parameters: typing.Union[DocumentImportWriteParameters, None] = None, batch_size: typing.Union[int, None] = None, ) -> typing.List[typing.Union[ImportResponseSuccess, ImportResponseFail[TDoc]]]: ... @@ -319,8 +319,11 @@ async def import_( Args: documents: The documents to import. - import_parameters: Parameters for the import operation. - batch_size: The size of each batch for batch imports. + import_parameters: Parameters for the import operation. To set the + server's ``batch_size`` query parameter, put it here. + batch_size: How many documents the client sends in each request. The + list is split into requests of this size; the value is not sent + to the server. Returns: The import response, which can be a list of responses or a string. diff --git a/src/typesense/sync/documents.py b/src/typesense/sync/documents.py index 278002e..7eca4d1 100644 --- a/src/typesense/sync/documents.py +++ b/src/typesense/sync/documents.py @@ -40,8 +40,8 @@ DocumentImportParametersReturnDoc, DocumentImportParametersReturnDocAndId, DocumentImportParametersReturnId, + DocumentImportWriteParameters, DocumentSchema, - DocumentWriteParameters, ImportResponse, ImportResponseFail, ImportResponseSuccess, @@ -178,7 +178,7 @@ def create_many( return self.import_( documents, typing.cast( - typing.Optional[DocumentWriteParameters], + typing.Optional[DocumentImportWriteParameters], dirty_values_parameters, ), ) @@ -275,7 +275,7 @@ def import_( def import_( self, documents: typing.List[TDoc], - import_parameters: typing.Union[DocumentWriteParameters, None] = None, + import_parameters: typing.Union[DocumentImportWriteParameters, None] = None, batch_size: typing.Union[int, None] = None, ) -> typing.List[typing.Union[ImportResponseSuccess, ImportResponseFail[TDoc]]]: ... @@ -319,8 +319,11 @@ def import_( Args: documents: The documents to import. - import_parameters: Parameters for the import operation. - batch_size: The size of each batch for batch imports. + import_parameters: Parameters for the import operation. To set the + server's ``batch_size`` query parameter, put it here. + batch_size: How many documents the client sends in each request. The + list is split into requests of this size; the value is not sent + to the server. Returns: The import response, which can be a list of responses or a string. diff --git a/src/typesense/types/document.py b/src/typesense/types/document.py index 927c39c..c478325 100644 --- a/src/typesense/types/document.py +++ b/src/typesense/types/document.py @@ -99,6 +99,22 @@ class DocumentWriteParameters(DirtyValuesParameters): action: typing.NotRequired[typing.Literal["create", "update", "upsert", "emplace"]] +class DocumentImportWriteParameters(DocumentWriteParameters): + """ + Parameters for [importing documents](https://typesense.org/docs/latest/api/documents.html#index-multiple-documents). + + Attributes: + batch_size (int): How many documents the server processes at a time + (sent as the ``batch_size`` query parameter). The ``batch_size`` argument + of ``import_`` is different: it sets how many documents the client sends + in each request. + action (str): Action to perform on each document (see `DocumentWriteParameters`). + dirty_values (str): Handling of dirty values (see `DocumentWriteParameters`). + """ + + batch_size: typing.NotRequired[int] + + class UpdateByFilterParameters(typing.TypedDict): """ Parameters for updating documents by filter. @@ -198,7 +214,7 @@ class ImportResponseFail(typing.Generic[TDoc], typing.TypedDict): """Set of all possible responses after an import operation.""" -class DocumentImportParametersReturnId(DocumentWriteParameters): +class DocumentImportParametersReturnId(DocumentImportWriteParameters): """ Parameters for importing documents with return ID. @@ -231,7 +247,7 @@ class DocumentImportParametersReturnId(DocumentWriteParameters): return_id: typing.Literal[True] -class DocumentImportParametersReturnDoc(DocumentWriteParameters): +class DocumentImportParametersReturnDoc(DocumentImportWriteParameters): """ Parameters for importing documents with return document. @@ -264,7 +280,7 @@ class DocumentImportParametersReturnDoc(DocumentWriteParameters): return_doc: typing.Literal[True] -class DocumentImportParametersReturnDocAndId(DocumentWriteParameters): +class DocumentImportParametersReturnDocAndId(DocumentImportWriteParameters): """ Parameters for importing documents with return document and ID. @@ -300,7 +316,7 @@ class DocumentImportParametersReturnDocAndId(DocumentWriteParameters): DocumentImportParameters: typing.TypeAlias = typing.Union[ - DocumentWriteParameters, + DocumentImportWriteParameters, DocumentImportParametersReturnId, DocumentImportParametersReturnDoc, DocumentImportParametersReturnDocAndId, diff --git a/tests/import_parameters_test.py b/tests/import_parameters_test.py new file mode 100644 index 0000000..30850dd --- /dev/null +++ b/tests/import_parameters_test.py @@ -0,0 +1,110 @@ +"""Tests for the import parameters and the batch size of an import.""" + +import json +import sys + +import pytest + +from tests.utils.backends import Backend, RequestType, load_backend +from typesense.configuration import Configuration +from typesense.http_backend import ResponseType +from typesense.sync.api_call import ApiCall +from typesense.sync.documents import Documents +from typesense.types.document import ( + DocumentImportParameters, + DocumentImportParametersReturnDoc, + DocumentImportParametersReturnDocAndId, + DocumentImportParametersReturnId, + DocumentImportWriteParameters, + DocumentSchema, +) + +if sys.version_info >= (3, 11): + import typing +else: + import typing_extensions as typing + +IMPORT_PATH: typing.Final = "/collections/books/documents/import" + + +@pytest.fixture(name="backend", params=["httpx", "httpx2"]) +def backend_fixture(request: pytest.FixtureRequest) -> Backend: + """Return each HTTP backend that is installed.""" + name = request.param + assert isinstance(name, str) + return load_backend(name) + + +def make_documents( + backend: Backend, + config: Configuration, + requests: typing.List[RequestType], +) -> Documents[DocumentSchema]: + """Return documents that record each request and answer each line with success.""" + + def handler(request: RequestType) -> ResponseType: + requests.append(request) + lines = request.content.decode().split("\n") + body = "\n".join(json.dumps({"success": True}) for _ in lines) + return backend.Response(200, content=body.encode()) + + api_call = ApiCall(config, backend.client(handler)) + return Documents[DocumentSchema](api_call, "books") + + +@pytest.mark.parametrize( + "parameters_type", + [ + DocumentImportWriteParameters, + DocumentImportParametersReturnId, + DocumentImportParametersReturnDoc, + DocumentImportParametersReturnDocAndId, + ], +) +def test_import_parameters_accept_the_server_batch_size( + parameters_type: typing.Type[typing.Any], +) -> None: + """Test that each import parameters type has the server's batch_size.""" + hints = typing.get_type_hints(parameters_type) + + assert hints["batch_size"] is int + assert "batch_size" in parameters_type.__optional_keys__ + + +def test_import_parameters_union_has_the_plain_import_parameters() -> None: + """Test that a plain import uses the type with the server's batch_size.""" + assert DocumentImportWriteParameters in typing.get_args(DocumentImportParameters) + + +def test_batch_size_in_import_parameters_goes_to_the_server( + backend: Backend, + fake_config: Configuration, +) -> None: + """Test that batch_size in import_parameters is sent as a query parameter.""" + requests: typing.List[RequestType] = [] + documents = make_documents(backend, fake_config, requests) + parameters: DocumentImportWriteParameters = {"batch_size": 42} + + documents.import_([{"id": "1"}, {"id": "2"}], parameters) + + assert len(requests) == 1 + assert requests[0].url.path == IMPORT_PATH + assert requests[0].url.params["batch_size"] == "42" + + +def test_batch_size_argument_splits_the_requests_on_the_client( + backend: Backend, + fake_config: Configuration, +) -> None: + """Test that the batch_size argument splits the list and is not sent.""" + requests: typing.List[RequestType] = [] + documents = make_documents(backend, fake_config, requests) + + response = documents.import_( + [{"id": "1"}, {"id": "2"}, {"id": "3"}], + batch_size=2, + ) + + assert len(response) == 3 + assert [len(request.content.decode().split("\n")) for request in requests] == [2, 1] + assert all("batch_size" not in request.url.params for request in requests)