Skip to content

Commit 600acec

Browse files
committed
DOCSP-51350: Vector search queries
1 parent 7c94562 commit 600acec

File tree

2 files changed

+209
-1
lines changed

2 files changed

+209
-1
lines changed

source/atlas-vector-search.txt

Lines changed: 124 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,127 @@
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+
the ``vectorSearch()`` helper method that 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 about 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+
Vector Search Example
56+
~~~~~~~~~~~~~~~~~~~~~
57+
58+
The following example performs an Atlas Vector Search query on the ``plot_embedding``
59+
vector field and prints the ``title`` value of the first five results:
60+
61+
.. io-code-block::
62+
63+
.. input:: /includes/vector-search.kt
64+
:start-after: start-vs
65+
:end-before: end-vs
66+
:language: kotlin
67+
:dedent:
68+
69+
.. output::
70+
:visible: false
71+
72+
{"title": "Berserk: The Golden Age Arc I - The Egg of the King"}
73+
{"title": "Rollerball"}
74+
{"title": "After Life"}
75+
{"title": "What Women Want"}
76+
{"title": "Truth About Demons"}
77+
78+
.. tip:: Query Vector Type
79+
80+
The preceding example creates an instance of ``BinaryVector`` to
81+
serve as the query vector, but you can also create a ``List`` of
82+
``Double`` instances. However, we recommend that you use the
83+
``BinaryVector`` type to improve storage efficiency.
84+
85+
The following example shows how to run the aggregation and print
86+
the vector search meta-score from the result of the preceding
87+
aggregation pipeline:
88+
89+
.. io-code-block::
90+
91+
.. input:: /includes/vector-search.kt
92+
:start-after: start-vs-score
93+
:end-before: end-vs-score
94+
:language: kotlin
95+
:dedent:
96+
97+
.. output::
98+
:visible: false
99+
100+
Title: Berserk: The Golden Age Arc I - The Egg of the King, Score: 0.49899211525917053
101+
Title: Rollerball, Score: 0.4976102113723755
102+
Title: After Life, Score: 0.4965665936470032
103+
Title: What Women Want, Score: 0.49622756242752075
104+
Title: Truth About Demons, Score: 0.49614521861076355
105+
106+
.. tip:: Vector Search Tutorials
107+
108+
To view more tutorials that show how to run Atlas Vector Search queries,
109+
see the :atlas:`Atlas Vector Search Tutorials </atlas-vector-search/tutorials>`
110+
in the MongoDB Atlas documentation.
111+
112+
API Documentation
113+
-----------------
114+
115+
To learn more about the methods and types mentioned in this
116+
guide, see the following API documentation:
117+
118+
- `Aggregates.vectorSearch()
119+
<{+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)>`__
120+
121+
- `FieldSearchPath
122+
<{+core-api+}/client/model/search/FieldSearchPath.html>`__
123+
124+
- `VectorSearchOptions
125+
<{+core-api+}/client/model/search/VectorSearchOptions.html>`__
126+
127+
- `Projections.metaVectorSearchScore()
128+
<{+core-api+}/client/model/Projections.html#metaVectorSearchScore(java.lang.String)>`__

source/includes/vector-search.kt

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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 numCandidates and limit
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, // limit parameter
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+
val score = doc.getDouble("vectorSearchScore")
82+
println("Title: ${doc.getString("title")}, Score: ${doc.getDouble("score")}")
83+
}
84+
// end-vs-score
85+
}

0 commit comments

Comments
 (0)