This tutorial demonstrates how to run string-specific queries against non-string fields by converting the fields to strings and storing them in a materialized view. The materialized view lets you use string-specific operators to query the converted fields and keep the original data intact in the source collection.
This tutorial takes you through the following steps:
Before you begin, ensure that your cluster meets the requirements described in the Prerequisites.
Create a Materialized View
This section demonstrates how to create a
materialized view
named airbnb-mat-view
on the
sample_airbnb.listingsAndReviews collection.
This view stores various numeric and date fields from the source
collection as string fields.
Create MongoDB Search Indexes on the Materialized View
To run the queries in the Run Queries on the Converted Fields stage of
this tutorial, you need to create MongoDB Search indexes on the converted
string fields in your airbnb_mat_view
materialized view.
The following JSON definitions define MongoDB Search indexes on the
airbnb_mat_view
materialized view. You can use dynamic or static
mappings to specify which fields you want to index in your
collection, depending on the type of queries you want to run. To
learn more about field mappings or MongoDB Search index syntax, see
Define Field Mappings or Index Reference,
respectively.
The following JSON MongoDB Search index definition uses dynamic mappings to index the fields in the materialized view. You can use this index to run queries using the queryString operator.
You can't run queries using the autocomplete operator against dynamically indexed fields.
{ "mappings": { "dynamic": true } }
The following JSON MongoDB Search index definition uses static mappings to index the fields in the materialized view as the autocomplete type. You can use this index to run queries using the autocomplete operator.
You can't run queries using the queryString operator against fields indexed as type
autocomplete
.
{ "mappings": { "dynamic": false, "fields": { "accommodatesNumber": [ { "dynamic": true, "type": "document" }, { "minGrams": 1, "type": "autocomplete" } ], "lastScrapedDate": [ { "dynamic": true, "type": "document" }, { "type": "autocomplete" } ], "maximumNumberOfNights": [ { "dynamic": true, "type": "document" }, { "minGrams": 1, "type": "autocomplete" } ] } } }
To learn how to create the indexes defined above using your preferred interface, see Supported Clients.
Run Queries on the Converted Fields
You can run queries against the numeric and date fields that were converted to strings. This tutorial uses queryString and autocomplete operators to search for properties. The query uses the following pipeline stages:
$search
stage to search the collection$limit
stage to limit the output to5
results$project
stage to exclude_id
In this section, you connect to your cluster and run
the sample queries using the operator against the fields in the
airbnb_mat_view
collection.