Skip to content

Commit da7e043

Browse files
committed
Added HNSW example in cosmos db for mongodb vcore example
1 parent 07b39f2 commit da7e043

File tree

1 file changed

+78
-26
lines changed

1 file changed

+78
-26
lines changed

Python/CosmosDB-MongoDB-vCore/CosmosDB-MongoDB-vCore_AzureOpenAI_Tutorial.ipynb

Lines changed: 78 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
"COSMOS_MONGO_USER = config['cosmos_db_mongo_user']\n",
8181
"COSMOS_MONGO_PWD = config['cosmos_db_mongo_pwd']\n",
8282
"COSMOS_MONGO_SERVER = config['cosmos_db_mongo_server']\n",
83+
"\n",
8384
"openai.api_type = config['openai_api_type']\n",
8485
"openai.api_key = config['openai_api_key']\n",
8586
"openai.api_base = config['openai_api_endpoint']\n",
@@ -118,7 +119,7 @@
118119
"metadata": {},
119120
"source": [
120121
"# Load data and create embeddings <a class=\"anchor\" id=\"loaddata\"></a>\n",
121-
"Here we'll load a sample dataset containing descriptions of Azure services. Then we'll user Azure OpenAI to create vector embeddings from this data."
122+
"Here we load a sample dataset containing descriptions of Azure services, then we use Azure OpenAI to create vector embeddings from this data."
122123
]
123124
},
124125
{
@@ -127,10 +128,10 @@
127128
"metadata": {},
128129
"outputs": [],
129130
"source": [
130-
"# Load text-sample.json data file\n",
131+
"# Load text-sample.json data file. Embeddings will need to be generated using the function below.\n",
131132
"#data_file = open(file=\"../../DataSet/AzureServices/text-sample.json\", mode=\"r\")\n",
132133
"\n",
133-
"# Load this file instead if embeddings were previously created and saved.\n",
134+
"# OR Load text-sample_w_embeddings.json which has embeddings pre-computed\n",
134135
"data_file = open(file=\"../../DataSet/AzureServices/text-sample_w_embeddings.json\", mode=\"r\") \n",
135136
"data = json.load(data_file)\n",
136137
"data_file.close()"
@@ -185,7 +186,6 @@
185186
" item['contentVector'] = content_embeddings\n",
186187
" item['@search.action'] = 'upload'\n",
187188
" print(\"Creating embeddings for item:\", n, \"/\" ,len(data), end='\\r')\n",
188-
"\n",
189189
"# Save embeddings to sample_text_w_embeddings.json file\n",
190190
"with open(\"../../DataSet/AzureServices/text-sample_w_embeddings.json\", \"w\") as f:\n",
191191
" json.dump(data, f)"
@@ -215,17 +215,6 @@
215215
"mongo_client = pymongo.MongoClient(mongo_conn)"
216216
]
217217
},
218-
{
219-
"cell_type": "code",
220-
"execution_count": null,
221-
"metadata": {},
222-
"outputs": [],
223-
"source": [
224-
"## Use only if re-reunning code and want to reset db and collection\n",
225-
"collection.drop_index(\"vectorSearchIndex\")\n",
226-
"mongo_client.drop_database(\"TutorialDB\")"
227-
]
228-
},
229218
{
230219
"cell_type": "markdown",
231220
"metadata": {},
@@ -240,10 +229,10 @@
240229
"outputs": [],
241230
"source": [
242231
"# create a database called TutorialDB\n",
243-
"db = mongo_client['TutorialDB']\n",
232+
"db = mongo_client['ExampleDB']\n",
244233
"\n",
245234
"# Create collection if it doesn't exist\n",
246-
"COLLECTION_NAME = \"TutorialCol\"\n",
235+
"COLLECTION_NAME = \"ExampleCollection\"\n",
247236
"\n",
248237
"collection = db[COLLECTION_NAME]\n",
249238
"\n",
@@ -255,11 +244,32 @@
255244
" print(\"Using collection: '{}'.\\n\".format(COLLECTION_NAME))"
256245
]
257246
},
247+
{
248+
"cell_type": "code",
249+
"execution_count": null,
250+
"metadata": {},
251+
"outputs": [],
252+
"source": [
253+
"## Use only if re-reunning code and want to reset db and collection\n",
254+
"collection.drop_index(\"VectorSearchIndex\")\n",
255+
"mongo_client.drop_database(\"ExampleDB\")"
256+
]
257+
},
258+
{
259+
"cell_type": "markdown",
260+
"metadata": {},
261+
"source": [
262+
"## Create the vector index\n",
263+
"\n",
264+
"**IMPORTANT: You can only create one index per vector property.** That is, you cannot create more than one index that points to the same vector property. If you want to change the index type (e.g., from IVF to HNSW) you must drop the index first before creating a new index."
265+
]
266+
},
258267
{
259268
"cell_type": "markdown",
260269
"metadata": {},
261270
"source": [
262-
"## Create the vector index"
271+
"### IVF\n",
272+
"IVF is the default vector indexing algorithm, which works on all cluster tiers. It's an approximate nerarest neighbors (ANN) approach that uses clustering to speeding up the search for similar vectors in a dataset. "
263273
]
264274
},
265275
{
@@ -269,10 +279,10 @@
269279
"outputs": [],
270280
"source": [
271281
"db.command({\n",
272-
" 'createIndexes': 'TutorialCol',\n",
282+
" 'createIndexes': 'ExampleCollection',\n",
273283
" 'indexes': [\n",
274284
" {\n",
275-
" 'name': 'vectorSearchIndex',\n",
285+
" 'name': 'VectorSearchIndex',\n",
276286
" 'key': {\n",
277287
" \"contentVector\": \"cosmosSearch\"\n",
278288
" },\n",
@@ -284,7 +294,46 @@
284294
" }\n",
285295
" }\n",
286296
" ]\n",
287-
"});"
297+
"})"
298+
]
299+
},
300+
{
301+
"cell_type": "markdown",
302+
"metadata": {},
303+
"source": [
304+
"### HNSW (preview)\n",
305+
"\n",
306+
"HNSW stands for Hierarchical Navigable Small World, a graph-based data structure that partitions vectors into clusters and subclusters. With HNSW, you can perform fast approximate nearest neighbor search at higher speeds with greater accuracy. HNSW is an approximate (ANN) method. As a preview feature, this must be enabled using Azure Feature Enablement Control (AFEC) by selecting the \"mongoHnswIndex\" feature. For more information, see [enable preview features](https://learn.microsoft.com/azure/azure-resource-manager/management/preview-features).\n",
307+
"\n",
308+
"HNSW works on M50 cluster tiers and higher while in preview."
309+
]
310+
},
311+
{
312+
"cell_type": "code",
313+
"execution_count": null,
314+
"metadata": {},
315+
"outputs": [],
316+
"source": [
317+
"db.command(\n",
318+
"{ \n",
319+
" \"createIndexes\": \"ExampleCollection\",\n",
320+
" \"indexes\": [\n",
321+
" {\n",
322+
" \"name\": \"VectorSearchIndex\",\n",
323+
" \"key\": {\n",
324+
" \"contentVector\": \"cosmosSearch\"\n",
325+
" },\n",
326+
" \"cosmosSearchOptions\": { \n",
327+
" \"kind\": \"vector-hnsw\", \n",
328+
" \"m\": 16, # default value \n",
329+
" \"efConstruction\": 64, # default value \n",
330+
" \"similarity\": \"COS\", \n",
331+
" \"dimensions\": 1536\n",
332+
" } \n",
333+
" } \n",
334+
" ] \n",
335+
"}\n",
336+
")"
288337
]
289338
},
290339
{
@@ -327,7 +376,7 @@
327376
" \"cosmosSearch\": {\n",
328377
" \"vector\": query_embedding,\n",
329378
" \"path\": \"contentVector\",\n",
330-
" \"k\": num_results\n",
379+
" \"k\": num_results #, \"efsearch\": 40 # optional for HNSW only \n",
331380
" },\n",
332381
" \"returnStoredSource\": True }},\n",
333382
" {'$project': { 'similarityScore': { '$meta': 'searchScore' }, 'document' : '$$ROOT' } }\n",
@@ -346,12 +395,15 @@
346395
{
347396
"cell_type": "code",
348397
"execution_count": null,
349-
"metadata": {},
398+
"metadata": {
399+
"scrolled": true
400+
},
350401
"outputs": [],
351402
"source": [
352-
"query = \"What services do you have?\"\n",
403+
"query = \"What are the services for running ML models?\"\n",
353404
"results = vector_search(query)\n",
354405
"for result in results: \n",
406+
"# print(result)\n",
355407
" print(f\"Similarity Score: {result['similarityScore']}\") \n",
356408
" print(f\"Title: {result['document']['title']}\") \n",
357409
" print(f\"Content: {result['document']['content']}\") \n",
@@ -411,11 +463,11 @@
411463
"user_input = input(\"Prompt: \")\n",
412464
"while user_input.lower() != \"end\":\n",
413465
" results_for_prompt = vector_search(user_input)\n",
414-
" print(f\"User Prompt: {user_input}\")\n",
466+
" # print(f\"User Prompt: {user_input}\")\n",
415467
" completions_results = generate_completion(results_for_prompt)\n",
416468
" print(\"\\n\")\n",
417469
" print(completions_results['choices'][0]['message']['content'])\n",
418-
" user_input = input(\"Prompt: \")"
470+
" user_input = input(\"Prompt: \")\n"
419471
]
420472
}
421473
],

0 commit comments

Comments
 (0)