Skip to content

Commit 1592226

Browse files
authored
DOCSP-26444: use struct in text search pg (#215)
* DOCSP-26444: use struct in text search pg * MW PR fixes 1
1 parent e0207c4 commit 1592226

File tree

2 files changed

+126
-105
lines changed

2 files changed

+126
-105
lines changed

source/fundamentals/crud/read-operations/text.txt

Lines changed: 73 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,17 @@ In this guide, you can learn how to run a :ref:`text search
2626
Sample Data
2727
~~~~~~~~~~~
2828

29+
The examples in this guide use the following ``Dish`` struct as a model for documents
30+
in the ``menu`` collection:
31+
32+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
33+
:start-after: start-dish-struct
34+
:end-before: end-dish-struct
35+
:language: go
36+
:dedent:
37+
2938
To run the examples in this guide, load the sample data into the
30-
``marvel.movies`` collection with the following
39+
``db.menu`` collection with the following
3140
snippet:
3241

3342
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
@@ -36,12 +45,10 @@ snippet:
3645
:start-after: begin insert docs
3746
:end-before: end insert docs
3847

39-
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
48+
Each document contains the ``name`` and ``description`` of a dish on a
49+
restaurant's menu.
4050

41-
Each document contains the name and release year of the Marvel movie
42-
that corresponds to the ``title`` and ``year`` fields.
43-
44-
.. include:: /includes/fundamentals/truncated-id.rst
51+
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
4552

4653
Text Index
4754
~~~~~~~~~~
@@ -51,8 +58,8 @@ index specifies the string or string array field on which to run a text
5158
search.
5259

5360
The examples in the following sections run text searches on the
54-
``title`` field in the ``movies`` collection. To enable text searches on
55-
the ``title`` field, create a text index with the following snippet:
61+
``description`` field of documents in the ``menu`` collection. To enable text searches on
62+
the ``description`` field, create a text index with the following snippet:
5663

5764
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
5865
:language: go
@@ -97,35 +104,45 @@ To search for multiple terms, separate each term with spaces in the string.
97104
Example
98105
```````
99106

100-
The following example runs a text search for titles that contain the term "War":
107+
The following example runs a text search for descriptions that contain the term "herb":
101108

102109
.. io-code-block::
103110
:copyable: true
104111

105112
.. input::
106113
:language: go
107114

108-
filter := bson.D{{"$text", bson.D{{"$search", "War"}}}}
115+
filter := bson.D{{"$text", bson.D{{"$search", "herb"}}}}
109116

110117
cursor, err := coll.Find(context.TODO(), filter)
111118
if err != nil {
112119
panic(err)
113120
}
114121

115-
var results []bson.D
122+
var results []Dish
116123
if err = cursor.All(context.TODO(), &results); err != nil {
117124
panic(err)
118125
}
126+
119127
for _, result := range results {
120-
fmt.Println(result)
128+
res, _ := json.Marshal(result)
129+
fmt.Println(string(res))
121130
}
122131

123132
.. output::
124133
:language: none
125134
:visible: false
126135

127-
[{_id ObjectID("...")} {title Avengers: Infinity War} {year 2018}]
128-
[{_id ObjectID("...")} {title Captain America: Civil War} {year 2016}]
136+
{"Name":"Kale Tabbouleh","Description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
137+
{"Name":"Herbed Whole Branzino","Description":"Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4."}
138+
139+
.. tip::
140+
141+
Although the search term was "herb", the method also matches
142+
descriptions containing "herbs" because a MongoDB text index uses suffix
143+
stemming to match similar words. To learn more about how
144+
MongoDB matches terms, see :manual:`Index Entries
145+
</core/index-text/#index-entries>`.
129146

130147
Search by a Phrase
131148
~~~~~~~~~~~~~~~~~~
@@ -142,35 +159,38 @@ phrase, the ``Find()`` method runs a :ref:`term search <golang-term-search>`.
142159
Example
143160
```````
144161

145-
The following example runs a text search for titles that contain the
146-
phrase "Infinity War":
162+
The following example runs a text search for descriptions that contain the
163+
phrase "serves 2":
147164

148165
.. io-code-block::
149166
:copyable: true
150167

151168
.. input::
152169
:language: go
153170

154-
filter := bson.D{{"$text", bson.D{{"$search", "\"Infinity War\""}}}}
171+
filter := bson.D{{"$text", bson.D{{"$search", "\"serves 2\""}}}}
155172

156173
cursor, err := coll.Find(context.TODO(), filter)
157174
if err != nil {
158175
panic(err)
159176
}
160177

161-
var results []bson.D
178+
var results []Dish
162179
if err = cursor.All(context.TODO(), &results); err != nil {
163180
panic(err)
164181
}
182+
165183
for _, result := range results {
166-
fmt.Println(result)
184+
res, _ := json.Marshal(result)
185+
fmt.Println(string(res))
167186
}
168187

169188
.. output::
170189
:language: none
171190
:visible: false
172191

173-
[{_id ObjectID("...")} {title Avengers: Infinity War} {year 2018}]
192+
{"Name":"Shepherd’s Pie","Description":"A vegetarian take on the classic dish that uses lentils as a base. Serves 2."}
193+
{"Name":"Garlic Butter Trout","Description":"Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2."}
174194

175195
Search with Terms Excluded
176196
~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -188,36 +208,37 @@ your query filter.
188208
Example
189209
```````
190210

191-
The following example runs a text search for titles that contain the
192-
term "Avenger", but does not contain the phrase "Captain America":
211+
The following example runs a text search for descriptions that contain the
212+
term "vegan", but do not contain the term "tofu":
193213

194214
.. io-code-block::
195215
:copyable: true
196216

197217
.. input::
198218
:language: go
199219

200-
filter := bson.D{{"$text", bson.D{{"$search", "Avenger -\"Captain America\""}}}}
220+
filter := bson.D{{"$text", bson.D{{"$search", "vegan -tofu"}}}}
201221

202222
cursor, err := coll.Find(context.TODO(), filter)
203223
if err != nil {
204224
panic(err)
205225
}
206226

207-
var results []bson.D
227+
var results []Dish
208228
if err = cursor.All(context.TODO(), &results); err != nil {
209229
panic(err)
210230
}
231+
211232
for _, result := range results {
212-
fmt.Println(result)
233+
res, _ := json.Marshal(result)
234+
fmt.Println(string(res))
213235
}
214236

215237
.. output::
216238
:language: none
217239
:visible: false
218240

219-
[{_id ObjectID("...")} {title The Avengers} {year 2012}]
220-
[{_id ObjectID("...")} {title Avengers: Infinity War} {year 2018}]
241+
{"Name":"Kale Tabbouleh","Description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
221242

222243
Sort by Relevance
223244
~~~~~~~~~~~~~~~~~
@@ -233,19 +254,19 @@ Example
233254

234255
The following example performs the following actions:
235256

236-
- Runs a text search for titles that contain the term "Avenger"
257+
- Runs a text search for descriptions that contain the term "vegetarian"
237258
- Sorts the results in descending order based on their text score
238-
- Includes the ``title`` and ``score`` fields from the results
259+
- Includes only the ``name`` and ``score`` fields in the final output document
239260

240261
.. io-code-block::
241262
:copyable: true
242263

243264
.. input::
244265
:language: go
245266

246-
filter := bson.D{{"$text", bson.D{{"$search", "Avenger"}}}}
267+
filter := bson.D{{"$text", bson.D{{"$search", "vegetarian"}}}}
247268
sort := bson.D{{"score", bson.D{{"$meta", "textScore"}}}}
248-
projection := bson.D{{"title", 1}, {"score", bson.D{{"$meta", "textScore"}}}, {"_id", 0}}
269+
projection := bson.D{{"name", 1}, {"score", bson.D{{"$meta", "textScore"}}}, {"_id", 0}}
249270
opts := options.Find().SetSort(sort).SetProjection(projection)
250271

251272
cursor, err := coll.Find(context.TODO(), filter, opts)
@@ -265,17 +286,9 @@ The following example performs the following actions:
265286
:language: none
266287
:visible: false
267288

268-
[{title The Avengers} {score 1}]
269-
[{title Avengers: Infinity War} {score 0.6666666666666666}]
270-
[{title Captain America: The First Avenger} {score 0.625}]
271-
272-
.. tip::
273-
274-
Although the search term was "Avenger", the method also matches
275-
titles containing "Avengers" because a MongoDB text index uses suffix
276-
stemming to match similar words. To learn more about how
277-
MongoDB matches terms, see :manual:`Index Entries
278-
</core/index-text/#index-entries>`.
289+
[{name Green Curry} {score 0.8999999999999999}]
290+
[{name Kale Tabbouleh} {score 0.5625}]
291+
[{name Shepherd’s Pie} {score 0.5555555555555556}]
279292

280293
.. _golang-search-text-aggregation:
281294

@@ -286,56 +299,59 @@ You can also include the ``$text`` evaluation query operator in the
286299
:manual:`$match </reference/operator/aggregation/match/>` stage to
287300
perform a text search in an aggregation pipeline.
288301

289-
Term Search Example
302+
Match a Search Term
290303
~~~~~~~~~~~~~~~~~~~
291304

292-
The following example runs a text search for titles that contain the term "Winter":
305+
The following example runs a text search for descriptions that contain the term "herb":
293306

294307
.. io-code-block::
295308
:copyable: true
296309

297310
.. input::
298311
:language: go
299312

300-
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "Winter"}}}}}}
313+
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "herb"}}}}}}
301314

