如何定义自定义分析器并运行 Atlas Search 不区分变音符号的查询
本教程介绍如何创建使用自定义分析器的索引,并对 sample_mflix.movies
集合运行不区分变音符号的查询。它将引导您完成以下步骤:
在
sample_mflix.movies
collection中的title
和genres
字段上设置 Atlas Search 索引。使用 通配符 和 文本
title
操作符,针对genres
collection中的 和 字段运行 Atlas Search 查询 。sample_mflix.movies
开始之前,请确保 Atlas 集群满足先决条件中所述的要求。
要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin
或更高的项目访问权限。
创建 Atlas Search 索引
在本部分中,您将在sample_mflix.movies
collection中的title
和genres
字段上创建 Atlas Search 索引。
输入Index Name ,然后设置Database and Collection 。
在 Index Name 字段中输入
diacritic-insensitive-tutorial
。注意
如果将索引命名为
default
,则在使用 $search 管道阶段时,您无需指定index
参数。否则,您必须使用index
参数指定索引名称。在 Database and Collection(数据库和集合)部分中找到
sample_mflix
数据库,然后选择movies
集合。
指定索引定义。
genres
和title
字段的索引定义使用以下内容指定自定义分析器diacriticFolder
:
关键字分词器,将整个输入标记为单个词元。
icuFolding 词元筛选器,用于应用字符折叠,例如删除重音和大小写折叠。
索引定义指定了genres
和title
字段的字符串类型。它还对title
字段应用名为diacriticFolder
的自定义分析器。
使用 Atlas user 界面中的 Atlas Search Visual Editor或 Atlas Search JSON Editor创建索引。
单击 Next(连接)。
单击 Refine Your Index(连接)。
在 Custom Analyzers 部分中,单击 Add Custom Analyzer。
选择 Create Your Own 单选按钮并单击 Next。
在 Analyzer Name 字段中输入
diacriticFolder
。如果Tokenizer已折叠,请将其展开,然后从下拉列表中选择
keyword
。展开 Token Filters,然后单击 Add token filter。
从下拉列表中选择
icuFolding
,然后单击 Add token filter 以将词元过滤器添加到您的自定义分析器中。单击 Add,将自定义分析器添加到索引。
在Field Mappings部分中,单击Add Field Mapping可对
title
字段应用自定义分析器。从Field Name下拉列表中选择
title
,并从Data Type下拉列表中选择字符串。在数据类型的属性部分中,从 Index Analyzer 和 Search Analyzer 下拉菜单中选择
diacriticFolder
。单击 Add(连接)。
再次单击Add Field Mapping为
genres
字段编制索引。从Field Name下拉列表中选择
genres
,并从Data Type下拉列表中选择字符串。单击 Add,然后单击 Save Changes。
将默认定义替换为以下内容:
1 { 2 "mappings": { 3 "fields": { 4 "genres": { 5 "type": "string" 6 }, 7 "title": { 8 "analyzer": "diacriticFolder", 9 "type": "string" 10 } 11 } 12 }, 13 "analyzers": [{ 14 "charFilters": [], 15 "name": "diacriticFolder", 16 "tokenizer": { 17 "type": "keyword" 18 }, 19 "tokenFilters": [{ 20 "type": "icuFolding" 21 }] 22 }] 23 }
单击 Next(连接)。
搜索集合
➤ 使用选择语言下拉菜单设置本节中示例的语言。
您可以使用复合运算符将两个或多个操作符组合成一个查询。本部分中的示例查询使用复合运算符,通过多个运算符查询movies
集合中的title
和genres
字段。
在本部分中,连接到你的 Atlas 集群并使用compound
操作符针对sample_mflix.movies
collection 运行样本查询。
运行 Atlas Search 不区分变音符号的搜索。
此查询使用$search
阶段来查询使用compound
操作符的集合。 compound
操作符使用以下子句:
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
1 [ 2 { 3 "$search" : { 4 "index": "diacritic-insensitive-tutorial", 5 "compound" : { 6 "must": [{ 7 "wildcard" : { 8 "query" : "alle*", 9 "path": "title", 10 "allowAnalyzedField": true 11 } 12 }], 13 "should": [{ 14 "text": { 15 "query" : "Drama", 16 "path" : "genres" 17 } 18 }] 19 } 20 } 21 } 22 ]
SCORE: 1.2084882259368896 _id: "573a13a1f29313caabd07bb6" plot: "A group of hip retro teenage outsiders become involved in an interscho…" genres: 0: "Drama" 1: "Family" 2: "Sport" runtime: 103 title: "Alley Cats Strike" SCORE: 1.179288625717163 _id: "573a13b1f29313caabd382a2" plot: "Famous pianist Zetterstrèm returns home to his native Denmark, to give…" genres: 0: "Drama" 1: "Romance" 2: "Sci-Fi" runtime: 88 title: "Allegro" SCORE: 1 _id: "573a1397f29313caabce5f15" plot: "An enthusiastic filmmaker thinks he's come up with a totally original …" genres: 0: "Animation" 1: "Comedy" 2: "Fantasy" runtime: 75 title: "Allegro non troppo" SCORE: 1 _id: "573a13d1f29313caabd8f84b" plot: "The eleven year old cycling talent Freddy is the son of a butcher in a…" genres: 0: "Comedy" runtime: 100 title: "Allez, Eddy!"
展开查询结果。
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
连接到mongosh
中的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用sample_mflix
数据库。
在 mongosh
提示符下运行以下命令:
use sample_mflix
运行 Atlas Search 不区分变音符号的搜索。
此查询使用$search
阶段来查询使用compound
操作符的集合。 compound
操作符使用以下子句:
该查询使用$project
阶段执行以下操作:
排除
title
和genres
之外的所有字段添加字段
score
1 db.movies.aggregate([ 2 { 3 "$search" : { 4 "index": "diacritic-insensitive-tutorial", 5 "compound" : { 6 "must": [{ 7 "wildcard" : { 8 "query" : "alle*", 9 "path": "title", 10 "allowAnalyzedField": true 11 } 12 }], 13 "should": [{ 14 "text": { 15 "query" : "Drama", 16 "path" : "genres" 17 } 18 }] 19 } 20 } 21 }, 22 { 23 "$project" : { 24 "_id" : 0, 25 "title" : 1, 26 "genres" : 1, 27 "score" : { "$meta": "searchScore" } 28 } 29 } 30 ])
{ genres: [ 'Drama', 'Family', 'Sport' ], title: 'Alley Cats Strike', score: 1.2084882259368896 }, { genres: [ 'Drama', 'Romance', 'Sci-Fi' ], title: 'Allegro', score: 1.179288625717163 }, { genres: [ 'Animation', 'Comedy', 'Fantasy' ], title: 'Allegro non troppo', score: 1 }, { genres: [ 'Comedy' ], title: 'Allez, Eddy!', score: 1 }
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
运行 Atlas Search 不区分变音符号的搜索。
此查询使用以下compound
操作符子句来查询collection:
该查询使用$project
阶段执行以下操作:
排除
title
和genres
之外的所有字段添加字段
score
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。
管道阶段 | 查询 | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| ||||||||||||||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
{ genres: [ 'Drama', 'Family', 'Sport' ], title: 'Alley Cats Strike', score: 1.2084882259368896 }, { genres: [ 'Drama', 'Romance', 'Sci-Fi' ], title: 'Allegro', score: 1.179288625717163 }, { genres: [ 'Animation', 'Comedy', 'Fantasy' ], title: 'Allegro non troppo', score: 1 }, { genres: [ 'Comedy' ], title: 'Allez, Eddy!', score: 1 }
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
在Program.cs
文件中创建查询。
将
Program.cs
文件的内容替换为以下代码。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class DiacriticInsensitiveExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "alle*", true)) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Drama")), 27 indexName: "diacritic-insensitive-tutorial") 28 .Project<MovieDocument>(Builders<MovieDocument>.Projection 29 .Include(movie => movie.Title) 30 .Include(movie => movie.Genres) 31 .Exclude(movie => movie.Id) 32 .MetaSearchScore(movie => movie.Score)) 33 .ToList(); 34 35 // print results 36 foreach (var movie in results) 37 { 38 Console.WriteLine(movie.ToJson()); 39 } 40 } 41 } 42 43 [ ]44 public class MovieDocument 45 { 46 [ ]47 public ObjectId Id { get; set; } 48 public string [] Genres { get; set; } 49 public string Title { get; set; } 50 public double Score { get; set; } 51 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行Program.cs
文件。
dotnet run diacritic-insensitive-example.csproj
{ "genres" : ["Drama", "Family", "Sport"], "title" : "Alley Cats Strike", "score" : 1.2084882259368896 } { "genres" : ["Drama", "Romance", "Sci-Fi"], "title" : "Allegro", "score" : 1.1792886257171631 } { "genres" : ["Animation", "Comedy", "Fantasy"], "title" : "Allegro non troppo", "score" : 1.0 } { "genres" : ["Comedy"], "title" : "Allez, Eddy!", "score" : 1.0 }
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
运行 Atlas Search 不区分变音符号的搜索。
创建一个名为
diacritic-insensitive.go
的文件。将以下代码复制并粘贴到
diacritic-insensitive.go
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{{"$search", bson.M{ 25 "index": "diacritic-insensitive-tutorial", 26 "compound": bson.M{ 27 "must": bson.M{ 28 "wildcard": bson.M{ 29 "path": "title", 30 "query": "alle*", 31 "allowAnalyzedField": true, 32 }, 33 }, 34 "should": bson.D{ 35 {"text", bson.M{ 36 "path": "genres", 37 "query": "Drama"}}}, 38 }, 39 }}} 40 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"genres", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 41 42 // run pipeline 43 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage}) 44 if err != nil { 45 panic(err) 46 } 47 48 // print results 49 var results []bson.D 50 if err = cursor.All(context.TODO(), &results); err != nil { 51 panic(err) 52 } 53 for _, result := range results { 54 fmt.Println(result) 55 } 56 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
go run diacritic-insensitive.go [{genres [Drama Family Sport]} {title Alley Cats Strike} {score 1.2084882259368896}] [{genres [Drama Romance Sci-Fi]} {title Allegro} {score 1.179288625717163}] [{genres [Animation Comedy Fantasy]} {title Allegro non troppo} {score 1}] [{genres [Comedy]} {title Allez, Eddy!} {score 1}]
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
运行 Atlas Search 不区分变音符号的搜索。
创建一个名为
DiacriticInsensitive.java
的文件。将以下代码复制并粘贴到
DiacriticInsensitive.java
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 import static com.mongodb.client.model.Aggregates.project; 2 import static com.mongodb.client.model.Projections.*; 3 import com.mongodb.client.MongoClient; 4 import com.mongodb.client.MongoClients; 5 import com.mongodb.client.MongoCollection; 6 import com.mongodb.client.MongoDatabase; 7 import org.bson.Document; 8 import java.util.Arrays; 9 import java.util.List; 10 11 public class DiacriticInsensitive { 12 public static void main(String[] args) { 13 // define clauses 14 List<Document> mustClauses = 15 List.of( new Document("wildcard", 16 new Document("path", "title") 17 .append("query", "alle*") 18 .append("allowAnalyzedField", true))); 19 List<Document> shouldClauses = 20 List.of( new Document("text", 21 new Document("query", "Drama") 22 .append("path", "genres"))); 23 // define pipeline 24 Document agg = new Document( "$search", 25 new Document("index", "diacritic-insensitive-tutorial") 26 .append("compound", 27 new Document("must", mustClauses) 28 .append("should", shouldClauses))); 29 30 // connect to your Atlas cluster 31 String uri = "<connection-string>"; 32 33 try (MongoClient mongoClient = MongoClients.create(uri)) { 34 // set namespace 35 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 36 MongoCollection<Document> collection = database.getCollection("movies"); 37 38 // run pipeline and print results 39 collection.aggregate(Arrays.asList(agg, 40 project(fields( 41 excludeId(), 42 include("title"), 43 include("genres"), 44 computed("score", new Document("$meta", "searchScore")))))) 45 .forEach(doc -> System.out.println(doc.toJson())); 46 } 47 } 48 } 注意
要在 Maven 环境中运行示例代码,请将以下代码添加到文件中的 import 语句上方。
package com.mongodb.drivers; 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
DiacriticInsensitive.java
文件。javac DiacriticInsensitive.java java DiacriticInsensitive {"genres": ["Drama", "Family", "Sport"], "title": "Alley Cats Strike", "score": 1.2084882259368896} {"genres": ["Drama", "Romance", "Sci-Fi"], "title": "Allegro", "score": 1.179288625717163} {"genres": ["Animation", "Comedy", "Fantasy"], "title": "Allegro non troppo", "score": 1.0} {"genres": ["Comedy"], "title": "Allez, Eddy!", "score": 1.0}
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
运行 Atlas Search 不区分变音符号的搜索。
创建一个名为
DiacriticInsensitive.kt
的文件。将以下代码复制并粘贴到
DiacriticInsensitive.kt
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
打印与
AggregateFlow
实例中的查询相匹配的文档。
1 import com.mongodb.client.model.Aggregates.project 2 import com.mongodb.client.model.Projections.* 3 import com.mongodb.kotlin.client.coroutine.MongoClient 4 import kotlinx.coroutines.runBlocking 5 import org.bson.Document 6 7 fun main() { 8 // connect to your Atlas cluster 9 val uri = "<connection-string>" 10 val mongoClient = MongoClient.create(uri) 11 12 // set namespace 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClauses = listOf( 19 Document( 20 "wildcard", 21 Document("path", "title") 22 .append("query", "alle*") 23 .append("allowAnalyzedField", true) 24 ) 25 ) 26 27 val shouldClauses = listOf( 28 Document( 29 "text", 30 Document("query", "Drama") 31 .append("path", "genres") 32 ) 33 ) 34 35 // define pipeline 36 val agg = Document( "\$search", 37 Document("index", "diacritic-insensitive-tutorial") 38 .append("compound", Document("must", mustClauses) 39 .append("should", shouldClauses) 40 ) 41 ) 42 43 // run pipeline and print results 44 val resultsFlow = collection.aggregate<Document>( 45 listOf( 46 agg, 47 project(fields( 48 excludeId(), 49 include("title", "genres"), 50 computed("score", Document("\$meta", "searchScore")))) 51 ) 52 ) 53 resultsFlow.collect { println(it) } 54 } 55 56 mongoClient.close() 57 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行
DiacriticInsensitive.kt
文件。当你在 IDE 中运行
DiacriticInsensitive.kt
程序时,它会打印以下文档:Document{{genres=[Drama, Family, Sport], title=Alley Cats Strike, score=1.2084882259368896}} Document{{genres=[Drama, Romance, Sci-Fi], title=Allegro, score=1.179288625717163}} Document{{genres=[Animation, Comedy, Fantasy], title=Allegro non troppo, score=1.0}} Document{{genres=[Comedy], title=Allez, Eddy!, score=1.0}}
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
运行 Atlas Search 不区分变音符号的搜索。
创建一个名为
diacritic-insensitive.js
的文件。将以下代码复制并粘贴到
diacritic-insensitive.js
文件。此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 13 // set namespace 14 const database = client.db("sample_mflix"); 15 const coll = database.collection("movies"); 16 17 // define pipeline 18 const agg = [{ 19 '$search': { 20 'index': 'diacritic-insensitive-tutorial', 21 'compound': { 22 'must': [{ 23 'wildcard': { 24 'query': "alle*", 25 'path': "title", 26 'allowAnalyzedField': true 27 } 28 }], 29 'should': [{'text': {'query': 'Drama', 'path': 'genres'}}] 30 }}}, 31 { '$project': { '_id': 0, 'title': 1 , 'genres': 1, 'score': {'$meta': 'searchScore'}}}]; 32 33 // run pipeline 34 const result = await coll.aggregate(agg); 35 36 // print results 37 await result.forEach((doc) => console.log(doc)); 38 39 } finally { 40 await client.close(); 41 } 42 } 43 run().catch(console.dir); 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
node diacritic-insensitive.js { genres: [ 'Drama', 'Family', 'Sport' ], title: 'Alley Cats Strike', score: 1.2084882259368896 } { genres: [ 'Drama', 'Romance', 'Sci-Fi' ], title: 'Allegro', score: 1.179288625717163 } { genres: [ 'Animation', 'Comedy', 'Fantasy' ], title: 'Allegro non troppo', score: 1 } { genres: [ 'Comedy' ], title: 'Allez, Eddy!', score: 1 }
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。
运行 Atlas Search 不区分变音符号的搜索。
创建一个名为
diacritic-insensitive.py
的文件。将以下代码复制并粘贴到
diacritic-insensitive.py
文件。以下代码示例:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用DNS种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下
compound
操作符子句对该集合进行查询:该查询使用
$project
阶段执行以下操作:排除
title
和genres
之外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'diacritic-insensitive-tutorial', 10 'compound': { 11 'must': [{'wildcard': {'path': 'title', 'query': 'alle*', 'allowAnalyzedField': True}}], 12 'should': [{'text': {'query': 'Drama', 'path': 'genres'}}]}}}, 13 {'$project': {'_id': 0, 'title': 1, 'genres': 1, 'score': {'$meta': 'searchScore'}}} 14 ] 15 16 # run pipeline 17 result = client['sample_mflix']['movies'].aggregate(pipeline) 18 19 # print results 20 for i in result: 21 print(i) 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
python diacritic-insensitive.py {'genres': ['Drama', 'Family', 'Sport'], 'title': 'Alley Cats Strike', 'score': 1.2084882259368896} {'genres': ['Drama', 'Romance', 'Sci-Fi'], 'title': 'Allegro', 'score': 1.179288625717163} {'genres': ['Animation', 'Comedy', 'Fantasy'], 'title': 'Allegro non troppo', 'score': 1.0} {'genres': ['Comedy'], 'title': 'Allez, Eddy!', 'score': 1.0}
结果中的第一个文档在title
字段中包含变音符号,因为我们在title
字段上使用的diacriticFolder
自定义分析器对其值应用了字符折叠。 Atlas Search 返回标题以查询词alle
开头的文档,因为我们使用了关键字分词器,它将整个字符串(或短语)分词为单个词元。
或者,您可以在用于标题字段的自定义分析器中指定标准分词器,而不是关键字分词器。 对于标准分词器,Atlas Search 结果将包含标题以查询词alle
的词开头的任何位置开始或出现在该词开头的文档,例如“Desde allè”。 要对此进行测试,请编辑 索引定义 ,将第keyword
行上的17 分词器替换为standard
分词器,保存索引定义,然后运行示例查询。