-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathtext.txt
403 lines (292 loc) · 11.4 KB
/
text.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
.. _golang-search-text:
===========
Search Text
===========
.. meta::
:description: Learn how to perform text searches in MongoDB using Go, including creating text indexes and sorting results by relevance.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to run a :ref:`text search
<golang-text-search>`.
.. important::
MongoDB text search is different than :atlas:`Atlas Search
</atlas-search/>`.
Sample Data
~~~~~~~~~~~
The examples in this guide use the following ``Dish`` struct as a model for documents
in the ``menu`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
:start-after: start-dish-struct
:end-before: end-dish-struct
:language: go
:dedent:
To run the examples in this guide, load the sample data into the
``db.menu`` collection with the following
snippet:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
:language: go
:dedent:
:start-after: begin insert docs
:end-before: end insert docs
Each document contains the ``name`` and ``description`` of a dish on a
restaurant's menu.
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
Text Index
~~~~~~~~~~
You must create a **text index** before running a text search. A text
index specifies the string or string array field on which to run a text
search.
The examples in the following sections run text searches on the
``description`` field of documents in the ``menu`` collection. To enable text searches on
the ``description`` field, create a text index with the following snippet:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/textSearch.go
:language: go
:dedent:
:start-after: begin text index
:end-before: end text index
.. _golang-text-search:
Text Search
-----------
A text search retrieves documents that contain a **term** or a
**phrase** in the text indexed fields. A term is a sequence of
characters that excludes whitespace characters. A phrase is a sequence
of terms with any number of whitespace characters.
To perform a text search, use the ``$text`` evaluation query operator,
followed by the ``$search`` field in your query filter. The ``$text`` operator
performs a text search on the text indexed fields. The ``$search`` field
specifies the text to search in the text indexed fields.
Query filters for text searches use the following format:
.. code-block:: go
filter := bson.D{{"$text", bson.D{{"$search", "<text to search>"}}}}
.. _golang-term-search:
Search by a Term
~~~~~~~~~~~~~~~~
To search for a term, specify the term as a string in your query filter.
To search for multiple terms, separate each term with spaces in the string.
.. note::
When searching for multiple terms, the ``Find()`` method returns
documents with at least one of the terms in text indexed fields.
Example
```````
The following example runs a text search for descriptions that contain the term "herb":
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"$text", bson.D{{"$search", "herb"}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []Dish
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Kale Tabbouleh","description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
{"name":"Herbed Whole Branzino","description":"Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4."}
.. tip::
Although the search term was "herb", the method also matches
descriptions containing "herbs" because a MongoDB text index uses suffix
stemming to match similar words. To learn more about how
MongoDB matches terms, see :manual:`Index Entries
</core/index-text/#index-entries>`.
Search by a Phrase
~~~~~~~~~~~~~~~~~~
To search for a phrase, specify the phrase with escaped quotes as a
string in your query filter. If you don't add escaped quotes around the
phrase, the ``Find()`` method runs a :ref:`term search <golang-term-search>`.
.. tip::
Escaped quotes are a backslash character followed by a double quote
character.
Example
```````
The following example runs a text search for descriptions that contain the
phrase "serves 2":
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"$text", bson.D{{"$search", "\"serves 2\""}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []Dish
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Shepherd's Pie","description":"A vegetarian take on the classic dish that uses lentils as a base. Serves 2."}
{"name":"Garlic Butter Trout","description":"Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2."}
Search with Terms Excluded
~~~~~~~~~~~~~~~~~~~~~~~~~~
For each term or phrase you want to exclude from your text search,
specify the term or phrase prefixed with a minus sign as a string in
your query filter.
.. important::
You must search for at least one term if you want to exclude
terms from your search. If you don't search for any terms, the
``Find()`` method doesn't return any documents.
Example
```````
The following example runs a text search for descriptions that contain the
term "vegan", but do not contain the term "tofu":
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"$text", bson.D{{"$search", "vegan -tofu"}}}}
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}
var results []Dish
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Kale Tabbouleh","description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
Sort by Relevance
~~~~~~~~~~~~~~~~~
A text search assigns a numerical text score to indicate how closely
each result matches the string in your query filter. To reveal the text
score in your output, use a projection to retrieve the ``textScore``
metadata. You can sort the text score in descending order by specifying
a sort on the ``textScore`` metadata.
Example
```````
The following example performs the following actions:
- Runs a text search for descriptions that contain the term "vegetarian"
- Sorts the results in descending order based on their text score
- Includes only the ``name`` and ``score`` fields in the final output document
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"$text", bson.D{{"$search", "vegetarian"}}}}
sort := bson.D{{"score", bson.D{{"$meta", "textScore"}}}}
projection := bson.D{{"name", 1}, {"score", bson.D{{"$meta", "textScore"}}}, {"_id", 0}}
opts := options.Find().SetSort(sort).SetProjection(projection)
cursor, err := coll.Find(context.TODO(), filter, opts)
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Green Curry","score":0.8999999999999999}
{"name":"Kale Tabbouleh","score":0.5625}
{"name":"Shepherd's Pie","score":0.5555555555555556}
.. _golang-search-text-aggregation:
Aggregation
-----------
You can also include the ``$text`` evaluation query operator in the
:manual:`$match </reference/operator/aggregation/match/>` stage to
perform a text search in an aggregation pipeline.
Match a Search Term
~~~~~~~~~~~~~~~~~~~
The following example runs a text search for descriptions that contain the term "herb":
.. io-code-block::
:copyable: true
.. input::
:language: go
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "herb"}}}}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage})
if err != nil {
panic(err)
}
var results []Dish
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Kale Tabbouleh","description":"A bright, herb-based salad. A perfect starter for vegetarians and vegans."}
{"name":"Herbed Whole Branzino","description":"Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4."}
Sort by Relevance
~~~~~~~~~~~~~~~~~
The following example performs the following actions:
- Runs a text search for descriptions that contain the term "vegetarian"
- Sorts the results in descending order based on their text score
- Includes only the ``name`` and ``score`` fields in the final output document
.. io-code-block::
:copyable: true
.. input::
:language: go
matchStage := bson.D{{"$match", bson.D{{"$text", bson.D{{"$search", "vegetarian"}}}}}}
sortStage := bson.D{{"$sort", bson.D{{"score", bson.D{{ "$meta", "textScore" }}}}}}
projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"score", bson.D{{ "$meta", "textScore" }}}, {"_id", 0}}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, sortStage, projectStage})
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"name":"Green Curry","score":0.8999999999999999}
{"name":"Kale Tabbouleh","score":0.5625}
{"name":"Shepherd's Pie","score":0.5555555555555556}
Additional Information
----------------------
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-sort-results`
- :ref:`golang-project`
- :manual:`Text Indexes </core/index-text/>`
- :manual:`$text </reference/operator/query/text/>`
- :manual:`$meta </reference/operator/aggregation/meta/>`
- :ref:`golang-aggregation`
- :ref:`golang-indexes`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `Find() <{+api+}/mongo#Collection.Find>`__
- `FindOptionsBuilder.SetSort() <{+api+}/mongo/options#FindOptionsBuilder.SetSort>`__
- `FindOptionsBuilder.SetProjection() <{+api+}/mongo/options#FindOptionsBuilder.SetProjection>`__