本教程演示了如何通过将非字符串字段转换为字符串并将它们存储在物化视图中,针对这些非字符串字段运行字符串特定的查询。物化视图可让您使用特定于字符串的操作符来查询转换后的字段,并在源集合中保持原始数据不变。
本教程将指导您完成以下步骤:
在开始之前,请确保您的集群满足先决条件中描述的要求。
创建一个物化视图
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.
在物化视图上创建MongoDB Search 索引
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 for a MongoDB Search Index or Index Reference, respectively.
以下JSON MongoDB Search索引定义使用动态映射对物化视图中的字段索引。您可以使用此索引通过queryString操作符运行查询。
您无法使用autocomplete操作符对动态索引字段运行查询。
{ "mappings": { "dynamic": true } }
以下JSON MongoDB Search索引定义使用静态映射将物化视图中的字段索引为autocomplete 类型。您可以使用此索引通过 autocomplete操作符 运行查询。
不能使用 queryString 操作符对索引为 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" } ] } } }
要学习;了解如何使用您的首选接口创建上面定义的索引,请参阅支持的客户端。
对转换后的字段运行查询
您可以对已转换为字符串的 numeric 和 date 字段运行查询。本教程使用 queryString 和 autocomplete 操作符来搜索属性。查询使用了下列管道阶段:
在本部分中,您将连接到集群并使用操作符针对 airbnb_mat_view集合中的字段运行示例查询。
Query with queryString
The following procedure runs queryString queries against the converted fields. Use the index that you created with dynamic mappings.
Query with autocomplete
The following procedure runs autocomplete queries against the converted fields. Use the index that you created with static mappings.