kaxil commented on code in PR #77480:
URL: https://github.com/apache/airflow/pull/77480#discussion_r4688658144


##########
providers/weaviate/src/airflow/providers/weaviate/operators/weaviate.py:
##########
@@ -183,3 +183,84 @@ def execute(self, context: Context) -> Sequence[dict[str, 
UUID | str] | None]:
             tenant=self.tenant,
         )
         return batch_delete_error
+
+
+class WeaviateSwapAliasOperator(BaseOperator):
+    """
+    Point a Weaviate alias to a collection, creating the alias if needed.
+
+    Use it for zero-downtime re-indexing: load and embed the data into a new 
collection, then swap the
+    alias that applications query to the new collection. The switch is atomic. 
Requires Weaviate 1.32
+    or later.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:WeaviateSwapAliasOperator`
+
+    :param conn_id: The Weaviate connection.
+    :param alias_name: The alias to point to ``target_collection``.
+    :param target_collection: The collection the alias should point to.
+    :param create_if_missing: Create the alias if it does not exist. If 
``False``, a missing alias
+        raises an error.
+    :param delete_previous_collection: After the swap, delete the collection 
the alias pointed to
+        before. The deletion cannot be undone.
+    :param hook_params: Optional config params to be passed to the underlying 
hook.
+        Should match the desired hook constructor params.
+    :return: The name of the collection the alias pointed to before, or 
``None`` if the alias was created.
+    """
+
+    template_fields: Sequence[str] = (
+        "conn_id",
+        "alias_name",
+        "target_collection",
+    )
+
+    def __init__(
+        self,
+        conn_id: str,
+        alias_name: str,
+        target_collection: str,
+        create_if_missing: bool = True,
+        delete_previous_collection: bool = False,
+        hook_params: dict | None = None,
+        **kwargs: Any,
+    ) -> None:
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.alias_name = alias_name
+        self.target_collection = target_collection
+        self.create_if_missing = create_if_missing
+        self.delete_previous_collection = delete_previous_collection
+        self.hook_params = hook_params or {}
+
+    @cached_property
+    def hook(self) -> WeaviateHook:
+        """Return an instance of the WeaviateHook."""
+        return WeaviateHook(conn_id=self.conn_id, **self.hook_params)
+
+    def execute(self, context: Context) -> str | None:
+        alias = self.hook.get_alias(self.alias_name)
+        if alias is None:
+            if not self.create_if_missing:
+                raise ValueError(f"Alias '{self.alias_name}' does not exist 
and create_if_missing is False.")
+            self.hook.create_alias(self.alias_name, self.target_collection)
+            self.log.info("Created alias '%s' pointing to '%s'.", 
self.alias_name, self.target_collection)
+            return None
+
+        previous_collection = alias.collection
+        if previous_collection == self.target_collection:
+            self.log.info("Alias '%s' already points to '%s'.", 
self.alias_name, self.target_collection)
+            return previous_collection

Review Comment:
   If `delete_collections` raises after a successful swap, the retry lands on 
this branch and succeeds without deleting the old collection, so it leaks 
silently. This branch also returns the live collection's name as the "previous" 
one, and the how-to suggests a later task pick that up from XCom, most likely 
to clean it up. Would returning `None` here (plus a warning when 
`delete_previous_collection` is set) work, so a non-None return always means a 
different collection was swapped out?



##########
providers/weaviate/src/airflow/providers/weaviate/operators/weaviate.py:
##########
@@ -183,3 +183,84 @@ def execute(self, context: Context) -> Sequence[dict[str, 
UUID | str] | None]:
             tenant=self.tenant,
         )
         return batch_delete_error
