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


##########
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:
   Good catch — fixed in 1177911d. Added `_normalize_collection_name` 
(capitalizing the first character to match Weaviate's canonical form), guarded 
deletion with `previous_collection != normalized_target`, and parametrized 
`test_alias_already_on_target_is_a_no_op` with both `"Docs_v2"` and `"docs_v2"`.



##########
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:
   Updated in 1177911d to return `None` on the already-pointing-to-target 
branch and log a warning when `delete_previous_collection=True`, 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:
+            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:
   Added in 1177911d: before deleting `previous_collection`, the operator 
checks `self.hook.list_aliases(collection_name=previous_collection)` and skips 
deletion with a warning listing the remaining aliases if any are still 
attached, with unit test coverage.



##########
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:
   Updated `providers/weaviate/docs/operators/weaviate.rst` in 1177911d to 
document `create_if_missing` (and its `False` error behavior), the 
dangling-alias deletion guard, and the `None` return cases.



##########
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:
   Fixed in 1177911d: assigned `example_dag = example_weaviate_swap_alias()` 
and passed `example_dag` to `get_test_run(example_dag)`.



-- 
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