Elffuss BraidHub

kikocis/lancedb public

feat(python): merge_insert in async Python (#1707)

Fixes #1401
Changeset003c3ff7b96fc5980dec5f02ba003f1eea0ae4197b5f64fa7610fe6f6c1533b3
AuthorWill Jones <willjones127@gmail.com> · 2024-10-01 10:06 -07:00
CommitterGitHub <noreply@github.com> · 2024-10-01 10:06 -07:00
Parents70d43ccc8e37

Browse the files at this changeset

4 files changed

modified python/python/lancedb/merge.py +1 −1
@@ -104,4 +104,4 @@
104104 fill_value: float, default 0.
105105 The value to use when filling vectors. Only used if on_bad_vectors="fill".
106106 """
107- self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
107+ return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
modified python/python/lancedb/table.py +25 −1
@@ -2464,7 +2464,31 @@
24642464 on_bad_vectors: str,
24652465 fill_value: float,
24662466 ):
2467- pass
2467+ schema = await self.schema()
2468+ if on_bad_vectors is None:
2469+ on_bad_vectors = "error"
2470+ if fill_value is None:
2471+ fill_value = 0.0
2472+ data, _ = _sanitize_data(
2473+ new_data,
2474+ schema,
2475+ metadata=schema.metadata,
2476+ on_bad_vectors=on_bad_vectors,
2477+ fill_value=fill_value,
2478+ )
2479+ if isinstance(data, pa.Table):
2480+ data = pa.RecordBatchReader.from_batches(data.schema, data.to_batches())
2481+ await self._inner.execute_merge_insert(
2482+ data,
2483+ dict(
2484+ on=merge._on,
2485+ when_matched_update_all=merge._when_matched_update_all,
2486+ when_matched_update_all_condition=merge._when_matched_update_all_condition,
2487+ when_not_matched_insert_all=merge._when_not_matched_insert_all,
2488+ when_not_matched_by_source_delete=merge._when_not_matched_by_source_delete,
2489+ when_not_matched_by_source_condition=merge._when_not_matched_by_source_condition,
2490+ ),
2491+ )
24682492
24692493 async def delete(self, where: str):
24702494 """Delete rows from the table.
modified python/python/tests/test_table.py +76 −5
@@ -636,11 +636,13 @@
636636 new_data = pa.table({"a": [2, 4], "b": ["x", "z"]})
637637
638638 # replace-range
639- table.merge_insert(
640- "a"
641- ).when_matched_update_all().when_not_matched_insert_all().when_not_matched_by_source_delete(
642- "a > 2"
643- ).execute(new_data)
639+ (
640+ table.merge_insert("a")
641+ .when_matched_update_all()
642+ .when_not_matched_insert_all()
643+ .when_not_matched_by_source_delete("a > 2")
644+ .execute(new_data)
645+ )
644646
645647 expected = pa.table({"a": [1, 2, 4], "b": ["a", "x", "z"]})
646648 assert table.to_arrow().sort_by("a") == expected
@@ -658,6 +660,75 @@
658660 assert table.to_arrow().sort_by("a") == expected
659661
660662
663+@pytest.mark.asyncio
664+async def test_merge_insert_async(db_async: AsyncConnection):
665+ data = pa.table({"a": [1, 2, 3], "b": ["a", "b", "c"]})
666+ table = await db_async.create_table("some_table", data=data)
667+ assert await table.count_rows() == 3
668+ version = await table.version()
669+
670+ new_data = pa.table({"a": [2, 3, 4], "b": ["x", "y", "z"]})
671+
672+ # upsert
673+ await (
674+ table.merge_insert("a")
675+ .when_matched_update_all()
676+ .when_not_matched_insert_all()
677+ .execute(new_data)
678+ )
679+ expected = pa.table({"a": [1, 2, 3, 4], "b": ["a", "x", "y", "z"]})
680+ assert (await table.to_arrow()).sort_by("a") == expected
681+
682+ await table.checkout(version)
683+ await table.restore()
684+
685+ # conditional update
686+ await (
687+ table.merge_insert("a")
688+ .when_matched_update_all(where="target.b = 'b'")
689+ .execute(new_data)
690+ )
691+ expected = pa.table({"a": [1, 2, 3], "b": ["a", "x", "c"]})
692+ assert (await table.to_arrow()).sort_by("a") == expected
693+
694+ await table.checkout(version)
695+ await table.restore()
696+
697+ # insert-if-not-exists
698+ await table.merge_insert("a").when_not_matched_insert_all().execute(new_data)
699+ expected = pa.table({"a": [1, 2, 3, 4], "b": ["a", "b", "c", "z"]})
700+ assert (await table.to_arrow()).sort_by("a") == expected
701+
702+ await table.checkout(version)
703+ await table.restore()
704+
705+ # replace-range
706+ new_data = pa.table({"a": [2, 4], "b": ["x", "z"]})
707+ await (
708+ table.merge_insert("a")
709+ .when_matched_update_all()
710+ .when_not_matched_insert_all()
711+ .when_not_matched_by_source_delete("a > 2")
712+ .execute(new_data)
713+ )
714+ expected = pa.table({"a": [1, 2, 4], "b": ["a", "x", "z"]})
715+ assert (await table.to_arrow()).sort_by("a") == expected
716+
717+ await table.checkout(version)
718+ await table.restore()
719+
720+ # replace-range no condition
721+ await (
722+ table.merge_insert("a")
723+ .when_matched_update_all()
724+ .when_not_matched_insert_all()
725+ .when_not_matched_by_source_delete()
726+ .execute(new_data)
727+ )
728+ expected = pa.table({"a": [2, 4], "b": ["x", "z"]})
729+ assert (await table.to_arrow()).sort_by("a") == expected
730+
731+
661732 def test_create_with_embedding_function(db):
662733 class MyTable(LanceModel):
663734 text: str
modified python/src/table.rs +37 −1
@@ -9,7 +9,7 @@
99 exceptions::{PyRuntimeError, PyValueError},
1010 pyclass, pymethods,
1111 types::{PyDict, PyDictMethods, PyString},
12- Bound, PyAny, PyRef, PyResult, Python, ToPyObject,
12+ Bound, FromPyObject, PyAny, PyRef, PyResult, Python, ToPyObject,
1313 };
1414 use pyo3_asyncio_0_21::tokio::future_into_py;
1515
@@ -331,6 +331,31 @@
331331 })
332332 }
333333
334+ pub fn execute_merge_insert<'a>(
335+ self_: PyRef<'a, Self>,
336+ data: Bound<'a, PyAny>,
337+ parameters: MergeInsertParams,
338+ ) -> PyResult<Bound<'a, PyAny>> {
339+ let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
340+ let on = parameters.on.iter().map(|s| s.as_str()).collect::<Vec<_>>();
341+ let mut builder = self_.inner_ref()?.merge_insert(&on);
342+ if parameters.when_matched_update_all {
343+ builder.when_matched_update_all(parameters.when_matched_update_all_condition);
344+ }
345+ if parameters.when_not_matched_insert_all {
346+ builder.when_not_matched_insert_all();
347+ }
348+ if parameters.when_not_matched_by_source_delete {
349+ builder
350+ .when_not_matched_by_source_delete(parameters.when_not_matched_by_source_condition);
351+ }
352+
353+ future_into_py(self_.py(), async move {
354+ builder.execute(Box::new(batches)).await.infer_error()?;
355+ Ok(())
356+ })
357+ }
358+
334359 pub fn uses_v2_manifest_paths(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
335360 let inner = self_.inner_ref()?.clone();
336361 future_into_py(self_.py(), async move {
@@ -355,3 +380,14 @@
355380 })
356381 }
357382 }
383+
384+#[derive(FromPyObject)]
385+#[pyo3(from_item_all)]
386+pub struct MergeInsertParams {
387+ on: Vec<String>,
388+ when_matched_update_all: bool,
389+ when_matched_update_all_condition: Option<String>,
390+ when_not_matched_insert_all: bool,
391+ when_not_matched_by_source_delete: bool,
392+ when_not_matched_by_source_condition: Option<String>,
393+}