Skip to content

Commit e8abef9

Browse files
committed
Merge branch 'main' of https://github.com/jcodella/azure-docs-pr into cosmos-nosql-vector-javascript-howto
2 parents 52ea474 + b9f6e91 commit e8abef9

File tree

2 files changed

+174
-6
lines changed

2 files changed

+174
-6
lines changed

articles/cosmos-db/.openpublishing.redirection.cosmos-db.json

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,6 @@
55
"redirect_url": "/azure/cosmos-db/container-copy",
66
"redirect_document_id": true
77
},
8-
{
9-
"source_path_from_root": "/articles/cosmos-db/nosql/how-to-javascript-vector-index-query.md",
10-
"redirect_url": "/azure/cosmos-db/nosql",
11-
"redirect_document_id": false
12-
},
138
{
149
"source_path_from_root": "/articles/cosmos-db/account-databases-containers-items.md",
1510
"redirect_url": "/azure/cosmos-db/resource-model",
@@ -5826,4 +5821,4 @@
58265821
"redirect_document_id": false
58275822
}
58285823
]
5829-
}
5824+
}
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
---
2+
title: Index and query vector data in JavaScript
3+
titleSuffix: Azure Cosmos DB for NoSQL
4+
description: Add vector data Azure Cosmos DB for NoSQL and then query the data efficiently in your JavaScript application.
5+
author: jcodella
6+
ms.author: jacodel
7+
ms.reviewer: sidandrews
8+
ms.service: azure-cosmos-db
9+
ms.subservice: nosql
10+
ms.topic: how-to
11+
ms.date: 08/01/2023
12+
ms.custom: query-reference, build-2024, devx-track-js
13+
---
14+
15+
# Index and query vectors in Azure Cosmos DB for NoSQL in JavaScript.
16+
17+
[!INCLUDE[NoSQL](../includes/appliesto-nosql.md)]
18+
Vector search in Azure Cosmos DB for NoSQL is currently a preview feature. You're required to register for the preview before use. This article covers the following steps:
19+
20+
1. Registering for the preview of Vector Search in Azure Cosmos DB for NoSQL
21+
2. Setting up the Azure Cosmos DB container for vector search
22+
3. Authoring vector embedding policy
23+
4. Adding vector indexes to the container indexing policy
24+
5. Creating a container with vector indexes and vector embedding policy
25+
6. Performing a vector search on the stored data.
26+
7. This guide walks through the process of creating vector data, indexing the data, and then querying the data in a container.
27+
28+
29+
## Prerequisites
30+
- An existing Azure Cosmos DB for NoSQL account.
31+
- If you don't have an Azure subscription, [Try Azure Cosmos DB for NoSQL free](https://cosmos.azure.com/try/).
32+
- If you have an existing Azure subscription, [create a new Azure Cosmos DB for NoSQL account](how-to-create-account.md).
33+
- Latest version of the Azure Cosmos DB [JavaScript](sdk-nodejs.md) SDK (Version 4.1.0 or later)
34+
35+
## Registering for the preview
36+
Vector search for Azure Cosmos DB for NoSQL requires preview feature registration. Follow the below steps to register:
37+
38+
1. Navigate to your Azure Cosmos DB for NoSQL resource page.
39+
40+
2. Select the "Features" pane under the "Settings" menu item.
41+
42+
3. Select for “Vector Search in Azure Cosmos DB for NoSQL”.
43+
44+
5. Read the description of the feature to confirm you want to enroll in the preview.
45+
46+
6. Select "Enable" to enroll in the preview.
47+
48+
> [!NOTE]
49+
> The registration request will be autoapproved, however it may take several minutes to take effect.
50+
51+
## Understanding the steps involved in vector search
52+
53+
The following steps assume that you know how to [setup a Cosmos DB NoSQL account and create a database](quickstart-portal.md). The vector search feature is currently only supported on new containers, not existing container. You need to create a new container and then specify the container-level vector embedding policy and the vector indexing policy at the time of creation.
54+
55+
Let’s take an example of creating a database for an internet-based bookstore and you're storing Title, Author, ISBN, and Description for each book. We also define two properties to contain vector embeddings. The first is the “contentVector” property, which contains [text embeddings](../../ai-services/openai/concepts/models.md#embeddings ) generated from the text content of the book (for example, concatenating the “title” “author” “isbn” and “description” properties before creating the embedding). The second is “coverImageVector”, which is generated from [images of the book’s cover](../../ai-services/computer-vision/concept-image-retrieval.md).
56+
57+
1. Create and store vector embeddings for the fields on which you want to perform vector search.
58+
2. Specify the vector embedding paths in the vector embedding policy.
59+
3. Include any desired vector indexes in the indexing policy for the container.
60+
61+
For subsequent sections of this article, we consider the below structure for the items stored in our container:
62+
63+
```json
64+
{
65+
"title": "book-title",
66+
"author": "book-author",
67+
"isbn": "book-isbn",
68+
"description": "book-description",
69+
"contentVector": [2, -1, 4, 3, 5, -2, 5, -7, 3, 1],
70+
"coverImageVector": [0.33, -0.52, 0.45, -0.67, 0.89, -0.34, 0.86, -0.78]
71+
}
72+
```
73+
74+
## Creating a vector embedding policy for your container.
75+
Next, you need to define a container vector policy. This policy provides information that is used to inform the Azure Cosmos DB query engine how to handle vector properties in the VectorDistance system functions. This also informs the vector indexing policy of necessary information, should you choose to specify one.
76+
The following information is included in the contained vector policy:
77+
78+
* “path”: The property path that contains vectors 
79+
* “datatype”: The type of the elements of the vector (default Float32) 
80+
* “dimensions”: The length of each vector in the path (default 1536) 
81+
* “distanceFunction”: The metric used to compute distance/similarity (default Cosine) 
82+
83+
For our example with book details, the vector policy can look like the example JSON:
84+
85+
```javascript
86+
const vectorEmbeddingPolicy: VectorEmbeddingPolicy = {
87+
vectorEmbeddings: [
88+
{
89+
path: "/coverImageVector",
90+
dataType: "float32",
91+
dimensions: 8,
92+
distanceFunction: "dotproduct",
93+
},
94+
{
95+
path: "contentVector",
96+
dataType: "float32",
97+
dimensions: 10,
98+
distanceFunction: "cosine",
99+
},
100+
],
101+
};
102+
```
103+
104+
## Creating a vector index in the indexing policy
105+
Once the vector embedding paths are decided, vector indexes need to be added to the indexing policy. Currently, the vector search feature for Azure Cosmos DB for NoSQL is supported only on new containers so you need to apply the vector policy during the time of container creation and it can’t be modified later. For this example, the indexing policy would look like this:
106+
107+
```javascript
108+
const indexingPolicy: IndexingPolicy = {
109+
vectorIndexes: [
110+
{ path: "/coverImageVector", type: "quantizedFlat" },
111+
{ path: "/contentVector", type: "diskANN" },
112+
],
113+
inlcludedPaths: [
114+
{
115+
path: "/*",
116+
},
117+
],
118+
excludedPaths: [
119+
{
120+
path: "/coverImageVector/*",
121+
},
122+
{
123+
path: "/contentVector/*",
124+
},
125+
]
126+
};
127+
```
128+
129+
Now create your container as usual.
130+
131+
```javascript
132+
const containerName = "vector embedding container";
133+
// create container
134+
const { resource: containerdef } = await database.containers.createIfNotExists({
135+
id: containerName,
136+
vectorEmbeddingPolicy: vectorEmbeddingPolicy,
137+
indexingPolicy: indexingPolicy,
138+
});
139+
```
140+
141+
142+
> [!IMPORTANT]
143+
> Currently vector search in Azure Cosmos DB for NoSQL is supported on new containers only. You need to set both the container vector policy and any vector indexing policy during the time of container creation as it can’t be modified later. Both policies will be modifiable in a future improvement to the preview feature.
144+
145+
## Running vector similarity search query
146+
147+
Once you create a container with the desired vector policy, and insert vector data into the container, you can conduct a vector search using the [Vector Distance](query/vectordistance.md) system function in a query. Suppose you want to search for books about food recipes by looking at the description, you first need to get the embeddings for your query text. In this case, you might want to generate embeddings for the query text – “food recipe”. Once you have the embedding for your search query, you can use it in the VectorDistance function in the vector search query and get all the items that are similar to your query as shown here:
148+
149+
```sql
150+
SELECT c.title, VectorDistance(c.contentVector, [1,2,3,4,5,6,7,8,9,10]) AS SimilarityScore  
151+
FROM c 
152+
ORDER BY VectorDistance(c.contentVector, [1,2,3,4,5,6,7,8,9,10])  
153+
```
154+
155+
This query retrieves the book titles along with similarity scores with respect to your query. Here is an example in JavaScript:
156+
157+
```javascript
158+
const { resources } = await container.items
159+
.query({
160+
query: "SELECT c.title, VectorDistance(c.contentVector, @embedding) AS SimilarityScore FROM c  ORDER BY VectorDistance(c.contentVector, @embedding)"
161+
parameters: [{ name: "@embedding", value: [1,2,3,4,5,6,7,8,9,10] }]
162+
})
163+
.fetchAll();
164+
for (const item of resources) {
165+
console.log(`${itme.title}, ${item.SimilarityScore} is a capitol `);
166+
}
167+
```
168+
169+
170+
## Next steps
171+
- [VectorDistance system function](query/vectordistance.md)
172+
- [Vector indexing](../index-policy.md)
173+
- [Setup Azure Cosmos DB for NoSQL for vector search](../vector-search.md).

0 commit comments

Comments
 (0)