Skip to content

Commit c8b17c1

Browse files
authored
DOCSP-51350: Vector search queries (#117)
* DOCSP-51350: Vector search queries * edit * NX feedback * edits * word
1 parent 6f62210 commit c8b17c1

File tree

2 files changed

+215
-1
lines changed

2 files changed

+215
-1
lines changed

source/atlas-vector-search.txt

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,134 @@
22

33
================================
44
Run an Atlas Vector Search Query
5-
================================
5+
================================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: full text, text analyzer, meta, pipeline, scoring, Lucene, AI, artificial intelligence, code example, semantic, nearest
13+
:description: Learn about how to use Atlas Vector Search in the {+driver-short+}.
14+
15+
.. contents:: On this page
16+
:local:
17+
:backlinks: none
18+
:depth: 2
19+
:class: singlecol
20+
21+
Overview
22+
--------
23+
24+
In this guide, you can learn how to use the {+driver-short+} to perform
25+
:atlas:`Atlas Vector Search </atlas-vector-search/vector-search-overview/>`
26+
queries. The ``Aggregates`` builders class provides the
27+
``vectorSearch()`` helper method, which you can use to
28+
create a :atlas:`$vectorSearch </atlas-vector-search/vector-search-stage/>`
29+
pipeline stage.
30+
31+
.. important:: Feature Compatibility
32+
33+
To learn which versions of MongoDB Atlas support this feature, see
34+
:atlas:`Limitations </atlas-vector-search/vector-search-stage/#limitations>`
35+
in the MongoDB Atlas documentation.
36+
37+
Perform a Vector Search
38+
-----------------------
39+
40+
Before you can perform Atlas Vector Search queries, you must create an Atlas Vector Search
41+
index on your collection. To learn how to programmatically create a
42+
vector search index, see the :ref:`kotlin-sync-search-avs-indexes` guide.
43+
44+
Then, you can run an Atlas Vector Search query by using the
45+
``vectorSearch()`` method in an aggregation pipeline. This
46+
method accepts the following parameters:
47+
48+
- ``path``: The field to search
49+
- ``queryVector``: The vector embedding that represents your search query
50+
- ``indexName``: The name of the Atlas Vector Search index to use
51+
- ``limit``: The maximum number of results to return
52+
- ``options``: *(Optional)* A set of options that you can use to configure the
53+
vector search query
54+
55+
Basic Vector Search Example
56+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
57+
58+
This example runs an Atlas Vector Search query that performs
59+
the following actions:
60+
61+
- Queries the ``plot_embedding`` vector field.
62+
- Limits the results to ``5`` documents.
63+
- Specifies an Approximate Nearest Neighbor (ANN) vector search that considers
64+
``150`` candidates. To learn more about ANN searches, see :atlas:`ANN Search </atlas-vector-search/vector-search-stage/#ann-search>`
65+
in the MongoDB Atlas documentation.
66+
67+
.. io-code-block::
68+
69+
.. input:: /includes/vector-search.kt
70+
:start-after: start-vs
71+
:end-before: end-vs
72+
:language: kotlin
73+
:dedent:
74+
75+
.. output::
76+
:visible: false
77+
78+
{"title": "Berserk: The Golden Age Arc I - The Egg of the King"}
79+
{"title": "Rollerball"}
80+
{"title": "After Life"}
81+
{"title": "What Women Want"}
82+
{"title": "Truth About Demons"}
83+
84+
.. tip:: Query Vector Type
85+
86+
The preceding example creates an instance of ``BinaryVector`` to
87+
serve as the query vector, but you can also create a ``List`` of
88+
``Double`` instances. However, we recommend that you use the
89+
``BinaryVector`` type to improve storage efficiency.
90+
91+
Vector Search Score Example
92+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
93+
94+
The following example shows how to run same vector search
95+
query as the preceding example and print the documents' vector search
96+
meta-score. This score represents the relevance of each
97+
document to the query vector:
98+
99+
.. io-code-block::
100+
101+
.. input:: /includes/vector-search.kt
102+
:start-after: start-vs-score
103+
:end-before: end-vs-score
104+
:language: kotlin
105+
:dedent:
106+
107+
.. output::
108+
:visible: false
109+
110+
Title: Berserk: The Golden Age Arc I - The Egg of the King, Score: 0.49899211525917053
111+
Title: Rollerball, Score: 0.4976102113723755
112+
Title: After Life, Score: 0.4965665936470032
113+
Title: What Women Want, Score: 0.49622756242752075
114+
Title: Truth About Demons, Score: 0.49614521861076355
115+
116+
.. tip:: Vector Search Tutorials
117+
118+
To view more tutorials that show how to run Atlas Vector Search queries,
119+
see the :atlas:`Atlas Vector Search Tutorials </atlas-vector-search/tutorials>`
120+
in the MongoDB Atlas documentation.
121+
122+
API Documentation
123+
-----------------
124+
125+
To learn more about the methods and types mentioned in this
126+
guide, see the following API documentation:
127+
128+
- `Aggregates.vectorSearch()
129+
<{+core-api+}/client/model/Aggregates.html#vectorSearch(com.mongodb.client.model.search.FieldSearchPath,java.lang.Iterable,java.lang.String,long,com.mongodb.client.model.search.VectorSearchOptions)>`__
130+
131+
- `VectorSearchOptions
132+
<{+core-api+}/client/model/search/VectorSearchOptions.html>`__
133+
134+
- `Projections.metaVectorSearchScore()
135+
<{+core-api+}/client/model/Projections.html#metaVectorSearchScore(java.lang.String)>`__

source/includes/vector-search.kt

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package org.example
2+
3+
import com.mongodb.ConnectionString
4+
import com.mongodb.kotlin.client.MongoClient
5+
import com.mongodb.MongoClientSettings
6+
import com.mongodb.client.model.Aggregates.project
7+
import com.mongodb.client.model.Aggregates.vectorSearch
8+
import com.mongodb.client.model.search.FieldSearchPath
9+
import com.mongodb.client.model.Projections
10+
import com.mongodb.client.model.search.SearchPath.fieldPath
11+
import org.bson.BinaryVector
12+
import org.bson.conversions.Bson
13+
import com.mongodb.client.model.search.VectorSearchOptions.approximateVectorSearchOptions
14+
import org.bson.Document
15+
16+
fun main() {
17+
val uri = "<connection string>"
18+
19+
val settings = MongoClientSettings.builder()
20+
.applyConnectionString(ConnectionString(uri))
21+
.retryWrites(true)
22+
.build()
23+
24+
val mongoClient = MongoClient.create(settings)
25+
val database = mongoClient.getDatabase("sample_mflix")
26+
val collection = database.getCollection<Document>("embedded_movies")
27+
28+
// start-vs
29+
val vectorValues = FloatArray(1536) { i -> (i % 10).toFloat() * 0.1f }
30+
val queryVector = BinaryVector.floatVector(vectorValues)
31+
val indexName = "<vector search index>"
32+
33+
// Specifies the path of the field to search
34+
val fieldSearchPath: FieldSearchPath = fieldPath("plot_embedding")
35+
36+
// Creates the vector search pipeline stage with a limit and numCandidates
37+
val pipeline: List<Bson> = listOf(
38+
vectorSearch(
39+
fieldSearchPath,
40+
queryVector,
41+
indexName,
42+
5L,
43+
approximateVectorSearchOptions(150)
44+
),
45+
project(
46+
Projections.fields(
47+
Projections.excludeId(),
48+
Projections.include("title")
49+
)
50+
)
51+
)
52+
53+
val results = collection.aggregate(pipeline)
54+
55+
results.forEach { doc ->
56+
println(doc.toJson())
57+
}
58+
// end-vs
59+
60+
// start-vs-score
61+
val pipeline: List<Bson> = listOf(
62+
vectorSearch(
63+
fieldSearchPath,
64+
queryVector,
65+
indexName,
66+
5L,
67+
approximateVectorSearchOptions(150)
68+
),
69+
project(
70+
Projections.fields(
71+
Projections.excludeId(),
72+
Projections.include("title"),
73+
Projections.metaVectorSearchScore("score")
74+
)
75+
)
76+
)
77+
78+
val results = collection.aggregate(pipeline)
79+
80+
results.forEach { doc ->
81+
println("Title: ${doc.getString("title")}, Score: ${doc.getDouble("score")}")
82+
}
83+
// end-vs-score
84+
}

0 commit comments

Comments
 (0)