+
+
+class WeaviateSwapAliasOperator(BaseOperator):
+    """
+    Point a Weaviate alias to a collection, creating the alias if needed.
+
+    Use it for zero-downtime re-indexing: load and embed the data into a new 
collection, then swap the
+    alias that applications query to the new collection. The switch is atomic. 
Requires Weaviate 1.32
+    or later.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:WeaviateSwapAliasOperator`
+
+    :param conn_id: The Weaviate connection.
+    :param alias_name: The alias to point to ``target_collection``.
+    :param target_collection: The collection the alias should point to.
+    :param create_if_missing: Create the alias if it does not exist. If 
``False``, a missing alias
+        raises an error.
+    :param delete_previous_collection: After the swap, delete the collection 
the alias pointed to
+        before. The deletion cannot be undone.
+    :param hook_params: Optional config params to be passed to the underlying 
hook.
+        Should match the desired hook constructor params.
+    :return: The name of the collection the alias pointed to before, or 
``None`` if the alias was created.
+    """
+
+    template_fields: Sequence[str] = (
+        "conn_id",
+        "alias_name",
+        "target_collection",
+    )
+
+    def __init__(
+        self,
+        conn_id: str,
+        alias_name: str,
+        target_collection: str,
+        create_if_missing: bool = True,
+        delete_previous_collection: bool = False,
+        hook_params: dict | None = None,
+        **kwargs: Any,
+    ) -> None:
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.alias_name = alias_name
+        self.target_collection = target_collection
+        self.create_if_missing = create_if_missing
+        self.delete_previous_collection = delete_previous_collection
+        self.hook_params = hook_params or {}
+
+    @cached_property
+    def hook(self) -> WeaviateHook:
+        """Return an instance of the WeaviateHook."""
+        return WeaviateHook(conn_id=self.conn_id, **self.hook_params)
+
+    def execute(self, context: Context) -> str | None:
+        alias = self.hook.get_alias(self.alias_name)
+        if alias is None:
+            if not self.create_if_missing:
+                raise ValueError(f"Alias '{self.alias_name}' does not exist 
and create_if_missing is False.")
+            self.hook.create_alias(self.alias_name, self.target_collection)
+            self.log.info("Created alias '%s' pointing to '%s'.", 
self.alias_name, self.target_collection)
+            return None
+
+        previous_collection = alias.collection
+        if previous_collection == self.target_collection:

Review Comment:
   Weaviate stores collection names with the first letter capitalized, so 
`alias.collection` comes back as `Products_v2` when the user passed 
`target_collection="products_v2"`. On a rerun this comparison is False, the 
update goes through, and with `delete_previous_collection=True` the next lines 
delete the collection the alias now points to. Running the same swap task twice 
against a real Weaviate server left no collections at all. Could this compare 
against the server's form of the name and refuse to delete when the two match? 
The no-op test uses the same string on both sides, so a lower-case target there 
would cover it.



##########
providers/weaviate/docs/operators/weaviate.rst:
##########
@@ -58,3 +58,27 @@ An example using the operator to ingest data without vectors 
retrieved from a py
     :language: python
     :start-after: [START 
howto_operator_weaviate_ingest_callable_data_without_vectors]
     :end-before: [END 
howto_operator_weaviate_ingest_callable_data_without_vectors]
+
+.. _howto/operator:WeaviateSwapAliasOperator:
+
+WeaviateSwapAliasOperator
+=========================
+
+Use the 
:class:`~airflow.providers.weaviate.operators.weaviate.WeaviateSwapAliasOperator`
 to point a
+Weaviate alias to a collection. Applications that query the alias instead of 
the collection name can then
+be moved to a freshly built collection without downtime: load and embed the 
data into a new collection,
+then swap the alias to it. The alias is created if it does not exist. Aliases 
require Weaviate 1.32 or later.

Review Comment:
   This reads as if the alias is always created, but with 
`create_if_missing=False` a missing alias is an error. Could the page mention 
the flag?



##########
providers/weaviate/src/airflow/providers/weaviate/operators/weaviate.py:
##########
@@ -183,3 +183,84 @@ def execute(self, context: Context) -> Sequence[dict[str, 
UUID | str] | None]:
             tenant=self.tenant,
         )
         return batch_delete_error