302315
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage})
303316
if err != nil {
304317
panic(err)
305318
}
306319

307-
var results []bson.D
320+
var results []Dish
308321
if err = cursor.All(context.TODO(), &results); err != nil {
309322
panic(err)
310323
}
324+
311325
for _, result := range results {
312-
fmt.Println(result)
326+
res, _ := json.Marshal(result)
327+
fmt.Println(string(res))
313328
}
314329

315330
.. output::
316331
:language: none
317332
:visible: false
318333

319-
[{_id ObjectID("...")} {title Captain America: The Winter Soldier} {year 2014}]
334+
{"Name":"Kale Tabbouleh","Description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
335+
{"Name":"Herbed Whole Branzino","Description":"Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4."}
320336

321-
Text Score Example
322-
~~~~~~~~~~~~~~~~~~
337+
Sort by Relevance
338+
~~~~~~~~~~~~~~~~~
323339

324340
The following example performs the following actions:
325341

326-
- Runs a text search for titles that contain the term "Avenger"
342+
- Runs a text search for descriptions that contain the term "vegetarian"
327343
- Sorts the results in descending order based on their text score
328-
- Includes the ``title`` and ``score`` fields from the results
344+
- Includes only the ``name`` and ``score`` fields in the final output document
329345

330346
.. io-code-block::
331347
:copyable: true
332348

333349
.. input::
334350
:language: go
335351

336-
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "Avenger"}}}}}}
352+
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "vegetarian"}}}}}}
337353
sortStage := bson.D{{"$sort", bson.D{{"score", bson.D{{ "$meta", "textScore" }}}}}}
338-
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"score", bson.D{{ "$meta", "textScore" }}}, {"_id", 0}}}}
354+
projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"score", bson.D{{ "$meta", "textScore" }}}, {"_id", 0}}}}
339355

340356
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, sortStage, projectStage})
341357
if err != nil {
@@ -354,17 +370,9 @@ The following example performs the following actions:
354370
:language: none
355371
:visible: false
356372

357-
[{title The Avengers} {score 1}]
358-
[{title Avengers: Infinity War} {score 0.6666666666666666}]
359-
[{title Captain America: The First Avenger} {score 0.625}]
360-
361-
.. tip::
362-
363-
Although the search term was "Avenger", the method also matches
364-
titles containing "Avengers" because a MongoDB text index uses suffix
365-
stemming to match similar words. To learn more about how
366-
MongoDB matches terms, see :manual:`Index Entries
367-
</core/index-text/#index-entries>`.
373+
[{name Green Curry} {score 0.8999999999999999}]
374+
[{name Kale Tabbouleh} {score 0.5625}]
375+
[{name Shepherd’s Pie} {score 0.5555555555555556}]
368376

369377
Additional Information
370378
----------------------

0 commit comments

Comments
 (0)