-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcosmosdbloader.py
More file actions
82 lines (57 loc) · 2.68 KB
/
Copy pathcosmosdbloader.py
File metadata and controls
82 lines (57 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from os import environ
from dotenv import load_dotenv
from pymongo import MongoClient, database
from jsondataloader import JSONDataLoader
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores.azure_cosmos_db import AzureCosmosDBVectorSearch, CosmosDBSimilarityType
load_dotenv(override=True)
class CosmosDBLoader():
def __init__(
self, DB_Name):
self.MONGO_CONNECTION_STRING = environ.get("MONGO_CONNECTION_STRING")
self.DB_NAME = DB_Name
def __collection_exists(self,db:database, collection_name:str)->bool:
collections = db.list_collection_names()
if collection_name in collections: return True
return False
def __drop_collection(self,db:database, collection_name:str):
if self.__collection_exists(db,collection_name):
db.drop_collection(collection_name)
def load_data(self,data:list,collection_name:str):
"""load documents into Cosmos DB Collection"""
print(f"--load {collection_name}--")
client = MongoClient(self.MONGO_CONNECTION_STRING)
db = client[self.DB_NAME]
self.__drop_collection(db,collection_name)
collection = db[collection_name]
collection.insert_many(data)
return collection
def load_vectors(self,data:list,collection_name:str):
"""load embeddings into Cosmos DB vector store"""
INDEX_NAME = "vectorSearchIndex"
print(f"--load vectors {collection_name}--")
client = MongoClient(self.MONGO_CONNECTION_STRING)
db = client[self.DB_NAME]
self.__drop_collection(db,collection_name)
collection = db[collection_name]
loader = JSONDataLoader( )
docs = None
if collection_name == 'ships':
docs = loader.load_ship(data)
else:
if collection_name == 'destinations':
docs = loader.load_destination(data)
if docs != None:
#load documents into Cosmos DB Vector Store
vector_store = AzureCosmosDBVectorSearch.from_documents(
docs,
OpenAIEmbeddings(disallowed_special=()),
collection=collection,
index_name=INDEX_NAME)
if vector_store.index_exists() == False:
#Create an index for vector search
num_lists = 1 #for a small demo, you can start with numLists set to 1 to perform a brute-force search across all vectors.
dimensions = 1536
similarity_algorithm = CosmosDBSimilarityType.COS
vector_store.create_index(num_lists, dimensions, similarity_algorithm)
return collection