mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
refactor(sdk)!: standardize compaction APIs on Optimize
BREAKING CHANGE: Replace compact_async/compactAsync with optimize_async/optimizeAsync, Rust compact(overrides) with optimize(overrides), and Python compact_files() with optimize(action="rewrite_data"). No compatibility aliases are retained.
This commit is contained in:
@@ -806,7 +806,7 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def compact_async(
|
||||
async def optimize_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
async def optimize(
|
||||
@@ -815,6 +815,7 @@ class Table:
|
||||
cleanup_since_ms: Optional[int] = None,
|
||||
delete_unverified: Optional[bool] = None,
|
||||
compaction_options: Optional[Dict[str, Any]] = None,
|
||||
action: Optional[str] = None,
|
||||
) -> OptimizeStats: ...
|
||||
async def uri(self) -> str: ...
|
||||
async def initial_storage_options(self) -> Optional[Dict[str, str]]: ...
|
||||
|
||||
@@ -90,6 +90,8 @@ from ..types import BaseTokenizerType, ScalarIndexType
|
||||
from ..util import infer_vector_column_name
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lancedb._lancedb import OptimizeStats
|
||||
|
||||
import lance
|
||||
import polars as pl
|
||||
|
||||
@@ -1098,21 +1100,11 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_files(self, *args, **kwargs):
|
||||
"""
|
||||
compact_files() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"compact_files() is a no-op in LanceDB Enterprise.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_async(
|
||||
def optimize_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
LOOP.run(self._table.optimize_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
@@ -1122,11 +1114,12 @@ class RemoteTable(Table):
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
):
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
"""Compact the table's data files via a durable, asynchronous
|
||||
Enterprise job. Pruning old versions and index optimization are not
|
||||
yet supported remotely, so this call skips them and returns
|
||||
successfully with zeroed pruning statistics once the compaction job
|
||||
successfully with placeholder statistics once the compaction job
|
||||
has been submitted; it does not wait for that job to finish. The
|
||||
per-job options ``target_rows_per_fragment``, ``max_source_rows``,
|
||||
``io_buffer_size``, and ``batch_size`` are supported on compatible
|
||||
@@ -1141,6 +1134,7 @@ class RemoteTable(Table):
|
||||
delete_unverified=delete_unverified,
|
||||
retrain=retrain,
|
||||
compaction_options=compaction_options,
|
||||
action=action,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -304,7 +304,6 @@ if TYPE_CHECKING:
|
||||
Table as LanceDBTable,
|
||||
OptimizeStats,
|
||||
CleanupStats,
|
||||
CompactionStats,
|
||||
Tag,
|
||||
AddColumnsResult,
|
||||
RefreshColumnResult,
|
||||
@@ -3115,29 +3114,7 @@ class Table(ABC):
|
||||
cleanup for you automatically.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def compact_files(self, *args, **kwargs):
|
||||
"""
|
||||
Run the compaction process on the table.
|
||||
This can be run after making several small appends to optimize the table
|
||||
for faster reads.
|
||||
|
||||
Arguments are passed onto Lance's
|
||||
`lance.dataset.DatasetOptimizer.compact_files`.
|
||||
For most cases, the default should be fine.
|
||||
|
||||
See Also
|
||||
--------
|
||||
[Table.optimize][lancedb.table.Table.optimize]: A more comprehensive
|
||||
optimization operation that includes cleanup as well as other operations.
|
||||
|
||||
Notes
|
||||
-----
|
||||
This function is not available in LanceDB Enterprise, which manages
|
||||
compaction for you automatically.
|
||||
"""
|
||||
|
||||
def compact_async(
|
||||
def optimize_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
"""Submit remote compaction and return a durable job after acceptance.
|
||||
@@ -3157,7 +3134,7 @@ class Table(ABC):
|
||||
Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and
|
||||
cancellation use generic HTTP job APIs and their existing permissions.
|
||||
|
||||
>>> job = table.compact_async( # doctest: +SKIP
|
||||
>>> job = table.optimize_async( # doctest: +SKIP
|
||||
... compaction_options={"target_rows_per_fragment": 1000})
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
@@ -3172,7 +3149,8 @@ class Table(ABC):
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
):
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -3181,7 +3159,7 @@ class Table(ABC):
|
||||
On a LanceDB Enterprise (remote) table, only compaction is
|
||||
currently supported. Pruning old versions and index optimization
|
||||
are silently skipped there instead of being attempted, so this
|
||||
call returns successfully, with zeroed pruning statistics, once
|
||||
call returns placeholder statistics (not completed work) once
|
||||
the compaction job has been submitted; it does not wait for that
|
||||
job to finish. Remote compaction supports per-job
|
||||
``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
|
||||
@@ -3226,6 +3204,11 @@ class Table(ABC):
|
||||
|
||||
retrain: bool, default False
|
||||
This parameter is no longer used and is deprecated.
|
||||
action: "rewrite_data", optional
|
||||
Run only data compaction, retaining old versions and skipping the
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
compaction_options: CompactionOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
@@ -5865,31 +5848,11 @@ class LanceTable(Table):
|
||||
older_than, delete_unverified=delete_unverified
|
||||
)
|
||||
|
||||
@deprecation.deprecated(
|
||||
deprecated_in="0.21.0",
|
||||
current_version=__version__,
|
||||
details="Use `Table.optimize` instead.",
|
||||
)
|
||||
def compact_files(self, *args, **kwargs) -> CompactionStats:
|
||||
"""
|
||||
Run the compaction process on the table.
|
||||
|
||||
This can be run after making several small appends to optimize the table
|
||||
for faster reads.
|
||||
|
||||
Arguments are passed onto `lance.dataset.DatasetOptimizer.compact_files`.
|
||||
(see Lance documentation for more details) For most cases, the default
|
||||
should be fine.
|
||||
"""
|
||||
stats = self.to_lance().optimize.compact_files(*args, **kwargs)
|
||||
self.checkout_latest()
|
||||
return stats
|
||||
|
||||
def compact_async(
|
||||
def optimize_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
LOOP.run(self._table.optimize_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
@@ -5899,7 +5862,8 @@ class LanceTable(Table):
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
):
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -5938,6 +5902,11 @@ class LanceTable(Table):
|
||||
|
||||
retrain: bool, default False
|
||||
This parameter is no longer used and is deprecated.
|
||||
action: "rewrite_data", optional
|
||||
Run only data compaction, retaining old versions and skipping the
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
compaction_options: CompactionOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
@@ -5952,11 +5921,12 @@ class LanceTable(Table):
|
||||
you have added or modified 100,000 or more records or run more than 20 data
|
||||
modification operations.
|
||||
"""
|
||||
LOOP.run(
|
||||
return LOOP.run(
|
||||
self._table._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup_older_than, retrain),
|
||||
delete_unverified,
|
||||
compaction_options,
|
||||
action,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -9575,16 +9545,16 @@ class AsyncTable:
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def compact_async(
|
||||
async def optimize_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> AsyncJob[CompactionResult]:
|
||||
"""Submit remote compaction; await the returned job for actual results.
|
||||
|
||||
See [Table.compact_async][lancedb.table.Table.compact_async] for options,
|
||||
See [Table.optimize_async][lancedb.table.Table.optimize_async] for options,
|
||||
permissions, completion semantics and compatibility requirements.
|
||||
"""
|
||||
return _typed_job(
|
||||
await self._inner.compact_async(compaction_options),
|
||||
await self._inner.optimize_async(compaction_options),
|
||||
CompactionResult.from_json,
|
||||
)
|
||||
|
||||
@@ -9595,6 +9565,7 @@ class AsyncTable:
|
||||
delete_unverified: bool = False,
|
||||
retrain=False,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
@@ -9604,7 +9575,7 @@ class AsyncTable:
|
||||
On a LanceDB Enterprise (remote) table, only compaction is
|
||||
currently supported. Pruning old versions and index optimization
|
||||
are silently skipped there instead of being attempted, so this
|
||||
call returns successfully, with zeroed pruning statistics, once
|
||||
call returns placeholder statistics (not completed work) once
|
||||
the compaction job has been submitted; it does not wait for that
|
||||
job to finish. Remote compaction supports per-job
|
||||
``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
|
||||
@@ -9649,6 +9620,11 @@ class AsyncTable:
|
||||
|
||||
retrain: bool, default False
|
||||
This parameter is no longer used and is deprecated.
|
||||
action: "rewrite_data", optional
|
||||
Run only data compaction, retaining old versions and skipping the
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
compaction_options: CompactionOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
@@ -9667,6 +9643,7 @@ class AsyncTable:
|
||||
_optimize_cleanup_since_ms(cleanup_older_than, retrain),
|
||||
delete_unverified,
|
||||
compaction_options,
|
||||
action,
|
||||
)
|
||||
|
||||
async def _do_optimize(
|
||||
@@ -9674,8 +9651,10 @@ class AsyncTable:
|
||||
cleanup_since_ms: Optional[int],
|
||||
delete_unverified: bool,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
return await self._inner.optimize(
|
||||
action=action,
|
||||
cleanup_since_ms=cleanup_since_ms,
|
||||
delete_unverified=delete_unverified,
|
||||
compaction_options=compaction_options,
|
||||
|
||||
@@ -70,7 +70,7 @@ async def test_maintenance_job_result_and_reopen_against_server(
|
||||
version = await table.version() if asynchronous else table.version
|
||||
if operation == "compact":
|
||||
job = await call(
|
||||
table.compact_async,
|
||||
table.optimize_async,
|
||||
compaction_options={
|
||||
"target_rows_per_fragment": 100,
|
||||
"batch_size": 128,
|
||||
|
||||
@@ -3611,7 +3611,7 @@ def test_remote_python_only_messages():
|
||||
f"{method}() is not supported in LanceDB Enterprise. "
|
||||
f"Use table.search().{method}() instead."
|
||||
)
|
||||
for method in ["compact_files", "cleanup_old_versions"]:
|
||||
for method in ["cleanup_old_versions"]:
|
||||
with pytest.warns(UserWarning) as warning:
|
||||
getattr(table, method)()
|
||||
assert (
|
||||
@@ -8471,7 +8471,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
job = await table.compact_async(
|
||||
job = await table.optimize_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
@@ -8492,7 +8492,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.compact_async(
|
||||
job = table.optimize_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
@@ -8547,11 +8547,11 @@ def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.compact_async()
|
||||
table.optimize_async()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["compact_async", "optimize"])
|
||||
@pytest.mark.parametrize("method", ["optimize_async", "optimize"])
|
||||
@pytest.mark.parametrize(
|
||||
"option",
|
||||
["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"],
|
||||
|
||||
@@ -4841,10 +4841,10 @@ def test_compact_cleanup(tmp_db: DBConnection):
|
||||
assert len(table) == 3
|
||||
assert table.version == 2
|
||||
|
||||
stats = table.compact_files()
|
||||
stats = table.optimize(action="rewrite_data").compaction
|
||||
assert len(table) == 3
|
||||
# Compact_files bump 2 versions.
|
||||
assert table.version == 4
|
||||
optimized_version = table.version
|
||||
assert optimized_version > 2
|
||||
assert stats.fragments_removed > 0
|
||||
assert stats.fragments_added == 1
|
||||
|
||||
@@ -4853,10 +4853,10 @@ def test_compact_cleanup(tmp_db: DBConnection):
|
||||
|
||||
stats = table.cleanup_old_versions(older_than=timedelta(0), delete_unverified=True)
|
||||
assert stats.bytes_removed > 0
|
||||
assert table.version == 4
|
||||
assert table.version == optimized_version
|
||||
|
||||
with pytest.raises(Exception, match="Version 3 no longer exists"):
|
||||
table.checkout(3)
|
||||
with pytest.raises(Exception, match="Version 2 no longer exists"):
|
||||
table.checkout(2)
|
||||
|
||||
|
||||
def test_count_rows(mem_db: DBConnection):
|
||||
@@ -6435,3 +6435,74 @@ async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, m
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_optimize_rewrite_only_preserves_versions_and_index(
|
||||
tmp_path, asynchronous
|
||||
):
|
||||
"""A rewrite must retain history and leave incremental indexing to full Optimize."""
|
||||
db = (
|
||||
(await lancedb.connect_async(str(tmp_path)))
|
||||
if asynchronous
|
||||
else lancedb.connect(str(tmp_path))
|
||||
)
|
||||
|
||||
async def call(obj, name, *args, **kwargs):
|
||||
result = getattr(obj, name)(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
table = await call(db, "create_table", "rewrite", [{"id": 1}])
|
||||
await call(table, "add", [{"id": 2}])
|
||||
await call(table, "create_index", "id", config=BTree())
|
||||
await call(table, "add", [{"id": 3}])
|
||||
await call(table, "add", [{"id": 4}])
|
||||
before = await call(table, "list_versions")
|
||||
stats = await call(table, "optimize", action="rewrite_data")
|
||||
assert stats.compaction.fragments_removed == 4
|
||||
assert stats.compaction.fragments_added == 2
|
||||
assert stats.prune.old_versions_removed == 0
|
||||
assert len(await call(table, "list_versions")) > len(before)
|
||||
index_stats = await call(table, "index_stats", "id_idx")
|
||||
assert (
|
||||
index_stats.num_unindexed_rows
|
||||
if asynchronous
|
||||
else index_stats["num_unindexed_rows"]
|
||||
) == 2
|
||||
await call(table, "optimize")
|
||||
index_stats = await call(table, "index_stats", "id_idx")
|
||||
assert (
|
||||
index_stats.num_unindexed_rows
|
||||
if asynchronous
|
||||
else index_stats["num_unindexed_rows"]
|
||||
) == 0
|
||||
await call(table, "checkout", 1)
|
||||
assert await call(table, "count_rows") == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs",
|
||||
[
|
||||
{"action": "unknown"},
|
||||
{"action": "rewrite_data", "cleanup_older_than": timedelta(days=1)},
|
||||
{"action": "rewrite_data", "delete_unverified": True},
|
||||
],
|
||||
)
|
||||
async def test_optimize_action_validation(mem_db_async, kwargs):
|
||||
table = await mem_db_async.create_table("rewrite_invalid", [{"id": 1}])
|
||||
with pytest.raises(ValueError, match="action"):
|
||||
await table.optimize(**kwargs)
|
||||
assert await table.version() == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_optimize_async_requires_remote(mem_db, mem_db_async):
|
||||
table = mem_db.create_table("local_job", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="only supported on remote tables"):
|
||||
table.optimize_async()
|
||||
async_table = await mem_db_async.create_table("local_job", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="only supported on remote tables"):
|
||||
await async_table.optimize_async()
|
||||
assert not hasattr(async_table, "compact_async")
|
||||
|
||||
@@ -25,7 +25,7 @@ import pytest
|
||||
"create_fts_index",
|
||||
"search",
|
||||
"cleanup_old_versions",
|
||||
"compact_files",
|
||||
"optimize_async",
|
||||
"optimize",
|
||||
"to_polars",
|
||||
],
|
||||
@@ -179,7 +179,6 @@ def test_fts_unsupported_options(sync_table, kwargs, message):
|
||||
"cleanup_old_versions",
|
||||
{"older_than": timedelta(days=1), "delete_unverified": True},
|
||||
),
|
||||
("compact_files", {"target_rows_per_fragment": 1000}),
|
||||
],
|
||||
)
|
||||
def test_remote_maintenance_options_warn(method, kwargs):
|
||||
@@ -200,6 +199,7 @@ def test_remote_optimize_options():
|
||||
delete_unverified=True,
|
||||
retrain=True,
|
||||
compaction_options=None,
|
||||
action=None,
|
||||
)
|
||||
|
||||
|
||||
@@ -258,3 +258,23 @@ def test_index_replacement_defaults(tmp_path):
|
||||
with pytest.warns(DeprecationWarning):
|
||||
sync.create_scalar_index("id")
|
||||
assert len(list(table.list_indices())) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [Table, LanceTable, RemoteTable])
|
||||
def test_optimize_has_no_legacy_compaction_aliases(cls):
|
||||
assert not hasattr(cls, "compact_files")
|
||||
assert not hasattr(cls, "compact_async")
|
||||
|
||||
|
||||
def test_remote_optimize_rewrite_action():
|
||||
handle = MagicMock()
|
||||
handle.optimize = AsyncMock(return_value="accepted")
|
||||
table = RemoteTable(handle, "test_db")
|
||||
assert table.optimize(action="rewrite_data") == "accepted"
|
||||
handle.optimize.assert_awaited_once_with(
|
||||
cleanup_older_than=None,
|
||||
delete_unverified=False,
|
||||
retrain=False,
|
||||
compaction_options=None,
|
||||
action="rewrite_data",
|
||||
)
|
||||
|
||||
+43
-10
@@ -2297,7 +2297,7 @@ impl Table {
|
||||
|
||||
/// Submit remote compaction and retain its durable job and actual result.
|
||||
#[pyo3(signature = (compaction_options=None))]
|
||||
pub fn compact_async<'py>(
|
||||
pub fn optimize_async<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
compaction_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
@@ -2313,19 +2313,34 @@ impl Table {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.compact_async(overrides).await.infer_error()?;
|
||||
let job = inner.optimize_async(overrides).await.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
})
|
||||
}
|
||||
|
||||
/// Optimize the on-disk data by compacting and pruning old data, for better performance.
|
||||
#[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))]
|
||||
#[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None, action=None))]
|
||||
pub fn optimize<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
cleanup_since_ms: Option<u64>,
|
||||
delete_unverified: Option<bool>,
|
||||
compaction_options: Option<&Bound<'py, PyDict>>,
|
||||
action: Option<String>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let rewrite_only = match action.as_deref() {
|
||||
None => false,
|
||||
Some("rewrite_data") => true,
|
||||
Some(_) => {
|
||||
return Err(PyValueError::new_err(
|
||||
"action must be 'rewrite_data' or None",
|
||||
));
|
||||
}
|
||||
};
|
||||
if rewrite_only && (cleanup_since_ms.is_some() || delete_unverified == Some(true)) {
|
||||
return Err(PyValueError::new_err(
|
||||
"action='rewrite_data' cannot be combined with cleanup options",
|
||||
));
|
||||
}
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let target_specified = compaction_options
|
||||
.map(|options| options.contains("target_rows_per_fragment"))
|
||||
@@ -2346,9 +2361,18 @@ impl Table {
|
||||
};
|
||||
future_into_py(self_.py(), async move {
|
||||
let stats = if inner.as_native().is_some() {
|
||||
inner
|
||||
.optimize_full(compaction_options, older_than, None, delete_unverified)
|
||||
.await
|
||||
if rewrite_only {
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::Compact {
|
||||
options: compaction_options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full(compaction_options, older_than, None, delete_unverified)
|
||||
.await
|
||||
}
|
||||
} else {
|
||||
let mut overrides =
|
||||
lancedb::table::optimize::CompactionOverrides::try_from(compaction_options)
|
||||
@@ -2356,13 +2380,22 @@ impl Table {
|
||||
if !target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
inner
|
||||
.optimize_full_with_overrides(overrides, older_than, None, delete_unverified)
|
||||
.await
|
||||
if rewrite_only {
|
||||
inner.optimize(overrides).await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full_with_overrides(
|
||||
overrides,
|
||||
older_than,
|
||||
None,
|
||||
delete_unverified,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
.infer_error()?;
|
||||
let compaction_stats = stats.compaction.unwrap();
|
||||
let prune_stats = stats.prune.unwrap();
|
||||
let prune_stats = stats.prune.unwrap_or_default();
|
||||
Ok(OptimizeStats {
|
||||
compaction: CompactionStats {
|
||||
files_added: compaction_stats.files_added as u64,
|
||||
|
||||
Reference in New Issue
Block a user