+
+
+class WeaviateSwapAliasOperator(BaseOperator):
+    """
+    Point a Weaviate alias to a collection, creating the alias if needed.
+
+    Use it for zero-downtime re-indexing: load and embed the data into a new 
collection, then swap the
+    alias that applications query to the new collection. The switch is atomic. 
Requires Weaviate 1.32
+    or later.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:WeaviateSwapAliasOperator`
+
+    :param conn_id: The Weaviate connection.
+    :param alias_name: The alias to point to ``target_collection``.
+    :param target_collection: The collection the alias should point to.
+    :param create_if_missing: Create the alias if it does not exist. If 
``False``, a missing alias
+        raises an error.
+    :param delete_previous_collection: After the swap, delete the collection 
the alias pointed to
+        before. The deletion cannot be undone.
+    :param hook_params: Optional config params to be passed to the underlying 
hook.
+        Should match the desired hook constructor params.
+    :return: The name of the collection the alias pointed to before, or 
``None`` if the alias was created.
+    """
+
+    template_fields: Sequence[str] = (
+        "conn_id",
+        "alias_name",
+        "target_collection",
+    )
+
+    def __init__(
+        self,
+        conn_id: str,
+        alias_name: str,
+        target_collection: str,
+        create_if_missing: bool = True,
+        delete_previous_collection: bool = False,
+        hook_params: dict | None = None,
+        **kwargs: Any,
+    ) -> None:
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.alias_name = alias_name
+        self.target_collection = target_collection
+        self.create_if_missing = create_if_missing
+        self.delete_previous_collection = delete_previous_collection
+        self.hook_params = hook_params or {}
+
+    @cached_property
+    def hook(self) -> WeaviateHook:
+        """Return an instance of the WeaviateHook."""
+        return WeaviateHook(conn_id=self.conn_id, **self.hook_params)
+
+    def execute(self, context: Context) -> str | None:
+        alias = self.hook.get_alias(self.alias_name)
+        if alias is None:
+            if not self.create_if_missing:
+                raise ValueError(f"Alias '{self.alias_name}' does not exist 
and create_if_missing is False.")
+            self.hook.create_alias(self.alias_name, self.target_collection)
+            self.log.info("Created alias '%s' pointing to '%s'.", 
self.alias_name, self.target_collection)
+            return None
+
+        previous_collection = alias.collection
+        if previous_collection == self.target_collection:
+            self.log.info("Alias '%s' already points to '%s'.", 
self.alias_name, self.target_collection)
+            return previous_collection
+
+        if not self.hook.update_alias(self.alias_name, self.target_collection):
+            raise RuntimeError(f"Alias '{self.alias_name}' disappeared before 
it could be updated.")
+        self.log.info(
+            "Swapped alias '%s' from '%s' to '%s'.",
+            self.alias_name,
+            previous_collection,
+            self.target_collection,
+        )
+        if self.delete_previous_collection:
+            self.hook.delete_collections(previous_collection)

Review Comment:
   Weaviate accepts deleting a collection that other aliases still point to and 
leaves those aliases dangling, so queries through them start failing. Should 
this check `self.hook.list_aliases(collection_name=previous_collection)` first 
and skip the delete with a warning if any remain?



##########
providers/weaviate/tests/system/weaviate/example_weaviate_swap_alias.py:
##########
@@ -0,0 +1,107 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import pendulum
+from weaviate.classes.config import Configure
+
+try:
+    from airflow.sdk import dag, task, teardown
+except ImportError:
+    # Airflow 2 path
+    from airflow.decorators import dag, task, teardown  # type: 
ignore[attr-defined,no-redef]
+from airflow.providers.weaviate.operators.weaviate import 
WeaviateIngestOperator, WeaviateSwapAliasOperator
+
+ALIAS_NAME = "QuestionsAlias"
+OLD_COLLECTION = "QuestionsAliasV1"
+NEW_COLLECTION = "QuestionsAliasV2"
+
+sample_data = [
+    {"Question": "This organ removes excess glucose from the blood", "Vector": 
[-0.0066, -0.0042, 0.0305]},
+    {
+        "Question": "It's the only living mammal in the order Proboseidea",
+        "Vector": [-0.0167, -0.0009, -0.0125],
+    },
+]
+
+
+@dag(
+    schedule=None,
+    start_date=pendulum.datetime(2021, 1, 1, tz="UTC"),
+    catchup=False,
+    tags=["example", "weaviate"],
+)
+def example_weaviate_swap_alias():
+    """Example DAG re-indexing into a new collection and swapping an alias to 
it without downtime."""
+
+    @task()
+    def create_collections():
+        from airflow.providers.weaviate.hooks.weaviate import WeaviateHook
+
+        hook = WeaviateHook()
+        for name in (OLD_COLLECTION, NEW_COLLECTION):
+            hook.create_collection(name, 
vector_config=Configure.Vectors.self_provided())
+
+    point_alias_to_old_collection = WeaviateSwapAliasOperator(
+        task_id="point_alias_to_old_collection",
+        conn_id="weaviate_default",
+        alias_name=ALIAS_NAME,
+        target_collection=OLD_COLLECTION,
+    )
+
+    ingest_into_new_collection = WeaviateIngestOperator(
+        task_id="ingest_into_new_collection",
+        conn_id="weaviate_default",
+        collection_name=NEW_COLLECTION,
+        input_data=sample_data,
+    )
+
+    # [START howto_operator_weaviate_swap_alias]
+    swap_alias_to_new_collection = WeaviateSwapAliasOperator(
+        task_id="swap_alias_to_new_collection",
+        conn_id="weaviate_default",
+        alias_name=ALIAS_NAME,
+        target_collection=NEW_COLLECTION,
+        delete_previous_collection=True,
+    )
+    # [END howto_operator_weaviate_swap_alias]
+
+    @teardown
+    @task
+    def delete_alias_and_collections():
+        from airflow.providers.weaviate.hooks.weaviate import WeaviateHook
+
+        hook = WeaviateHook()
+        hook.delete_alias(ALIAS_NAME)
+        hook.delete_collections([OLD_COLLECTION, NEW_COLLECTION])
+
+    (
+        create_collections()
+        >> point_alias_to_old_collection
+        >> ingest_into_new_collection
+        >> swap_alias_to_new_collection
+        >> delete_alias_and_collections()
+    )
+
+
+example_weaviate_swap_alias()
+
+
+from tests_common.test_utils.system_tests import get_test_run  # noqa: E402
+
+# Needed to run the example DAG with pytest (see: 
contributing-docs/testing/system_tests.rst)
+test_run = get_test_run(dag)

Review Comment:
   `dag` here is the decorator imported from `airflow.sdk`, not the Dag, so 
running this as a system test fails with `AttributeError: 'function' object has 
no attribute 'on_failure_callback'`. The other weaviate examples have the same 
line, but since this file is new, could it keep the result of 
`example_weaviate_swap_alias()` on line 101 and pass that instead?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to