jrmccluskey commented on code in PR #31657: URL: https://github.com/apache/beam/pull/31657#discussion_r1664607697
########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider +from apache_beam import coders + +import typing + +# Set the logging level to reduce verbose information +import logging + +logging.root.setLevel(logging.INFO) +logger = logging.getLogger(__name__) + +import redis + +__all__ = ['InsertDocInRedis', 'InsertEmbeddingInRedis'] + + +class Document(typing.NamedTuple): + id: str + url: str + title: str + text: str + + +coders.registry.register_coder(Document, coders.RowCoder) + +"""This module implements IO classes to read write data on Redis. + + +Insert Doc in Redis: +----------------- +:class:`InsertDocInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') +class InsertDocInRedis(PTransform): + """InsertDocInRedis is a ``PTransform`` that writes a ``PCollection`` of + key, value tuple or 2-element array into a redis server. + """ + + def __init__(self, host=None, port=None, command=None, batch_size=100): + """ + + Args: + host (str, ValueProvider): The redis host + port (int, ValueProvider): The redis port + batch_size(int, ValueProvider): Number of key, values pairs to write at once + command : command to be executed with redis client + + Returns: + :class:`~apache_beam.transforms.ptransform.PTransform` + + """ + if not isinstance(host, (str, unicode, ValueProvider)): Review Comment: Yeah 100% don't use value providers here ########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider Review Comment: You shouldn't be using Value Providers, those are used in Dataflow classic templates ########## examples/notebooks/beam-ml/rag_usecase/redis_enrichment.py: ########## @@ -0,0 +1,124 @@ +# +# 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. + +"""This module implements enrichment classes to implement semantic search on Redis Vector DB. + + +Redis :Enrichment Handler +----------------- +:class:`RedisEnrichmentHandler` is a ``EnrichmentSourceHandler`` that performs enrichment/search +by fetching the similar text to the user query/prompt from the knowledge base (redis vector DB) and returns +the similar text along with its embeddings as Beam.Row Object. + +Example usage:: + redis_handler = RedisEnrichmentHandler(redis_host='127.0.0.1', redis_port=6379) + + pipeline | Enrichment(redis_handler) + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +import logging + + +import numpy as np +import redis +from redis.commands.search.query import Query + +import apache_beam as beam +from apache_beam.transforms.enrichment import EnrichmentSourceHandler +from apache_beam.transforms.enrichment_handlers.utils import ExceptionLevel + +__all__ = [ + 'RedisEnrichmentHandler', +] + + +_LOGGER = logging.getLogger(__name__) + + +class RedisEnrichmentHandler(EnrichmentSourceHandler[beam.Row, beam.Row]): + """A handler for :class:`apache_beam.transforms.enrichment.Enrichment` + transform to interact with redis vector DB. + + Args: + redis_host (str): Redis Host to connect to redis DB + redis_port (int): Redis Port to connect to redis DB + index_name (str): Index Name created for searching in Redis DB + vector_field (str): vector field to compute similarity score in vector DB + return_fields (list): returns list of similar text and its embeddings + hybrid_fields (str): fields to be selected + k (int): Value of K in KNN algorithm for searching in redis + """ + + def __init__( + self, + redis_host: str, + redis_port: int, + index_name: str = "embeddings-index", + vector_field: str = "text_vector", + return_fields: list = ["id", "title", "url", "text"], + hybrid_fields: str = "*", + k: int = 2, + ): + + self.redis_host = redis_host + self.redis_port = redis_port + self.index_name = index_name + self.vector_field = vector_field + self.return_fields = return_fields + self.hybrid_fields = hybrid_fields + self.k = k + self.client = None + + def __enter__(self): + """connect to the redis DB using redis client.""" + self.client = redis.Redis(host=self.redis_host, port=self.redis_port) + + + def __call__(self, request: beam.Row, *args, **kwargs): + """ + Reads a row from the redis Vector DB and returns + a `Tuple` of request and response. + + Args: + request: the input `beam.Row` to enrich. + """ + + + # read embedding vector for user query + + embedded_query = request['text'] + + + # Prepare the Query + base_query = f'{self.hybrid_fields}=>[KNN {self.k} @{self.vector_field} $vector AS vector_score]' + query = ( + Query(base_query) + .return_fields(*self.return_fields) + # .sort_by("vector_score") + .paging(0, self.k) + .dialect(2) + ) + + params_dict = {"vector": np.array(embedded_query).astype(dtype=np.float32).tobytes()} + + # perform vector search + results = self.client.ft(self.index_name).search(query, params_dict) + + return beam.Row(text=embedded_query), beam.Row(docs = results.docs) Review Comment: Would you want to return a tuple of `request, beam.Row(docs=results.docs)` instead? Or is stripping out the full input row and rebuilding it with just the text field of some value? ########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider +from apache_beam import coders + +import typing + +# Set the logging level to reduce verbose information +import logging + +logging.root.setLevel(logging.INFO) +logger = logging.getLogger(__name__) + +import redis + +__all__ = ['InsertDocInRedis', 'InsertEmbeddingInRedis'] + + +class Document(typing.NamedTuple): + id: str + url: str + title: str + text: str + + +coders.registry.register_coder(Document, coders.RowCoder) + +"""This module implements IO classes to read write data on Redis. + + +Insert Doc in Redis: +----------------- +:class:`InsertDocInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') +class InsertDocInRedis(PTransform): + """InsertDocInRedis is a ``PTransform`` that writes a ``PCollection`` of + key, value tuple or 2-element array into a redis server. + """ + + def __init__(self, host=None, port=None, command=None, batch_size=100): Review Comment: Instead of doing manual type checking in this function, annotate your input types: https://docs.python.org/3/library/typing.html You also shouldn't specify `None` base types for required inputs, those are only valid defaults for optional parameters (which should be type hinted as such) ########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider +from apache_beam import coders + +import typing + +# Set the logging level to reduce verbose information +import logging + +logging.root.setLevel(logging.INFO) +logger = logging.getLogger(__name__) + +import redis + +__all__ = ['InsertDocInRedis', 'InsertEmbeddingInRedis'] + + +class Document(typing.NamedTuple): + id: str + url: str + title: str + text: str + + +coders.registry.register_coder(Document, coders.RowCoder) + +"""This module implements IO classes to read write data on Redis. + + +Insert Doc in Redis: +----------------- +:class:`InsertDocInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') Review Comment: Why mark your transform as deprecated? ########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider +from apache_beam import coders + +import typing + +# Set the logging level to reduce verbose information +import logging + +logging.root.setLevel(logging.INFO) +logger = logging.getLogger(__name__) + +import redis + +__all__ = ['InsertDocInRedis', 'InsertEmbeddingInRedis'] + + +class Document(typing.NamedTuple): + id: str + url: str + title: str + text: str + + +coders.registry.register_coder(Document, coders.RowCoder) + +"""This module implements IO classes to read write data on Redis. + + +Insert Doc in Redis: +----------------- +:class:`InsertDocInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') +class InsertDocInRedis(PTransform): + """InsertDocInRedis is a ``PTransform`` that writes a ``PCollection`` of + key, value tuple or 2-element array into a redis server. + """ + + def __init__(self, host=None, port=None, command=None, batch_size=100): + """ + + Args: + host (str, ValueProvider): The redis host + port (int, ValueProvider): The redis port + batch_size(int, ValueProvider): Number of key, values pairs to write at once + command : command to be executed with redis client + + Returns: + :class:`~apache_beam.transforms.ptransform.PTransform` + + """ + if not isinstance(host, (str, unicode, ValueProvider)): + raise TypeError( + '%s: host must be string, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(host))) + + if not isinstance(port, (int, ValueProvider)): + raise TypeError( + '%s: port must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(port))) + + if not isinstance(port, (int, ValueProvider)): + raise TypeError( + '%s: batch_size must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(batch_size))) + + if isinstance(host, (str, unicode)): + host = StaticValueProvider(str, host) + + if isinstance(port, int): + port = StaticValueProvider(int, port) + + if isinstance(command, int): + command = StaticValueProvider(str, command) + + if isinstance(batch_size, int): + batch_size = StaticValueProvider(int, batch_size) + + self._host = host + self._port = port + self._command = command + self._batch_size = batch_size + + def expand(self, pcoll): + return pcoll \ + | "Reshuffle for Redis Insert" >> Reshuffle() \ + | "Insert document into Redis" >> beam.ParDo(_InsertDocRedisFn(self._host, + self._port, + self._command, + self._batch_size) + # .with_output_types(Document) + ) + + +class _InsertDocRedisFn(DoFn): + """Abstract class that takes in redis + credentials to connect to redis DB + """ + + def __init__(self, host, port, command, batch_size): + self.host = host + self.port = port + self.command = command + self.batch_size = batch_size + + self.batch_counter = 0 + self.batch = list() + + self.text_col = None + + def finish_bundle(self): + self._flush() + + def process(self, element, *args, **kwargs): + # if type(element) is not dict: + # element = element._asdict() + self.batch.append(element) + self.batch_counter += 1 + if self.batch_counter == self.batch_size.get(): + self._flush() + # yield Document(**element) + yield element + + def _flush(self): + if self.batch_counter == 0: + return + + with _InsertDocRedisSink(self.host.get(), self.port.get()) as sink: + + if not self.command: + sink.write(self.batch) + + else: + sink.execute_command(self.command, self.batch) + + self.batch_counter = 0 + self.batch = list() + + +class _InsertDocRedisSink(object): + """Class where we create redis client + and write insertion logic in redis + """ + + def __init__(self, host, port): + self.host = host + self.port = port + self.client = None + + def _create_client(self): + if self.client is None: + self.client = redis.Redis(host=self.host, + port=self.port) + + def write(self, elements): + self._create_client() + with self.client.pipeline() as pipe: + # id = 1 + for element in elements: # ML Transform passes a dictionary list. TODO: add a transform instead to suit the Vector DB functionality. + doc_key = f"doc_{str(element['id'])}" + for k, v in element.items(): + print(f'Inserting doc_key={doc_key}, key={k}, value={v}') + pipe.hset(name=doc_key, key=k, value=v) + + pipe.execute() + + def execute_command(self, command, elements): + self._create_client() + with self.client.pipeline() as pipe: + for element in elements: + k, v = element + pipe.execute_command(command, k, v) + pipe.execute() + + def __enter__(self): + self._create_client() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.client is not None: + self.client.close() + + +"""This module implements IO classes to read write data on Redis. Review Comment: Module-level comments should be at the top of the file, class level comments should be under the class for pydoc purposes. ########## examples/notebooks/beam-ml/rag_usecase/redis_connector.py: ########## @@ -0,0 +1,406 @@ +# +# 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 absolute_import + +import logging +from past.builtins import unicode + +import apache_beam as beam +import numpy as np + +from apache_beam.transforms import DoFn +from apache_beam.transforms import PTransform +from apache_beam.transforms import Reshuffle +from apache_beam.utils.annotations import deprecated +from apache_beam.options.value_provider import ValueProvider +from apache_beam.options.value_provider import StaticValueProvider +from apache_beam import coders + +import typing + +# Set the logging level to reduce verbose information +import logging + +logging.root.setLevel(logging.INFO) +logger = logging.getLogger(__name__) + +import redis + +__all__ = ['InsertDocInRedis', 'InsertEmbeddingInRedis'] + + +class Document(typing.NamedTuple): + id: str + url: str + title: str + text: str + + +coders.registry.register_coder(Document, coders.RowCoder) + +"""This module implements IO classes to read write data on Redis. + + +Insert Doc in Redis: +----------------- +:class:`InsertDocInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') +class InsertDocInRedis(PTransform): + """InsertDocInRedis is a ``PTransform`` that writes a ``PCollection`` of + key, value tuple or 2-element array into a redis server. + """ + + def __init__(self, host=None, port=None, command=None, batch_size=100): + """ + + Args: + host (str, ValueProvider): The redis host + port (int, ValueProvider): The redis port + batch_size(int, ValueProvider): Number of key, values pairs to write at once + command : command to be executed with redis client + + Returns: + :class:`~apache_beam.transforms.ptransform.PTransform` + + """ + if not isinstance(host, (str, unicode, ValueProvider)): + raise TypeError( + '%s: host must be string, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(host))) + + if not isinstance(port, (int, ValueProvider)): + raise TypeError( + '%s: port must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(port))) + + if not isinstance(port, (int, ValueProvider)): + raise TypeError( + '%s: batch_size must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(batch_size))) + + if isinstance(host, (str, unicode)): + host = StaticValueProvider(str, host) + + if isinstance(port, int): + port = StaticValueProvider(int, port) + + if isinstance(command, int): + command = StaticValueProvider(str, command) + + if isinstance(batch_size, int): + batch_size = StaticValueProvider(int, batch_size) + + self._host = host + self._port = port + self._command = command + self._batch_size = batch_size + + def expand(self, pcoll): + return pcoll \ + | "Reshuffle for Redis Insert" >> Reshuffle() \ + | "Insert document into Redis" >> beam.ParDo(_InsertDocRedisFn(self._host, + self._port, + self._command, + self._batch_size) + # .with_output_types(Document) + ) + + +class _InsertDocRedisFn(DoFn): + """Abstract class that takes in redis + credentials to connect to redis DB + """ + + def __init__(self, host, port, command, batch_size): + self.host = host + self.port = port + self.command = command + self.batch_size = batch_size + + self.batch_counter = 0 + self.batch = list() + + self.text_col = None + + def finish_bundle(self): + self._flush() + + def process(self, element, *args, **kwargs): + # if type(element) is not dict: + # element = element._asdict() + self.batch.append(element) + self.batch_counter += 1 + if self.batch_counter == self.batch_size.get(): + self._flush() + # yield Document(**element) + yield element + + def _flush(self): + if self.batch_counter == 0: + return + + with _InsertDocRedisSink(self.host.get(), self.port.get()) as sink: + + if not self.command: + sink.write(self.batch) + + else: + sink.execute_command(self.command, self.batch) + + self.batch_counter = 0 + self.batch = list() + + +class _InsertDocRedisSink(object): + """Class where we create redis client + and write insertion logic in redis + """ + + def __init__(self, host, port): + self.host = host + self.port = port + self.client = None + + def _create_client(self): + if self.client is None: + self.client = redis.Redis(host=self.host, + port=self.port) + + def write(self, elements): + self._create_client() + with self.client.pipeline() as pipe: + # id = 1 + for element in elements: # ML Transform passes a dictionary list. TODO: add a transform instead to suit the Vector DB functionality. + doc_key = f"doc_{str(element['id'])}" + for k, v in element.items(): + print(f'Inserting doc_key={doc_key}, key={k}, value={v}') + pipe.hset(name=doc_key, key=k, value=v) + + pipe.execute() + + def execute_command(self, command, elements): + self._create_client() + with self.client.pipeline() as pipe: + for element in elements: + k, v = element + pipe.execute_command(command, k, v) + pipe.execute() + + def __enter__(self): + self._create_client() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.client is not None: + self.client.close() + + +"""This module implements IO classes to read write data on Redis. + + +Insert Embedding in Redis : +----------------- +:class:`InsertEmbeddingInRedis` is a ``PTransform`` that writes key and values to a +configured sink, and the write is conducted through a redis pipeline. + +The ptransform works by getting the first and second elements from the input, +this means that inputs like `[k,v]` or `(k,v)` are valid. + +Example usage:: + + pipeline | WriteToRedis(host='localhost', + port=6379, + batch_size=100) + + +No backward compatibility guarantees. Everything in this module is experimental. +""" + + +@deprecated(since='v.1') +class InsertEmbeddingInRedis(PTransform): + """WriteToRedis is a ``PTransform`` that writes a ``PCollection`` of + key, value tuple or 2-element array into a redis server. + """ + + def __init__(self, host=None, port=None, command=None, batch_size=100, embedded_columns=None): + """ + + Args: + host (str, ValueProvider): The redis host + port (int, ValueProvider): The redis port + command : command to be executed with redis client + batch_size(int, ValueProvider): Number of key, values pairs to write at once + embedded_columns (list, ValueProvider): list of column whose embedding needs to be generated + + Returns: + :class:`~apache_beam.transforms.ptransform.PTransform` + + """ + if not isinstance(host, (str, unicode, ValueProvider)): + raise TypeError( + '%s: host must be string, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(host))) + + if not isinstance(port, (int, ValueProvider)): + raise TypeError( + '%s: port must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(port))) + + if not isinstance(batch_size, (int, ValueProvider)): + raise TypeError( + '%s: batch_size must be int, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(batch_size))) + + if not isinstance(embedded_columns, (list, ValueProvider)): + raise TypeError( + '%s: embedded_columns must be list, or ValueProvider; got %r instead' + ) % (self.__class__.__name__, (type(embedded_columns))) + + if isinstance(host, (str, unicode)): + host = StaticValueProvider(str, host) + + if isinstance(port, int): + port = StaticValueProvider(int, port) + + if isinstance(command, int): + command = StaticValueProvider(str, command) + + if isinstance(batch_size, int): + batch_size = StaticValueProvider(int, batch_size) + + if isinstance(embedded_columns, int): + embedded_columns = StaticValueProvider(int, embedded_columns) Review Comment: Same thing here, use type hinting to do the input validation for you. -- 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]
