|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# The OpenSearch Contributors require contributions made to |
| 3 | +# this file be licensed under the Apache-2.0 license or a |
| 4 | +# compatible open source license. |
| 5 | +# Any modifications Copyright OpenSearch Contributors. See |
| 6 | +# GitHub history for details. |
| 7 | + |
| 8 | + |
| 9 | +# Licensed to Elasticsearch B.V. under one or more contributor |
| 10 | +# license agreements. See the NOTICE file distributed with |
| 11 | +# this work for additional information regarding copyright |
| 12 | +# ownership. Elasticsearch B.V. licenses this file to you under |
| 13 | +# the Apache License, Version 2.0 (the "License"); you may |
| 14 | +# not use this file except in compliance with the License. |
| 15 | +# You may obtain a copy of the License at |
| 16 | +# |
| 17 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 18 | +# |
| 19 | +# Unless required by applicable law or agreed to in writing, |
| 20 | +# software distributed under the License is distributed on an |
| 21 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 22 | +# KIND, either express or implied. See the License for the |
| 23 | +# specific language governing permissions and limitations |
| 24 | +# under the License. |
| 25 | + |
| 26 | +from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth, exceptions as opensearch_exceptions |
| 27 | +import boto3 |
| 28 | +from urllib.parse import urlparse |
| 29 | +from opensearchpy import helpers as opensearch_helpers |
| 30 | + |
| 31 | +class OpenSearchConnector: |
| 32 | + def __init__(self, config): |
| 33 | + self.config = config |
| 34 | + self.opensearch_client = None |
| 35 | + self.aws_region = config.get('region') |
| 36 | + self.index_name = config.get('index_name') |
| 37 | + self.is_serverless = config.get('is_serverless', 'False') == 'True' |
| 38 | + self.opensearch_endpoint = config.get('opensearch_endpoint') |
| 39 | + self.opensearch_username = config.get('opensearch_username') |
| 40 | + self.opensearch_password = config.get('opensearch_password') |
| 41 | + |
| 42 | + def initialize_opensearch_client(self): |
| 43 | + if not self.opensearch_endpoint: |
| 44 | + print("OpenSearch endpoint not set. Please run setup first.") |
| 45 | + return False |
| 46 | + |
| 47 | + parsed_url = urlparse(self.opensearch_endpoint) |
| 48 | + host = parsed_url.hostname |
| 49 | + port = parsed_url.port or 443 |
| 50 | + |
| 51 | + if self.is_serverless: |
| 52 | + credentials = boto3.Session().get_credentials() |
| 53 | + auth = AWSV4SignerAuth(credentials, self.aws_region, 'aoss') |
| 54 | + else: |
| 55 | + if not self.opensearch_username or not self.opensearch_password: |
| 56 | + print("OpenSearch username or password not set. Please run setup first.") |
| 57 | + return False |
| 58 | + auth = (self.opensearch_username, self.opensearch_password) |
| 59 | + |
| 60 | + try: |
| 61 | + self.opensearch_client = OpenSearch( |
| 62 | + hosts=[{'host': host, 'port': port}], |
| 63 | + http_auth=auth, |
| 64 | + use_ssl=True, |
| 65 | + verify_certs=True, |
| 66 | + connection_class=RequestsHttpConnection, |
| 67 | + pool_maxsize=20 |
| 68 | + ) |
| 69 | + print(f"Initialized OpenSearch client with host: {host} and port: {port}") |
| 70 | + return True |
| 71 | + except Exception as ex: |
| 72 | + print(f"Error initializing OpenSearch client: {ex}") |
| 73 | + return False |
| 74 | + |
| 75 | + def create_index(self, embedding_dimension, space_type): |
| 76 | + index_body = { |
| 77 | + "mappings": { |
| 78 | + "properties": { |
| 79 | + "nominee_text": {"type": "text"}, |
| 80 | + "nominee_vector": { |
| 81 | + "type": "knn_vector", |
| 82 | + "dimension": embedding_dimension, |
| 83 | + "method": { |
| 84 | + "name": "hnsw", |
| 85 | + "space_type": space_type, |
| 86 | + "engine": "nmslib", |
| 87 | + "parameters": {"ef_construction": 512, "m": 16}, |
| 88 | + }, |
| 89 | + }, |
| 90 | + } |
| 91 | + }, |
| 92 | + "settings": { |
| 93 | + "index": { |
| 94 | + "number_of_shards": 2, |
| 95 | + "knn.algo_param": {"ef_search": 512}, |
| 96 | + "knn": True, |
| 97 | + } |
| 98 | + }, |
| 99 | + } |
| 100 | + try: |
| 101 | + self.opensearch_client.indices.create(index=self.index_name, body=index_body) |
| 102 | + print(f"KNN index '{self.index_name}' created successfully with dimension {embedding_dimension} and space type {space_type}.") |
| 103 | + except opensearch_exceptions.RequestError as e: |
| 104 | + if 'resource_already_exists_exception' in str(e).lower(): |
| 105 | + print(f"Index '{self.index_name}' already exists.") |
| 106 | + else: |
| 107 | + print(f"Error creating index '{self.index_name}': {e}") |
| 108 | + |
| 109 | + def verify_and_create_index(self, embedding_dimension, space_type): |
| 110 | + try: |
| 111 | + index_exists = self.opensearch_client.indices.exists(index=self.index_name) |
| 112 | + if index_exists: |
| 113 | + print(f"KNN index '{self.index_name}' already exists.") |
| 114 | + else: |
| 115 | + self.create_index(embedding_dimension, space_type) |
| 116 | + return True |
| 117 | + except Exception as ex: |
| 118 | + print(f"Error verifying or creating index: {ex}") |
| 119 | + return False |
| 120 | + |
| 121 | + def bulk_index(self, actions): |
| 122 | + try: |
| 123 | + success_count, error_info = opensearch_helpers.bulk(self.opensearch_client, actions) |
| 124 | + error_count = len(error_info) |
| 125 | + print(f"Indexed {success_count} documents successfully. Failed to index {error_count} documents.") |
| 126 | + return success_count, error_count |
| 127 | + except Exception as e: |
| 128 | + print(f"Error during bulk indexing: {e}") |
| 129 | + return 0, len(actions) |
| 130 | + |
| 131 | + def search(self, vector, k=5): |
| 132 | + try: |
| 133 | + response = self.opensearch_client.search( |
| 134 | + index=self.index_name, |
| 135 | + body={ |
| 136 | + "size": k, |
| 137 | + "_source": ["nominee_text"], |
| 138 | + "query": { |
| 139 | + "knn": { |
| 140 | + "nominee_vector": { |
| 141 | + "vector": vector, |
| 142 | + "k": k |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + ) |
| 148 | + return response['hits']['hits'] |
| 149 | + except Exception as e: |
| 150 | + print(f"Error during search: {e}") |
| 151 | + return [] |
0 commit comments