jrmccluskey commented on code in PR #32018:
URL: https://github.com/apache/beam/pull/32018#discussion_r1698871123


##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()

Review Comment:
   You don't provide a .env file and I don't see any accesses of any 
environment variables in the file, should be removed



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()
+
+
+# Set the logging level to reduce verbose information
+import logging
+
+logging.root.setLevel(logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+__all__ = ['InsertDocInOpenSearch','InsertEmbeddingInOpenSearch']
+
+
+
+
+"""This module implements IO classes to read document in Opensearch.
+
+
+Insert Doc in OpenSearch:
+-----------------
+:class:`InsertDocInOpenSearch` is a ``PTransform`` that writes key and values 
to a
+configured sink, and the write is conducted through a Opensearch 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 | InsertDocInOpenSearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+class InsertDocInOpenSearch(PTransform):
+    """InsertDocInOpensearch is a ``PTransform`` that writes a ``PCollection`` 
of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int,
+                 username:str, 
+                 password:str, 
+                 batch_size:int=100
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        batch_size(int, ValueProvider): Number of key, values pairs to write 
at once

Review Comment:
   Arg types aren't `Union[typ, ValueProvider]`, also missing username and 
password args



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()
+
+
+# Set the logging level to reduce verbose information
+import logging
+
+logging.root.setLevel(logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+__all__ = ['InsertDocInOpenSearch','InsertEmbeddingInOpenSearch']
+
+
+
+
+"""This module implements IO classes to read document in Opensearch.
+
+
+Insert Doc in OpenSearch:
+-----------------
+:class:`InsertDocInOpenSearch` is a ``PTransform`` that writes key and values 
to a
+configured sink, and the write is conducted through a Opensearch 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 | InsertDocInOpenSearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+class InsertDocInOpenSearch(PTransform):
+    """InsertDocInOpensearch is a ``PTransform`` that writes a ``PCollection`` 
of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int,
+                 username:str, 
+                 password:str, 
+                 batch_size:int=100
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        batch_size(int, ValueProvider): Number of key, values pairs to write 
at once
+
+        Returns:
+        :class:`~apache_beam.transforms.ptransform.PTransform`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        self._batch_size = batch_size
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Opensearch Insert" >> Reshuffle() \
+               | "Insert document into Opensearch" >> 
beam.ParDo(_InsertDocOpenSearchFn(self.host,
+                                        self.port,
+                                        self.username,
+                                        self.password,
+                                        self._batch_size)
+               )
+
+
+class _InsertDocOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  
+    credentials to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100
+        ):
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        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):     
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush() 
+        yield element
+
+    def _flush(self):
+        if self.batch_counter == 0: 
+            return
+
+        with _InsertDocOpenSearchSink(self.host, self.port, 
self.username,self.password) as sink:
+
+            sink.write(self.batch)
+            self.batch_counter = 0
+            self.batch = list()
+
+
+
+class _InsertDocOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write insertion logic in Opensearch
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False)
+
+
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements: 
+            documents.extend([{
+                    "index": {
+                    "_index": "embeddings-index", 
+                    "_id" : str(element["id"]),
+                    }
+                }, {
+                    "url" : element["url"],
+                    "title" : element["title"],
+                    "text" : element["text"],
+                    "section_id" : element["section_id"]
+                }])
+        
+            print(f'Inside insert Doc in DB{element}')
+        self.client.bulk(body = documents, refresh = True)
+
+    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 text Embeddings in Opensearch.
+
+
+Insert Embedding in Opensearch :
+-----------------
+:class:`InsertEmbeddingInOpensearch` is a ``PTransform`` that writes key and 
values to a
+configured sink, and the write is conducted through a Opensearch 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 | WriteToOpensearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+
+class InsertEmbeddingInOpenSearch(PTransform):
+    """WriteToOpensearch is a ``PTransform`` that writes a ``PCollection`` of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str, 
+                 password:str,
+                 batch_size:int=100, 
+                 embedded_columns:list=[]
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        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`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Embedding in Opensearch Insert" >> Reshuffle() 
\
+               | "Write `Embeddings` to Opensearch" >> 
beam.ParDo(_WriteEmbeddingInOpenSearchFn(self.host,
+                                          self.port,
+                                          self.username,
+                                          self.password,
+                                          self.batch_size,
+                                          self.embedded_columns))
+
+
+class _WriteEmbeddingInOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  credentials 
+    to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100,
+                 embedded_columns:list=[]):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+        self.batch_counter = 0
+        self.batch = list()
+
+    def finish_bundle(self):
+        self._flush()
+
+    def process(self, element, *args, **kwargs):
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush()
+
+    def _flush(self):
+        if self.batch_counter == 0:
+            return
+
+        with _InsertEmbeddingInOpenSearchSink(self.host, self.port, 
self.username, self.password, self.embedded_columns) as sink:

Review Comment:
   Is there a reason you're instantiating a new instance of the internal class 
here every time? You wind up creating a new class + client every time 



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()
+
+
+# Set the logging level to reduce verbose information
+import logging
+
+logging.root.setLevel(logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+__all__ = ['InsertDocInOpenSearch','InsertEmbeddingInOpenSearch']
+
+
+
+
+"""This module implements IO classes to read document in Opensearch.
+
+
+Insert Doc in OpenSearch:
+-----------------
+:class:`InsertDocInOpenSearch` is a ``PTransform`` that writes key and values 
to a
+configured sink, and the write is conducted through a Opensearch 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 | InsertDocInOpenSearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+class InsertDocInOpenSearch(PTransform):
+    """InsertDocInOpensearch is a ``PTransform`` that writes a ``PCollection`` 
of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int,
+                 username:str, 
+                 password:str, 
+                 batch_size:int=100
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        batch_size(int, ValueProvider): Number of key, values pairs to write 
at once
+
+        Returns:
+        :class:`~apache_beam.transforms.ptransform.PTransform`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        self._batch_size = batch_size
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Opensearch Insert" >> Reshuffle() \
+               | "Insert document into Opensearch" >> 
beam.ParDo(_InsertDocOpenSearchFn(self.host,
+                                        self.port,
+                                        self.username,
+                                        self.password,
+                                        self._batch_size)
+               )
+
+
+class _InsertDocOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  
+    credentials to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100
+        ):
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        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):     
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush() 
+        yield element
+
+    def _flush(self):
+        if self.batch_counter == 0: 
+            return
+
+        with _InsertDocOpenSearchSink(self.host, self.port, 
self.username,self.password) as sink:
+
+            sink.write(self.batch)
+            self.batch_counter = 0
+            self.batch = list()
+
+
+
+class _InsertDocOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write insertion logic in Opensearch
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False)
+
+
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements: 
+            documents.extend([{
+                    "index": {
+                    "_index": "embeddings-index", 
+                    "_id" : str(element["id"]),
+                    }
+                }, {
+                    "url" : element["url"],
+                    "title" : element["title"],
+                    "text" : element["text"],
+                    "section_id" : element["section_id"]
+                }])
+        
+            print(f'Inside insert Doc in DB{element}')
+        self.client.bulk(body = documents, refresh = True)
+
+    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 text Embeddings in Opensearch.
+
+
+Insert Embedding in Opensearch :
+-----------------
+:class:`InsertEmbeddingInOpensearch` is a ``PTransform`` that writes key and 
values to a
+configured sink, and the write is conducted through a Opensearch 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 | WriteToOpensearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+
+class InsertEmbeddingInOpenSearch(PTransform):
+    """WriteToOpensearch is a ``PTransform`` that writes a ``PCollection`` of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str, 
+                 password:str,
+                 batch_size:int=100, 
+                 embedded_columns:list=[]
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        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`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Embedding in Opensearch Insert" >> Reshuffle() 
\
+               | "Write `Embeddings` to Opensearch" >> 
beam.ParDo(_WriteEmbeddingInOpenSearchFn(self.host,
+                                          self.port,
+                                          self.username,
+                                          self.password,
+                                          self.batch_size,
+                                          self.embedded_columns))
+
+
+class _WriteEmbeddingInOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  credentials 
+    to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100,
+                 embedded_columns:list=[]):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+        self.batch_counter = 0
+        self.batch = list()
+
+    def finish_bundle(self):
+        self._flush()
+
+    def process(self, element, *args, **kwargs):
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush()
+
+    def _flush(self):
+        if self.batch_counter == 0:
+            return
+
+        with _InsertEmbeddingInOpenSearchSink(self.host, self.port, 
self.username, self.password, self.embedded_columns) as sink:
+
+            sink.write(self.batch)
+
+            self.batch_counter = 0
+            self.batch = list()
+
+
+class _InsertEmbeddingInOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write text embedding  in Opensearch DB
+    """
+    
+    def __init__(self, host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 embedded_columns:list=[]):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.embedded_columns = embedded_columns
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False
+        )
+
+        
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements:
+            print(f'Insert Embeddings in opensearch DB {element}')
+            doc_update = {
+                "url" : element["url"],
+                "section_id" : element["section_id"]
+            }
+            
+            for k,v in element.items():
+                if k in self.embedded_columns:
+                    doc_update[f"{k}_vector"] = v
+                        
+            documents.extend([{
+                            "update": {
+                            "_index": "embeddings-index", 
+                            "_id" : str(element["id"]),
+                            }
+                        }, { 
+                            "doc": doc_update
+                        }])
+                    
+        
+        print(f'Inside insert Doc in DB{documents}')

Review Comment:
   is this a leftover debugging string?



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()
+
+
+# Set the logging level to reduce verbose information
+import logging
+
+logging.root.setLevel(logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+__all__ = ['InsertDocInOpenSearch','InsertEmbeddingInOpenSearch']
+
+
+
+
+"""This module implements IO classes to read document in Opensearch.
+
+
+Insert Doc in OpenSearch:
+-----------------
+:class:`InsertDocInOpenSearch` is a ``PTransform`` that writes key and values 
to a
+configured sink, and the write is conducted through a Opensearch 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 | InsertDocInOpenSearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+class InsertDocInOpenSearch(PTransform):
+    """InsertDocInOpensearch is a ``PTransform`` that writes a ``PCollection`` 
of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int,
+                 username:str, 
+                 password:str, 
+                 batch_size:int=100
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        batch_size(int, ValueProvider): Number of key, values pairs to write 
at once
+
+        Returns:
+        :class:`~apache_beam.transforms.ptransform.PTransform`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        self._batch_size = batch_size
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Opensearch Insert" >> Reshuffle() \
+               | "Insert document into Opensearch" >> 
beam.ParDo(_InsertDocOpenSearchFn(self.host,
+                                        self.port,
+                                        self.username,
+                                        self.password,
+                                        self._batch_size)
+               )
+
+
+class _InsertDocOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  
+    credentials to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100
+        ):
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        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):     
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush() 
+        yield element
+
+    def _flush(self):
+        if self.batch_counter == 0: 
+            return
+
+        with _InsertDocOpenSearchSink(self.host, self.port, 
self.username,self.password) as sink:
+
+            sink.write(self.batch)
+            self.batch_counter = 0
+            self.batch = list()
+
+
+
+class _InsertDocOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write insertion logic in Opensearch
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False)
+
+
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements: 
+            documents.extend([{
+                    "index": {
+                    "_index": "embeddings-index", 
+                    "_id" : str(element["id"]),
+                    }
+                }, {
+                    "url" : element["url"],
+                    "title" : element["title"],
+                    "text" : element["text"],
+                    "section_id" : element["section_id"]
+                }])
+        
+            print(f'Inside insert Doc in DB{element}')
+        self.client.bulk(body = documents, refresh = True)
+
+    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 text Embeddings in Opensearch.
+
+
+Insert Embedding in Opensearch :
+-----------------
+:class:`InsertEmbeddingInOpensearch` is a ``PTransform`` that writes key and 
values to a
+configured sink, and the write is conducted through a Opensearch 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 | WriteToOpensearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+
+class InsertEmbeddingInOpenSearch(PTransform):
+    """WriteToOpensearch is a ``PTransform`` that writes a ``PCollection`` of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str, 
+                 password:str,
+                 batch_size:int=100, 
+                 embedded_columns:list=[]
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        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`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Embedding in Opensearch Insert" >> Reshuffle() 
\
+               | "Write `Embeddings` to Opensearch" >> 
beam.ParDo(_WriteEmbeddingInOpenSearchFn(self.host,
+                                          self.port,
+                                          self.username,
+                                          self.password,
+                                          self.batch_size,
+                                          self.embedded_columns))
+
+
+class _WriteEmbeddingInOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  credentials 
+    to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100,
+                 embedded_columns:list=[]):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.batch_size = batch_size
+        self.embedded_columns = embedded_columns
+
+        self.batch_counter = 0
+        self.batch = list()
+
+    def finish_bundle(self):
+        self._flush()
+
+    def process(self, element, *args, **kwargs):
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush()
+
+    def _flush(self):
+        if self.batch_counter == 0:
+            return
+
+        with _InsertEmbeddingInOpenSearchSink(self.host, self.port, 
self.username, self.password, self.embedded_columns) as sink:
+
+            sink.write(self.batch)
+
+            self.batch_counter = 0
+            self.batch = list()
+
+
+class _InsertEmbeddingInOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write text embedding  in Opensearch DB
+    """
+    
+    def __init__(self, host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 embedded_columns:list=[]):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.embedded_columns = embedded_columns
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False
+        )
+
+        
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements:
+            print(f'Insert Embeddings in opensearch DB {element}')
+            doc_update = {
+                "url" : element["url"],
+                "section_id" : element["section_id"]
+            }
+            
+            for k,v in element.items():
+                if k in self.embedded_columns:
+                    doc_update[f"{k}_vector"] = v
+                        
+            documents.extend([{
+                            "update": {
+                            "_index": "embeddings-index", 
+                            "_id" : str(element["id"]),
+                            }
+                        }, { 
+                            "doc": doc_update
+                        }])
+                    
+        
+        print(f'Inside insert Doc in DB{documents}')
+        self.client.bulk(documents)

Review Comment:
   Does this call need any sort of error checking/handling?



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_connector.py:
##########
@@ -0,0 +1,383 @@
+#
+# 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
+
+import apache_beam as beam
+
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+from apache_beam import coders
+
+
+import typing
+from opensearchpy import OpenSearch
+
+import os 
+from dotenv import load_dotenv
+
+
+load_dotenv()
+
+
+# Set the logging level to reduce verbose information
+import logging
+
+logging.root.setLevel(logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+__all__ = ['InsertDocInOpenSearch','InsertEmbeddingInOpenSearch']
+
+
+
+
+"""This module implements IO classes to read document in Opensearch.
+
+
+Insert Doc in OpenSearch:
+-----------------
+:class:`InsertDocInOpenSearch` is a ``PTransform`` that writes key and values 
to a
+configured sink, and the write is conducted through a Opensearch 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 | InsertDocInOpenSearch(host='localhost',
+                          port=6379,
+                          batch_size=100)
+
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+class InsertDocInOpenSearch(PTransform):
+    """InsertDocInOpensearch is a ``PTransform`` that writes a ``PCollection`` 
of
+    key, value tuple or 2-element array into a Opensearch server.
+    """
+
+    def __init__(self, 
+                 host:str, 
+                 port:int,
+                 username:str, 
+                 password:str, 
+                 batch_size:int=100
+        ):
+        """
+
+        Args:
+        host (str, ValueProvider): The Opensearch host
+        port (int, ValueProvider): The Opensearch port
+        batch_size(int, ValueProvider): Number of key, values pairs to write 
at once
+
+        Returns:
+        :class:`~apache_beam.transforms.ptransform.PTransform`
+
+        """
+
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        self._batch_size = batch_size
+
+    def expand(self, pcoll):
+        return pcoll \
+               | "Reshuffle for Opensearch Insert" >> Reshuffle() \
+               | "Insert document into Opensearch" >> 
beam.ParDo(_InsertDocOpenSearchFn(self.host,
+                                        self.port,
+                                        self.username,
+                                        self.password,
+                                        self._batch_size)
+               )
+
+
+class _InsertDocOpenSearchFn(DoFn):
+    """Abstract class that takes in Opensearch  
+    credentials to connect to Opensearch DB
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str,
+                 batch_size:int=100
+        ):
+        self.host = host
+        self.port = port
+        self.username= username
+        self.password = password
+        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):     
+        self.batch.append(element)
+        self.batch_counter += 1
+        if self.batch_counter >= self.batch_size:
+            self._flush() 
+        yield element
+
+    def _flush(self):
+        if self.batch_counter == 0: 
+            return
+
+        with _InsertDocOpenSearchSink(self.host, self.port, 
self.username,self.password) as sink:
+
+            sink.write(self.batch)
+            self.batch_counter = 0
+            self.batch = list()
+
+
+
+class _InsertDocOpenSearchSink(object):
+    """Class where we create Opensearch client 
+    and write insertion logic in Opensearch
+    """
+    
+    def __init__(self, 
+                 host:str, 
+                 port:int, 
+                 username:str,
+                 password:str):
+        self.host = host
+        self.port = port
+        self.username = username
+        self.password = password
+        self.client = None
+
+    def _create_client(self):
+        if self.client is None:
+            http_auth = [self.username, self.password]
+            self.client = OpenSearch(hosts = [f'{self.host}:{self.port}'],
+                                    http_auth = http_auth,
+                                    verify_certs = False)
+
+
+    def write(self, elements):
+        self._create_client()
+        documents = []
+        for element in elements: 
+            documents.extend([{
+                    "index": {
+                    "_index": "embeddings-index", 
+                    "_id" : str(element["id"]),
+                    }
+                }, {
+                    "url" : element["url"],
+                    "title" : element["title"],
+                    "text" : element["text"],
+                    "section_id" : element["section_id"]
+                }])
+        
+            print(f'Inside insert Doc in DB{element}')
+        self.client.bulk(body = documents, refresh = True)
+
+    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()
+
+
+
+

Review Comment:
   Run `yapf` manually to clean up the whitespace (see 
https://cwiki.apache.org/confluence/display/BEAM/Python+Tips#PythonTips-Runningyapfformattermanually)



##########
examples/notebooks/beam-ml/rag_usecase/opensearch_enrichment.py:
##########
@@ -0,0 +1,138 @@
+#
+# 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 
opensearch Vector DB.
+
+
+opensearch :Enrichment Handler
+-----------------
+:class:`opensearchEnrichmentHandler` is a ``EnrichmentSourceHandler`` that 
performs enrichment/search
+by fetching the similar text to the user query/prompt from the knowledge base 
(opensearch vector DB) and returns
+the similar text along with its embeddings as Beam.Row Object. 
+
+Example usage::
+  opensearch_handler = 
opensearchEnrichmentHandler(opensearch_host='127.0.0.1', opensearch_port=6379)
+  
+  pipeline | Enrichment(opensearch_handler)
+
+No backward compatibility guarantees. Everything in this module is 
experimental.
+"""
+
+
+import logging
+
+
+import numpy as np
+from opensearchpy import OpenSearch
+
+
+import apache_beam as beam
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+from apache_beam.transforms.enrichment_handlers.utils import ExceptionLevel
+
+__all__ = [
+    'OpenSearchEnrichmentHandler',
+]
+
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class OpenSearchEnrichmentHandler(EnrichmentSourceHandler[beam.Row, beam.Row]):
+  """A handler for :class:`apache_beam.transforms.enrichment.Enrichment`
+  transform to interact with opensearch vector DB.
+
+  Args:
+    opensearch_host (str): opensearch Host to connect to opensearch DB
+    opensearch_port (int): opensearch Port to connect to opensearch DB
+    index_name (str): Index Name created for searching in opensearch 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 opensearch
+  """

Review Comment:
   These should be documented as args to `__init__` not the class declaration



-- 
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: github-unsubscr...@beam.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to