自动补全
在此页面上
定义
autocomplete
autocomplete操作符从不完整输入字符串中搜索包含字符序列的单词或短语。您打算使用
autocomplete
操作符查询的字段必须使用集合索引定义中的自动完成数据类型进行索引。
注意
对于单个字符串中包含三个以上单词的查询,Atlas Search 可能会返回不准确的结果。
示例使用案例
您可以将 autocomplete
运算符与“键入时搜索”应用程序一起使用,以在应用程序的搜索字段中输入字符时更加准确地预测单词。autocomplete
返回的结果包含根据自动完成索引定义中指定的标记化策略所预测的单词。
如果您想使用 Atlas Search自动完成操作符构建建议或下拉列表,我们建议您查询建议搜索词的集合或使用过去的搜索词来填充下拉列表。如果您创建单独的建议搜索词集合,则可以在 Atlas Search 索引中定义同义词映射,以便在集合中搜索确切的单词或替代单词。您可以跟踪搜索词并查看搜索词的指标以构建您的集合。
语法
autocomplete
通过以下语法实现:
1 { 2 $search: { 3 "index": "<index name>", // optional, defaults to "default" 4 "autocomplete": { 5 "query": "<search-string>", 6 "path": "<field-to-search>", 7 "tokenOrder": "any|sequential", 8 "fuzzy": <options>, 9 "score": <options> 10 } 11 } 12 }
选项
字段 | 类型 | 说明 | 必要性 | 默认 | ||||||
---|---|---|---|---|---|---|---|---|---|---|
query | 字符串或字符串数组 | 要搜索的一个或多个字符串。如果字符串中有多个词,Atlas Search 还会分别为字符串中的每个词查找匹配项。 | 是 | |||||||
path | 字符串 | 要搜索的已索引 autocomplete 类型字段。 | 是 | |||||||
fuzzy | 对象 | 启用模糊搜索。查找与搜索词相似的字符串。 | 没有 | |||||||
fuzzy .maxEdits | 整型 | 匹配指定搜索词所需的最大单字符编辑数。值可以是 1 或 2 。 | 没有 | 2 | ||||||
fuzzy .prefixLength | 整型 | 结果中每个术语开头必须完全匹配的字符数。 | 没有 | 0 | ||||||
fuzzy .maxExpansions | 整型 | 生成和搜索变体的最大数量。此限制适用于每个令牌。 | 没有 | 50 | ||||||
score | 对象 | 要分配给匹配搜索词结果的分数。使用以下选项之一修改默认分数:
有关在查询中使用 注意
要了解更多信息,请参阅评分行为。 | 没有 | |||||||
tokenOrder | 字符串 | 搜索令牌的顺序。值可以是以下之一:
| 没有 | any |
评分行为
属于完全匹配的 autocomplete
运算符查询结果比非完全匹配的结果得分低。如果仅指定 autocomplete 已索引的令牌子字符串,Atlas Search 则无法确定查询字符串是否与索引的文本完全匹配。要提高完全匹配的得分,请尝试以下解决方法:
注意
以下解决方法无法保证在所有情况下精确匹配都能获得较高的分数。
当
autocomplete
字段也被索引为string
时,Atlas Searchautocomplete
会提高精确匹配度,从而提高精确匹配的分数。使用复合操作符查询。
有关此解决方法的演示,请参阅跨多个字段搜索。
举例
以下示例使用 sample_mflix
数据库中的 movies
集合。如果在集群上加载了样本数据集,则可以创建用于自动完成的静态索引,并在集群上运行示例查询。
提示
如果您已经加载示例数据集,请按照 Atlas Search 入门教程,创建索引定义并运行 Atlas Search 查询。
索引定义
以下标签页包含 edgeGram
、rightEdgeGram
和 nGram
分词器策略的示例索引定义。除了 autocomplete 类型以外,示例索引定义还包括 title
字段上的 string 和 stringFacet 类型。
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": [ 6 { 7 "type": "stringFacet" 8 }, 9 { 10 "type": "string" 11 }, 12 { 13 "foldDiacritics": false, 14 "maxGrams": 7, 15 "minGrams": 3, 16 "tokenization": "edgeGram", 17 "type": "autocomplete" 18 } 19 ] 20 } 21 } 22 }
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": [ 6 { 7 "type": "stringFacet" 8 }, 9 { 10 "type": "string" 11 }, 12 { 13 "type": "autocomplete", 14 "tokenization": "rightEdgeGram", 15 "minGrams": 3, 16 "maxGrams": 7, 17 "foldDiacritics": false 18 } 19 ] 20 } 21 } 22 }
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": [ 6 { 7 "type": "stringFacet" 8 }, 9 { 10 "type": "string" 11 }, 12 { 13 "type": "autocomplete", 14 "tokenization": "nGram", 15 "minGrams": 3, 16 "maxGrams": 7, 17 "foldDiacritics": false 18 } 19 ] 20 } 21 } 22 }
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
在 Search Tester 中查看和编辑查询语法:
在 AtlasClusters 中,转到项目的 页面。
如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。
此时会显示“集群”页面。
转到集群的 Atlas Search 页面。
您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。
在侧边栏中,单击Services标题下的Atlas Search 。
从Select data source下拉列表中,选择您的集群并单击Go to Atlas Search 。
显示Atlas Search页面。
单击集群的对应 Browse Collections 按钮。
展开数据库并选择集合。
单击集合的Search Indexes标签页。
显示Atlas Search页面。
单击集群名称。
单击 Atlas Search 标签页。
显示Atlas Search页面。
在mongosh
提示符下运行以下命令以使用sample_mflix
数据库:
use sample_mflix
基本示例
下面的查询会搜索 title
字段中包含字符 off
的电影。
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "off" } } } ]
查询包括:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class AutocompleteBasicExample { private const string MongoConnectionString = "<connection-string>"; public static void Main(string[] args) { // allow automapping of the camelCase database fields to our MovieDocument var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); // connect to your Atlas cluster var mongoClient = new MongoClient(MongoConnectionString); var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); // define and run pipeline var results = moviesCollection.Aggregate() .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "off")) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(10) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
查询包括:
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) // set namespace collection := client.Database("sample_mflix").Collection("movies") // define pipeline stages searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "off"}, {"path", "title"}}}}}} limitStage := bson.D{{"$limit", 10}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) if err != nil { panic(err) } // print results var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) } }
查询包括:
import static com.mongodb.client.model.Aggregates.limit; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AutocompleteBasicExample { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("$search", new Document("autocomplete", new Document("query", "off").append("path", "title"))); // run pipeline and print results collection.aggregate(Arrays.asList(agg, limit(10), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
查询包括:
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Projections.* import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { val uri = "<connection-string>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val agg = Document( "\$search", Document("autocomplete", Document("query", "off") .append("path", "title")) ) val resultsFlow = collection.aggregate<Document>( listOf( agg, limit(10), project(fields(excludeId(), include("title"))) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
查询包括:
const { MongoClient } = require("mongodb"); // connect to your Atlas cluster const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { await client.connect(); // set namespace const database = client.db("sample_mflix"); const coll = database.collection("movies"); // define pipeline const agg = [ {$search: {autocomplete: {query: "off", path: "title"}}}, {$limit: 10}, {$project: {_id: 0,title: 1}} ]; // run pipeline const result = await coll.aggregate(agg); // print results await result.forEach((doc) => console.log(doc)); } finally { await client.close(); } } run().catch(console.dir);
查询包括:
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"autocomplete": {"query": "off", "path": "title"}}}, {"$limit": 10}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
SCORE: 9.361787796020508 _id: "573a13b0f29313caabd355c8" countries: Array genres: Array runtime: 100 ... title: "Off Beat" SCORE: 9.068204879760742 _id: "573a13aaf29313caabd22a8c" fullplot: "An 11-year-old girl watches her father come down with a crippling depr…" imdb: Object year: 2003 ... title: "Off the Map" SCORE: 9.068204879760742 _id: "573a13bef29313caabd5d208" plot: "With white Jewish lesbians for parents and two adopted brothers - one …" genres: Array runtime: 76 ... title: "Off and Running" SCORE: 8.742463111877441 _id: "573a13bbf29313caabd5567" countries: Array genres: Array runtime: 98 ... title: "Hands off Mississippi" SCORE: 8.61273193359375 _id: "5573a1396f29313caabce4791" plot: "Unable to deal with her parents, Jeannie Tyne runs away from home. Lar…" genres: Array runtime: 93 ... title: "Taking Off" SCORE: 8.61273193359375 _id: "573a1399f29313caabced3c1" plot: "A travelling theater group find so much action going on behind-the-sce…" genres: Array runtime: 101 ... title: "Noises Off..." SCORE: 8.61273193359375 _id: "573a139af29313caabcefc73" fullplot: "In existence for a hundred years, Grimley Colliery Brass band is as ol…" imdb: Object year: 1996 ... title: "Brassed Off" SCORE: 8.61273193359375 _id: "573a139af29313caabcf08f5" fullplot: "Sean Archer, a very tough, rugged FBI Agent. Who is still grieving for…" imdb: Object year: 1997 ... title: "Face/Off" SCORE: 8.603004455566406 _id: "573a13a9f29313caabd1ea36" fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…" imdb: Object year: 2004 ... title: "Benji: Off the Leash!" SCORE: 7.953945159912109 _id: "573a139af29313caabcf037c" plot: "Desperation drives four inner-city women (Queen Latifah, Jada Pinkett …" genres: Array runtime: 123 ... title: "Set it Off"
SCORE: 9.81808090209961 _id: "5573a1396f29313caabce4791" plot: "Unable to deal with her parents, Jeannie Tyne runs away from home. Lar…" genres: Array runtime: 93 ... title: "Taking Off" SCORE: 9.81808090209961 _id: "573a1399f29313caabced3c1" plot: "A travelling theater group find so much action going on behind-the-sce…" genres: Array runtime: 101 ... title: "Noises Off..." SCORE: 9.81808090209961 _id: "573a139af29313caabcefc73" fullplot: "In existence for a hundred years, Grimley Colliery Brass band is as ol…" imdb: Object year: 1996 ... title: "Brassed Off" SCORE: 9.81808090209961 _id: "573a139af29313caabcf08f5" fullplot: "Sean Archer, a very tough, rugged FBI Agent. Who is still grieving for…" imdb: Object year: 1997 ... title: "Face/Off" SCORE: 9.544584274291992 _id: "573a139af29313caabcf037c" plot: "Desperation drives four inner-city women (Queen Latifah, Jada Pinkett …" genres: Array runtime: 123 ... title: "Set it Off" SCORE: 9.191947937011719 _id: "573a13bbf29313caabd5567" countries: Array genres: Array runtime: 98 ... title: "Hands off Mississippi" SCORE: 9.074413299560547 _id: "573a1398f29313caabce9f28" plot: "A high school wise guy is determined to have a day off from school, de…" genres: Array runtime: 103 ... title: "Ferris Bueller's Day Off" SCORE: 9.007184982299805 _id: "573a13b0f29313caabd355c8" countries: Array genres: Array runtime: 100 ... title: "Off Beat" SCORE: 8.700296401977539 _id: "573a13a9f29313caabd1ea36" fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…" imdb: Object year: 2004 ... title: "Benji: Off the Leash!" SCORE: 8.33833122253418 _id: "573a13aaf29313caabd22a8c" fullplot: "An 11-year-old girl watches her father come down with a crippling depr…" imdb: Object year: 2003 ... title: "Off the Map"
SCORE: 5.802560806274414 _id: “573a1396f29313caabce47f4” countries: Array genres: Array runtime: 98 ... title: "Come Have Coffee with Us" SCORE: 5.790548801422119 _id: "573a13d1f29313caabd90811" plot: "From pagan re-enactors to failed communes, black metal festivals to Ar…" genres: Array runtime: 98 ... title: "A Spell to Ward Off the Darkness" SCORE: 5.7726240158081055 _id: "573a13f3f29313caabddeb07" plot: "Turkey in the 1960s and 70s was one of the biggest producers of film i…" genres: Array runtime: 96 ... title: "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema" SCORE: 5.749281883239746 _id: "573a13a9f29313caabd1ea36" fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…" imdb: Object year: 2004 ... title: "Benji: Off the Leash!" SCORE: 5.749281883239746 _id: "573a13d4f29313caabd98488" fullplot: "This tragicomedy is a self-ironic portrait of a young man who drops ou…" imdb: Object year: 2012 ... title: "A Coffee in Berlin" SCORE: 5.74220085144043 _id: “573a1397f29313caabce863f” fullplot: "Zack Mayo is a young man who has signed up for Navy Aviation Officer C…" imdb: Object year: 1982 ... title: "An Officer and a Gentleman" SCORE: 5.671174049377441 _id: “573a1398f29313caabce987c” plot: "After the end of the Dirty War, a high school teacher sets out to find…" genres: Array runtime: 112 ... title: "The Official Story" SCORE: 5.671174049377441 _id: “573a13a5f29313caabd14c36” plot: "The first days of WWI. Adrien, a young and handsome lieutenant, is wou…" genres: Array runtime: 135 ... title: "The Officer's Ward" SCORE: 5.671174049377441 _id: "573a13bbf29313caabd5567" countries: Array genres: Array runtime: 98 ... title: "Hands off Mississippi" SCORE: 5.534632682800293 _id: "573a1395f29313caabce18c9" plot: "In this "Romeo and Juliet" inspired Cold War satire starring, written …" genres: Array runtime: 103 ... title: "Romanoff and Juliet"
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
1 { title: 'Off Beat' }, 2 { title: 'Off the Map' }, 3 { title: 'Off and Running' }, 4 { title: 'Hands off Mississippi' }, 5 { title: 'Taking Off' }, 6 { title: 'Noises Off...' }, 7 { title: 'Brassed Off' }, 8 { title: 'Face/Off' }, 9 { title: 'Benji: Off the Leash!' }, 10 { title: 'Set It Off' }
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 { title: 'Taking Off' } 2 { title: 'Noises Off...' } 3 { title: 'Brassed Off' } 4 { title: 'Face/Off' } 5 { title: 'Set It Off' } 6 { title: 'Hands off Mississippi' } 7 { title: "Ferris Bueller's Day Off" } 8 { title: 'Off Beat' } 9 { title: 'Benji: Off the Leash!' } 10 { title: 'Off the Map' }
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 { title: 'Come Have Coffee with Us' }, 2 { title: 'A Spell to Ward Off the Darkness' }, 3 { title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' }, 4 { title: 'Benji: Off the Leash!' }, 5 { title: 'A Coffee in Berlin' }, 6 { title: 'An Officer and a Gentleman' }, 7 { title: 'The Official Story' }, 8 { title: "The Officer's Ward" }, 9 { title: 'Hands off Mississippi' }, 10 { title: 'Romanoff and Juliet' }
在上述结果中,字符 off
出现在标题中的不同位置。
1 { title: 'Off Beat' }, 2 { title: 'Off the Map' }, 3 { title: 'Off and Running' }, 4 { title: 'Hands off Mississippi' }, 5 { title: 'Taking Off' }, 6 { title: 'Noises Off...' }, 7 { title: 'Brassed Off' }, 8 { title: 'Face/Off' }, 9 { title: 'Benji: Off the Leash!' }, 10 { title: 'Set It Off' }
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 { title: 'Taking Off' } 2 { title: 'Noises Off...' } 3 { title: 'Brassed Off' } 4 { title: 'Face/Off' } 5 { title: 'Set It Off' } 6 { title: 'Hands off Mississippi' } 7 { title: "Ferris Bueller's Day Off" } 8 { title: 'Off Beat' } 9 { title: 'Benji: Off the Leash!' } 10 { title: 'Off the Map' }
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 { title: 'Come Have Coffee with Us' }, 2 { title: 'A Spell to Ward Off the Darkness' }, 3 { title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' }, 4 { title: 'Benji: Off the Leash!' }, 5 { title: 'A Coffee in Berlin' }, 6 { title: 'An Officer and a Gentleman' }, 7 { title: 'The Official Story' }, 8 { title: "The Officer's Ward" }, 9 { title: 'Hands off Mississippi' }, 10 { title: 'Romanoff and Juliet' }
在上述结果中,字符 off
出现在标题中的不同位置。
1 { "title": "Off Beat" } 2 { "title": "Off the Map" } 3 { "title": "Off and Running" } 4 { "title": "Hands off Mississippi" } 5 { "title": "Taking Off" } 6 { "title": "Noises Off..." } 7 { "title": "Brassed Off" } 8 { "title": "Face/Off" } 9 { "title": "Benji: Off the Leash!" } 10 { "title": "Set It Off" }
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 { "title" : "Taking Off" } 2 { "title" : "Noises Off..." } 3 { "title" : "Brassed Off" } 4 { "title" : "Face/Off" } 5 { "title" : "Set It Off" } 6 { "title" : "Hands off Mississippi" } 7 { "title" : "Ferris Bueller's Day Off" } 8 { "title" : "Off Beat" } 9 { "title" : "Benji: Off the Leash!" } 10 { "title" : "Off the Map" }
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 { "title" : "Come Have Coffee with Us" } 2 { "title" : "A Spell to Ward Off the Darkness" } 3 { "title" : "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema" } 4 { "title" : "Benji: Off the Leash!" } 5 { "title" : "A Coffee in Berlin" } 6 { "title" : "An Officer and a Gentleman" } 7 { "title" : "The Official Story" } 8 { "title" : "The Officer's Ward" } 9 { "title" : "Hands off Mississippi" } 10 { "title" : "Romanoff and Juliet" }
在上述结果中,字符 off
出现在标题中的不同位置。
1 [{title Off Beat}] 2 [{title Off the Map}] 3 [{title Off and Running}] 4 [{title Hands off Mississippi}] 5 [{title Taking Off}] 6 [{title Noises Off...}] 7 [{title Brassed Off}] 8 [{title Face/Off}] 9 [{title Benji: Off the Leash!}] 10 [{title Set It Off}]
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 [{title Taking Off}] 2 [{title Noises Off...}] 3 [{title Brassed Off}] 4 [{title Face/Off}] 5 [{title Set It Off}] 6 [{title Hands off Mississippi}] 7 [{title Ferris Bueller's Day Off}] 8 [{title Off Beat}] 9 [{title Benji: Off the Leash!}] 10 [{title Off the Map}]
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 [{title Come Have Coffee with Us}] 2 [{title A Spell to Ward Off the Darkness}] 3 [{title Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema}] 4 [{title Benji: Off the Leash!}] 5 [{title A Coffee in Berlin}] 6 [{title An Officer and a Gentleman}] 7 [{title The Official Story}] 8 [{title The Officer's Ward}] 9 [{title Hands off Mississippi}] 10 [{title Romanoff and Juliet}]
在上述结果中,字符 off
出现在标题中的不同位置。
1 {"title": "Off Beat"} 2 {"title": "Off the Map"} 3 {"title": "Off and Running"} 4 {"title": "Hands off Mississippi"} 5 {"title": "Taking Off"} 6 {"title": "Noises Off..."} 7 {"title": "Brassed Off"} 8 {"title": "Face/Off"} 9 {"title": "Benji: Off the Leash!"} 10 {"title": "Set It Off"}
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 {"title": "Taking Off"} 2 {"title": "Noises Off..."} 3 {"title": "Brassed Off"} 4 {"title": "Face/Off"} 5 {"title": "Set It Off"} 6 {"title": "Hands off Mississippi"} 7 {"title": "Ferris Bueller's Day Off"} 8 {"title": "Off Beat"} 9 {"title": "Benji: Off the Leash!"} 10 {"title": "Off the Map"}
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 {"title": "Come Have Coffee with Us"} 2 {"title": "A Spell to Ward Off the Darkness"} 3 {"title": "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema"} 4 {"title": "Benji: Off the Leash!"} 5 {"title": "A Coffee in Berlin"} 6 {"title": "An Officer and a Gentleman"} 7 {"title": "The Official Story"} 8 {"title": "The Officer's Ward"} 9 {"title": "Hands off Mississippi"} 10 {"title": "Romanoff and Juliet"}
在上述结果中,字符 off
出现在标题中的不同位置。
1 Document{{title=Off Beat}} 2 Document{{title=Off the Map}} 3 Document{{title=Off and Running}} 4 Document{{title=Hands off Mississippi}} 5 Document{{title=Taking Off}} 6 Document{{title=Face/Off}} 7 Document{{title=Noises Off...}} 8 Document{{title=Brassed Off}} 9 Document{{title=Benji: Off the Leash!}} 10 Document{{title=Set It Off}}
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 Document{{title=Noises Off...}} 2 Document{{title=Taking Off}} 3 Document{{title=Brassed Off}} 4 Document{{title=Face/Off}} 5 Document{{title=Set It Off}} 6 Document{{title=Hands off Mississippi}} 7 Document{{title=Ferris Bueller's Day Off}} 8 Document{{title=Off Beat}} 9 Document{{title=Benji: Off the Leash!}} 10 Document{{title=Off and Running}}
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 Document{{title=Taking Off}} 2 Document{{title=Noises Off...}} 3 Document{{title=Brassed Off}} 4 Document{{title=Face/Off}} 5 Document{{title=Off Beat}} 6 Document{{title=Hands off Mississippi}} 7 Document{{title=Off the Map}} 8 Document{{title=Set It Off}} 9 Document{{title=Off and Running}} 10 Document{{title=Benji: Off the Leash!}}
在上述结果中,字符 off
出现在标题中的不同位置。
1 { title: 'Off Beat' } 2 { title: 'Off the Map' } 3 { title: 'Off and Running' } 4 { title: 'Hands off Mississippi' } 5 { title: 'Taking Off' } 6 { title: 'Noises Off...' } 7 { title: 'Brassed Off' } 8 { title: 'Face/Off' } 9 { title: 'Benji: Off the Leash!' } 10 { title: 'Set It Off' }
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 { title: 'Taking Off' } 2 { title: 'Noises Off...' } 3 { title: 'Brassed Off' } 4 { title: 'Face/Off' } 5 { title: 'Set It Off' } 6 { title: 'Hands off Mississippi' } 7 { title: "Ferris Bueller's Day Off" } 8 { title: 'Off Beat' } 9 { title: 'Benji: Off the Leash!' } 10 { title: 'Off the Map' }
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 { title: 'Come Have Coffee with Us' } 2 { title: 'A Spell to Ward Off the Darkness' } 3 { title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' } 4 { title: 'Benji: Off the Leash!' } 5 { title: 'A Coffee in Berlin' } 6 { title: 'An Officer and a Gentleman' } 7 { title: 'The Official Story' } 8 { title: "The Officer's Ward" } 9 { title: 'Hands off Mississippi' } 10 { title: 'Romanoff and Juliet' }
在上述结果中,字符 off
出现在标题中的不同位置。
1 {'title': 'Off Beat'} 2 {'title': 'Off the Map'} 3 {'title': 'Off and Running'} 4 {'title': 'Hands off Mississippi'} 5 {'title': 'Taking Off'} 6 {'title': 'Noises Off...'} 7 {'title': 'Brassed Off'} 8 {'title': 'Face/Off'} 9 {'title': 'Benji: Off the Leash!'} 10 {'title': 'Set It Off'}
在上述结果中,字符 off
出现在所有标题中的某个单词的左侧。
1 {'title': 'Taking Off'} 2 {'title': 'Noises Off...'} 3 {'title': 'Brassed Off'} 4 {'title': 'Face/Off'} 5 {'title': 'Set It Off'} 6 {'title': 'Hands off Mississippi'} 7 {'title': "Ferris Bueller's Day Off"} 8 {'title': 'Off Beat'} 9 {'title': 'Benji: Off the Leash!'} 10 {'title': 'Off the Map'}
在上述结果中,字符 off
出现在所有标题中的某个单词的右侧。
1 {'title': 'Come Have Coffee with Us'} 2 {'title': 'A Spell to Ward Off the Darkness'} 3 {'title': 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema'} 4 {'title': 'Benji: Off the Leash!'} 5 {'title': 'A Coffee in Berlin'} 6 {'title': 'An Officer and a Gentleman'} 7 {'title': 'The Official Story'} 8 {'title': "The Officer's Ward"} 9 {'title': 'Hands off Mississippi'} 10 {'title': 'Romanoff and Juliet'}
在上述结果中,字符 off
出现在标题中的不同位置。
模糊示例
下面的查询会搜索 title
字段中包含字符 pre
的电影。查询使用:
字段 | 说明 |
maxEdits | 表示查询字符串 pre 中只允许有一个字符变体,以便将查询与文档中的单词匹配。 |
prefixLength | 表示将查询与文档中的单词进行匹配时,查询字符串 pre 中的第一个字符无法更改。 |
maxExpansions | 表示将查询字符串与文档中的单词进行匹配时,最多可以为 pre 考虑 256 个相似的术语。 |
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "pre", fuzzy: { maxEdits: 1, prefixLength: 1, maxExpansions: 256 } } } } ]
db.movies.aggregate([ { $search: { "autocomplete": { "path": "title", "query": "pre", "fuzzy": { "maxEdits": 1, "prefixLength": 1, "maxExpansions": 256 } } } }, { $limit: 10 }, { $project: { "_id": 0, "title": 1 } } ])
在 movies
集合的 Aggregations 标签页中,从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 添加其他阶段。
管道阶段 | 查询 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| |||||||||||
$limit |
| |||||||||||
$project |
|
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class AutocompleteFuzzyExample { private const string MongoConnectionString = "<connection-string>"; public static void Main(string[] args) { // allow automapping of the camelCase database fields to our MovieDocument var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); // connect to your Atlas cluster var mongoClient = new MongoClient(MongoConnectionString); var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); // define fuzzy options SearchFuzzyOptions fuzzyOptions = new SearchFuzzyOptions() { MaxEdits = 1, PrefixLength = 1, MaxExpansions = 256 }; // define and run pipeline var results = moviesCollection.Aggregate() .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "pre", fuzzy: fuzzyOptions)) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(10) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) // set namespace collection := client.Database("sample_mflix").Collection("movies") // define pipeline stages searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "pre"}, {"path", "title"}, {"fuzzy", bson.D{{"maxEdits", 1},{"prefixLength", 1},{"maxExpansions", 256}}}}}}}} limitStage := bson.D{{"$limit", 10}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) if err != nil { panic(err) } // print results var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) } }
import static com.mongodb.client.model.Aggregates.limit; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AutocompleteFuzzyExample { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("$search", new Document("autocomplete", new Document("query", "pre") .append("path", "title") .append("fuzzy", new Document("maxEdits", 1).append("prefixLength", 1).append("maxExpansions", 256)))); // run pipeline and print results collection.aggregate(Arrays.asList(agg, limit(10), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Projections.* import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { val uri = "<connection-string>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val agg = Document( "\$search", Document("autocomplete", Document("query", "pre") .append("path", "title") .append("fuzzy", Document("maxEdits", 1) .append("prefixLength", 1) .append("maxExpansions", 256)) ) ) val resultsFlow = collection.aggregate<Document>( listOf( agg, limit(10), project(fields(excludeId(), include("title"))) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
const { MongoClient } = require("mongodb"); // connect to your Atlas cluster const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { await client.connect(); // set namespace const database = client.db("sample_mflix"); const coll = database.collection("movies"); // define pipeline const agg = [ {$search: {autocomplete: {query: "pre", path: "title", fuzzy: {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}}, {$limit: 10}, {$project: {_id: 0,title: 1}} ]; // run pipeline const result = await coll.aggregate(agg); // print results await result.forEach((doc) => console.log(doc)); } finally { await client.close(); } } run().catch(console.dir);
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"autocomplete": {"query": "pre", "path": "title", "fuzzy": {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}}, {"$limit": 10}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
SCORE: 1 _id: “573a1390f29313caabcd5293” plot: "Young Pauline is left a lot of money when her wealthy uncle dies. Howe…" genres: Array runtime: 199 ... title: "The Perils of Pauline" SCORE: 1 _id: “573a1391f29313caabcd9458” plot: "A young artist draws a face at a canvas on his easel. Suddenly the mou…" genres: Array rated: "UNRATED" ... title: "The Blood of a Poet" SCORE: 1 _id: “573a1392f29313caabcda09b” plot: "Tells how King Henry VIII came to marry five more times after his divo…" genres: Array runtime: 97 ... title: "The Private Life of Henry VIII." SCORE: 1 _id: “573a1392f29313caabcda556” plot: "What do women want? Don Juan is aging. He's arrived secretly in Sevill…" genres: Array runtime: 89 ... title: "The Private Life of Don Juan" SCORE: 1 _id: “573a1392f29313caabcdaee0” plot: "The story of Dr. Samuel Mudd, who was imprisoned after innocently trea…" genres: Array runtime: 96 ... title: "The Prisoner of Shark Island" SCORE: 1 _id: “573a1392f29313caabcdb3f2” plot: "Two lookalike boys, one a poor street kid and the other a prince, exch…" genres: Array runtime: 118 ... title: "The Prince and the Pauper" SCORE: 1 _id: “573a1392f29313caabcdb3f4” plot: "An Englishman on a Ruritarian holiday must impersonate the king when t…" genres: Array runtime: 101 ... title: "The Prisoner of Zenda" SCORE: 1 _id: “573a1392f29313caabcdb505” plot: "After the death of her husband, Christine realizes she has possibly wa…" genres: Array runtime: 144 ... title: "Dance Program" SCORE: 1 _id: “573a1393f29313caabcdca58” plot: "While traveling in France during the Nazi invasion of 1940, an English…" genres: Array runtime: 87 ... title: "The Pied Piper" SCORE: 1 _id: “573a1393f29313caabcdca76” plot: "The official World War II US Government film statement defining the va…" genres: Array runtime: 87 ... title: "Prelude to War"
SCORE: 1 _id: “573a1390f29313caabcd5ea4” plot: "A District Attorney's outspoken stand on abortion gets him in trouble …" genres: Array runtime: 62 ... title: "Where Are My Children?" SCORE: 1 _id: “573a1391f29313caabcd70b4” plot: "An extended family split up in France and Germany find themselves on o…" genres: Array runtime: 150 ... title: "The Four Horsemen of the Apocalypse" SCORE: 1 _id: “573a1391f29313caabcd7850” plot: "In fifteenth century Paris, the brother of the archdeacon plots with t…" genres: Array runtime: 133 ... title: "The Hunchback of Notre Dame" SCORE: 1 _id: “573a1391f29313caabcd8cbd” plot: "A young lady from Georgia goes to Hollywood in the hopes of becoming a…" genres: Array runtime: 83 ... title: "Show People" SCORE: 1 _id: “573a1392f29313caabcd9df7” plot: "A young American man is transported back to London in the time of the …" genres: Array runtime: 84 ... title: "Berkeley Square" SCORE: 1 _id: “573a1392f29313caabcda7fb” plot: "An entertainer impersonates a look-alike banker, causing comic confusi…" genres: Array runtime: 82 ... title: "Folies Bergère de Paris" SCORE: 1 _id: “573a1393f29313caabcdc4a2” plot: "Boxer Joe Pendleton dies 50 years too soon due to a heavenly mistake, …" genres: Array runtime: 94 ... title: "Here Comes Mr. Jordan" SCORE: 1 _id: “573a1393f29313caabcdc814” plot: "An American man marries a Serbian immigrant who fears that she will tu…" genres: Array runtime: 73 ... title: "Cat People" SCORE: 1 _id: “573a1393f29313caabcdc87b” plot: "Mail author for translation. Kodos hegycsucsok, fekete fenyvesek vilag…" genres: Array runtime: 88 ... title: "People on the Alps" SCORE: 1 _id: “573a1393f29313caabcdcd39” plot: "A soldier falls for a chorus girl and then experiences trouble when he…" genres: Array runtime: 103 ... title: "The Gang's All Here"
SCORE: 1 _id: “573a1390f29313caabcd5293” plot: "Young Pauline is left a lot of money when her wealthy uncle dies. Howe…" genres: Array runtime: 199 ... title: "The Perils of Pauline" SCORE: 1 _id: “573a1390f29313caabcd5967” plot: "An intrepid reporter and his loyal friend battle a bizarre secret soci…" genres: Array runtime: 399 ... title: "Les vampires" SCORE: 1 _id: “573a1391f29313caabcd6ea2” plot: "The simple-minded son of a rich financier must find his own way in the…" genres: Array runtime: 77 ... title: "The Saphead" SCORE: 1 _id: “573a1391f29313caabcd70b4” plot: "An extended family split up in France and Germany find themselves on o…" genres: Array runtime: 150 ... title: "The Four Horsemen of the Apocalypse" SCORE: 1 _id: “573a1391f29313caabcd7b98” plot: "A bitter clown endeavors to rescue the young woman he loves from the l…" genres: Array runtime: 95 ... title: "He Who Gets Slapped" SCORE: 1 _id: “573a1391f29313caabcd806b” plot: "A mad, disfigured composer seeks love with a lovely young opera singer…" genres: Array runtime: 93 ... title: "The Phantom of the Opera" SCORE: 1 _id: “573a1391f29313caabcd8cbd” plot: "A young lady from Georgia goes to Hollywood in the hopes of becoming a…" genres: Array runtime: 83 ... title: "Show People" SCORE: 1 _id: “573a1391f29313caabcd9458” plot: "A young artist draws a face at a canvas on his easel. Suddenly the mou…" genres: Array rated: "UNRATED" ... title: "The Blood of a Poet" SCORE: 1 _id: “573a1391f29313caabcd9651” plot: "In London at the turn of the century, the bandit Mack the Knife marrie…" genres: Array runtime: 112 ... title: "The 3 Penny Opera" SCORE: 1 _id: “573a1392f29313caabcd9caa” plot: "Many passengers on the Shanghai Express are more concerned that the no…" genres: Array runtime: 82 ... title: "Shanghai Express"
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
1 { title: 'The Perils of Pauline' }, 2 { title: 'The Blood of a Poet' }, 3 { title: 'The Private Life of Henry VIII.' }, 4 { title: 'The Private Life of Don Juan' }, 5 { title: 'The Prisoner of Shark Island' }, 6 { title: 'The Prince and the Pauper' }, 7 { title: 'The Prisoner of Zenda' }, 8 { title: 'Dance Program' }, 9 { title: 'The Pied Piper' }, 10 { title: 'Prelude to War' }
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 { title: 'Where Are My Children?' } 2 { title: 'The Four Horsemen of the Apocalypse' } 3 { title: 'The Hunchback of Notre Dame' } 4 { title: 'Show People' } 5 { title: 'Berkeley Square' } 6 { title: 'Folies Bergère de Paris' } 7 { title: 'Here Comes Mr. Jordan' } 8 { title: 'Cat People' } 9 { title: 'People on the Alps' } 10 { title: "The Gang's All Here" }
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 { title: 'The Perils of Pauline' } 2 { title: 'Les vampires' } 3 { title: 'The Saphead' } 4 { title: 'The Four Horsemen of the Apocalypse' } 5 { title: 'He Who Gets Slapped' } 6 { title: 'The Phantom of the Opera' } 7 { title: 'Show People' } 8 { title: 'The Blood of a Poet' } 9 { title: 'The 3 Penny Opera' } 10 { title: 'Shanghai Express' }
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 { title: 'The Perils of Pauline' }, 2 { title: 'The Blood of a Poet' }, 3 { title: 'The Private Life of Henry VIII.' }, 4 { title: 'The Private Life of Don Juan' }, 5 { title: 'The Prisoner of Shark Island' }, 6 { title: 'The Prince and the Pauper' }, 7 { title: 'The Prisoner of Zenda' }, 8 { title: 'Dance Program' }, 9 { title: 'The Pied Piper' }, 10 { title: 'Prelude to War' }
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 { title: 'Where Are My Children?' } 2 { title: 'The Four Horsemen of the Apocalypse' } 3 { title: 'The Hunchback of Notre Dame' } 4 { title: 'Show People' } 5 { title: 'Berkeley Square' } 6 { title: 'Folies Bergère de Paris' } 7 { title: 'Here Comes Mr. Jordan' } 8 { title: 'Cat People' } 9 { title: 'People on the Alps' } 10 { title: "The Gang's All Here" }
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 { title: 'The Perils of Pauline' } 2 { title: 'Les vampires' } 3 { title: 'The Saphead' } 4 { title: 'The Four Horsemen of the Apocalypse' } 5 { title: 'He Who Gets Slapped' } 6 { title: 'The Phantom of the Opera' } 7 { title: 'Show People' } 8 { title: 'The Blood of a Poet' } 9 { title: 'The 3 Penny Opera' } 10 { title: 'Shanghai Express' }
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 { "title" : "The Perils of Pauline" } 2 { "title" : "The Blood of a Poet" } 3 { "title" : "The Private Life of Henry VIII." } 4 { "title" : "The Private Life of Don Juan" } 5 { "title" : "The Prisoner of Shark Island" } 6 { "title" : "The Prince and the Pauper" } 7 { "title" : "The Prisoner of Zenda" } 8 { "title" : "Dance Program" } 9 { "title" : "The Pied Piper" } 10 { "title" : "Prelude to War" }
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 { "title" : "Where Are My Children?" } 2 { "title" : "The Four Horsemen of the Apocalypse" } 3 { "title" : "The Hunchback of Notre Dame" } 4 { "title" : "Show People" } 5 { "title" : "Berkeley Square" } 6 { "title" : "Folies Bergère de Paris" } 7 { "title" : "Here Comes Mr. Jordan" } 8 { "title" : "Cat People" } 9 { "title" : "People on the Alps" } 10 { "title" : "The Gang's All Here" }
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 { "title" : "The Perils of Pauline" } 2 { "title" : "Les vampires" } 3 { "title" : "The Saphead" } 4 { "title" : "The Four Horsemen of the Apocalypse" } 5 { "title" : "He Who Gets Slapped" } 6 { "title" : "The Phantom of the Opera" } 7 { "title" : "Show People" } 8 { "title" : "The Blood of a Poet" } 9 { "title" : "The 3 Penny Opera" } 10 { "title" : "Shanghai Express" }
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 [{title The Perils of Pauline}] 2 [{title The Blood of a Poet}] 3 [{title The Private Life of Henry VIII.}] 4 [{title The Private Life of Don Juan}] 5 [{title The Prisoner of Shark Island}] 6 [{title The Prince and the Pauper}] 7 [{title The Prisoner of Zenda}] 8 [{title Dance Program}] 9 [{title The Pied Piper}] 10 [{title Prelude to War}]
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 [{title Where Are My Children?}] 2 [{title The Four Horsemen of the Apocalypse}] 3 [{title The Hunchback of Notre Dame}] 4 [{title Show People}] 5 [{title Berkeley Square}] 6 [{title Folies Bergère de Paris}] 7 [{title Here Comes Mr. Jordan}] 8 [{title Cat People}] 9 [{title People on the Alps}] 10 [{title The Gang's All Here}]
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 [{title The Perils of Pauline}] 2 [{title Les vampires}] 3 [{title The Saphead}] 4 [{title The Four Horsemen of the Apocalypse}] 5 [{title He Who Gets Slapped}] 6 [{title The Phantom of the Opera}] 7 [{title Show People}] 8 [{title The Blood of a Poet}] 9 [{title The 3 Penny Opera}] 10 [{title Shanghai Express}]
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 {"title": "The Perils of Pauline"} 2 {"title": "The Blood of a Poet"} 3 {"title": "The Private Life of Henry VIII."} 4 {"title": "The Private Life of Don Juan"} 5 {"title": "The Prisoner of Shark Island"} 6 {"title": "The Prince and the Pauper"} 7 {"title": "The Prisoner of Zenda"} 8 {"title": "Dance Program"} 9 {"title": "The Pied Piper"} 10 {'title': 'Prelude to War'}
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 {"title": "Where Are My Children?"} 2 {"title": "The Four Horsemen of the Apocalypse"} 3 {"title": "The Hunchback of Notre Dame"} 4 {"title": "Show People"} 5 {"title": "Berkeley Square"} 6 {"title": "Folies Bergère de Paris"} 7 {"title": "Here Comes Mr. Jordan"} 8 {"title": "Cat People"} 9 {"title": "People on the Alps"} 10 {"title": "The Gang's All Here"}
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 {"title": "The Perils of Pauline"} 2 {"title": "Les vampires"} 3 {"title": "The Saphead"} 4 {"title": "The Four Horsemen of the Apocalypse"} 5 {"title": "He Who Gets Slapped"} 6 {"title": "The Phantom of the Opera"} 7 {"title": "Show People"} 8 {"title": "The Blood of a Poet"} 9 {"title": "The 3 Penny Opera"} 10 {"title": "Shanghai Express"}
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 Document{{title=The Perils of Pauline}} 2 Document{{title=The Private Life of Henry VIII.}} 3 Document{{title=Prelude to War}} 4 Document{{title=Sitting Pretty}} 5 Document{{title=The Prisoner}} 6 Document{{title=Chi lavora è perduto (In capo al mondo)}} 7 Document{{title=Profound Desires of the Gods}} 8 Document{{title=The Protagonists}} 9 Document{{title=Property Is No Longer a Theft}} 10 Document{{title=Premiya}}
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 Document{{title=The Four Horsemen of the Apocalypse}} 2 Document{{title=Folies Bergère de Paris}} 3 Document{{title=Mother Wore Tights}} 4 Document{{title=El hombre sin rostro}} 5 Document{{title=Il segno di Venere}} 6 Document{{title=Creature from the Black Lagoon}} 7 Document{{title=Susan Slept Here}} 8 Document{{title=Tell Them Willie Boy Is Here}} 9 Document{{title=Pilatus und andere - Ein Film fèr Karfreitag}} 10 Document{{title=Watch Out, We're Mad}}
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 Document{{title=The Four Horsemen of the Apocalypse}} 2 Document{{title=The Private Life of Henry VIII.}} 3 Document{{title=David Copperfield}} 4 Document{{title=The Prisoner of Zenda}} 5 Document{{title=People on the Alps}} 6 Document{{title=Prelude to War}} 7 Document{{title=The Pride of the Yankees}} 8 Document{{title=Phantom of the Opera}} 9 Document{{title=The Curse of the Cat People}} 10 Document{{title=The People Against O'Hara}}
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 { title: 'The Perils of Pauline' } 2 { title: 'The Blood of a Poet' } 3 { title: 'The Private Life of Henry VIII.' } 4 { title: 'The Private Life of Don Juan' } 5 { title: 'The Prisoner of Shark Island' } 6 { title: 'The Prince and the Pauper' } 7 { title: 'The Prisoner of Zenda' } 8 { title: 'Dance Program' } 9 { title: 'The Pied Piper' } 10 { title: 'Prelude to War' }
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 { title: 'Where Are My Children?' } 2 { title: 'The Four Horsemen of the Apocalypse' } 3 { title: 'The Hunchback of Notre Dame' } 4 { title: 'Show People' } 5 { title: 'Berkeley Square' } 6 { title: 'Folies Bergère de Paris' } 7 { title: 'Here Comes Mr. Jordan' } 8 { title: 'Cat People' } 9 { title: 'People on the Alps' } 10 { title: "The Gang's All Here" }
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 { title: 'The Perils of Pauline' } 2 { title: 'Les vampires' } 3 { title: 'The Saphead' } 4 { title: 'The Four Horsemen of the Apocalypse' } 5 { title: 'He Who Gets Slapped' } 6 { title: 'The Phantom of the Opera' } 7 { title: 'Show People' } 8 { title: 'The Blood of a Poet' } 9 { title: 'The 3 Penny Opera' } 10 { title: 'Shanghai Express' }
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
1 {'title': 'The Perils of Pauline'} 2 {'title': 'The Blood of a Poet'} 3 {'title': 'The Private Life of Henry VIII.'} 4 {'title': 'The Private Life of Don Juan'} 5 {'title': 'The Prisoner of Shark Island'} 6 {'title': 'The Prince and the Pauper'} 7 {'title': 'The Prisoner of Zenda'} 8 {'title': 'Dance Program'} 9 {'title': 'The Pied Piper'} 10 {'title': 'Prelude to War'}
这些结果显示修改一个字符后查询字符串中预测的单词,所有标题中第一个字符常量位于单词左侧。
1 {'title': 'Where Are My Children?'} 2 {'title': 'The Four Horsemen of the Apocalypse'} 3 {'title': 'The Hunchback of Notre Dame'} 4 {'title': 'Show People'} 5 {'title': 'Berkeley Square'} 6 {'title': 'Folies Bergère de Paris'} 7 {'title': 'Here Comes Mr. Jordan'} 8 {'title': 'Cat People'} 9 {'title': 'People on the Alps'} 10 {'title': "The Gang's All Here"}
这些结果显示了在修改了一个字符且所有标题中第一个字符常量位于单词右侧的情况下为查询字符串预测的单词。
1 {'title': 'The Perils of Pauline'} 2 {'title': 'Les vampires'} 3 {'title': 'The Saphead'} 4 {'title': 'The Four Horsemen of the Apocalypse'} 5 {'title': 'He Who Gets Slapped'} 6 {'title': 'The Phantom of the Opera'} 7 {'title': 'Show People'} 8 {'title': 'The Blood of a Poet'} 9 {'title': 'The 3 Penny Opera'} 10 {'title': 'Shanghai Express'}
这些结果显示了针对字符串预测的单词,并在标题单词的不同位置修改了一个字符。
令牌顺序示例
以下查询搜索在 title
字段中包含字符 men
with
的电影。这些查询还使用 tokenOrder
字段,该字段指定查询是按 any
顺序还是按 sequential
顺序搜索令牌。
从示例开始
您可以使用关键字分析器将 title
字段编入索引,搜索以某个术语或短语开头的电影片名。
您必须使用关键字分析器和edgeGram
分词策略为字段编制索引,才能检索以下示例查询的结果。如果您使用任何其他内置分析器对该字段进行索引,Atlas Search 不会返回任何结果,因为它不会将您的文本字段作为单个术语进行索引。 edgeGram
分词策略从单词的左侧开始创建词元。
您还必须将foldDiacritics
设置为true
才能返回区分大小写的结果。如果将foldDiacritics
设置为false
,则查询词的字母大小写必须与文档中的字母大小写完全匹配,Atlas Search 才能返回任何结果。
{ "mappings": { "dynamic": false, "fields": { "title": [ { "type": "stringFacet" }, { "type": "string" }, { "foldDiacritics": true, "maxGrams": 7, "minGrams": 3, "analyzer": "lucene.keyword", "tokenization": "edgeGram", "type": "autocomplete" }] } } }
以下查询搜索以 Fast &
开头的电影标题。
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "Fast &", tokenOrder: "sequential" } } } ]
每个查询都包括:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class AutocompleteTokenOrderSequentialStartsWithExample { private const string MongoConnectionString = "<connection-string>"; public static void Main(string[] args) { // allow automapping of the camelCase database fields to our MovieDocument var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); // connect to your Atlas cluster var mongoClient = new MongoClient(MongoConnectionString); var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); // define and run pipeline var results = moviesCollection.Aggregate() .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "Fast &", SearchAutocompleteTokenOrder.Sequential)) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(4) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
每个查询都包括:
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) // set namespace collection := client.Database("sample_mflix").Collection("movies") // define pipeline stages searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "Fast &"}, {"path", "title"}, {"tokenOrder", "sequential"}}}}}} limitStage := bson.D{{"$limit", 4}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) if err != nil { panic(err) } // print results var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) } }
每个查询都包括:
import static com.mongodb.client.model.Aggregates.limit; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AutocompleteStartsWith { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("$search", new Document("autocomplete", new Document("query", "Fast &").append("path", "title").append("tokenOrder", "sequential"))); // run pipeline and print results collection.aggregate(Arrays.asList(agg, limit(4), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
每个查询都包括:
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Projections.* import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { val uri = "<connection-string>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val agg = Document( "\$search", Document( "autocomplete", Document("query", "Fast &") .append("path", "title") .append("tokenOrder", "sequential") ) ) val resultsFlow = collection.aggregate<Document>( listOf( agg, limit(4), project(fields(excludeId(), include("title"))) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
每个查询都包括:
const { MongoClient } = require("mongodb"); // connect to your Atlas cluster const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { await client.connect(); // set namespace const database = client.db("sample_mflix"); const coll = database.collection("movies"); // define pipeline const agg = [ {$search: {autocomplete: {query: "Fast &", path: "title", tokenOrder: "sequential"}}}, {$limit: 4}, {$project: {_id: 0,title: 1}} ]; // run pipeline const result = await coll.aggregate(agg); // print results await result.forEach((doc) => console.log(doc)); } finally { await client.close(); } } run().catch(console.dir);
每个查询都包括:
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "sequential"}}}, {"$limit": 4}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
SCORE: 10.042893409729004 _id: “573a13bdf29313caabd5929f” fullplot: "Heading back to the streets where it all began, two men rejoin two wom…" imdb: Object year: 2009 ... title: "Fast & Furious" SCORE: 9.515419006347656 _id: “573a13d3f29313caabd95cc5” fullplot: "Since Dom (Diesel) and Brian's (Walker) Rio heist toppled a kingpin's …" imdb: Object year: 2013 ... title "Fast & Furious 6"
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
1 { title: 'Fast & Furious' }, 2 { title: 'Fast & Furious 6' }
1 { title: 'Fast & Furious' }, 2 { title: 'Fast & Furious 6' }
1 { "title" : "Fast & Furious" } 2 { "title" : "Fast & Furious 6" }
1 [{title Fast & Furious}] 2 [{title Fast & Furious 6}]
1 {"title": "Fast & Furious"} 2 {"title": "Fast & Furious 6"}
1 Document{{title=Fast & Furious}} 2 Document{{title=Fast & Furious 6}}
1 { title: 'Fast & Furious' } 2 { title: 'Fast & Furious 6' }
1 {'title': 'Fast & Furious'} 2 {'title': 'Fast & Furious 6'}
简单的any
示例
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "men with", tokenOrder: "any" } } } ]
每个查询都包括:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class AutocompleteTokenOrderAnyExample { private const string MongoConnectionString = "<connection-string>"; public static void Main(string[] args) { // allow automapping of the camelCase database fields to our MovieDocument var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); // connect to your Atlas cluster var mongoClient = new MongoClient(MongoConnectionString); var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); // define and run pipeline var results = moviesCollection.Aggregate() .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "men with", SearchAutocompleteTokenOrder.Any)) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(4) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
每个查询都包括:
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) // set namespace collection := client.Database("sample_mflix").Collection("movies") // define pipeline stages searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "men with"}, {"path", "title"}, {"tokenOrder", "any"}}}}}} limitStage := bson.D{{"$limit", 4}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) if err != nil { panic(err) } // print results var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) } }
每个查询都包括:
import static com.mongodb.client.model.Aggregates.limit; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AutocompleteTokenAny { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("$search", new Document("autocomplete", new Document("query", "men with").append("path", "title").append("tokenOrder", "any"))); // run pipeline and print results collection.aggregate(Arrays.asList(agg, limit(4), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
每个查询都包括:
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Projections.* import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { val uri = "<connection-string>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val agg = Document( "\$search", Document("autocomplete", Document("query", "men with") .append("path", "title") .append("tokenOrder", "any")) ) val resultsFlow = collection.aggregate<Document>( listOf( agg, limit(4), project(fields(excludeId(), include("title"))) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
每个查询都包括:
const { MongoClient } = require("mongodb"); // connect to your Atlas cluster const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { await client.connect(); // set namespace const database = client.db("sample_mflix"); const coll = database.collection("movies"); // define pipeline const agg = [ {$search: {autocomplete: {query: "men with", path: "title", tokenOrder: "any"}}}, {$limit: 4}, {$project: {_id: 0,title: 1}} ]; // run pipeline const result = await coll.aggregate(agg); // print results await result.forEach((doc) => console.log(doc)); } finally { await client.close(); } } run().catch(console.dir);
每个查询都包括:
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "any"}}}, {"$limit": 4}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
SCORE: 21.18158721923828 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 21.18158721923828 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 19.015962600708008 _id: “573a1391f29313caabcd93a3” plot: "Navy divers clear the torpedo tube of a sunken submarine." genres: Array runtime: 77 ... title: "Men Without Women" SCORE: 11.215812683105469 _id: “573a13b8f29313caabd4bcbf” plot: "A graduate student (Nicholson) copes with a recent breakup by conducti…" genres: Array runtime: 80 ... title: "Brief Interviews with Hideous Men" SCORE: 10.668076515197754 _id: “573a13c9f29313caabd7ba99” plot: "The women of a remote Latin American town are forced to pick up the pi…"" genres: Array runtime: 87 ... title: "Without Men" SCORE: 10.106664657592773 _id: “573a13c8f29313caabd77ab6” plot: "Against the tumultuous backdrop of Iran's 1953 CIA-backed coup d'ètat,…" genres: Array runtime: 95 ... title: "Women Without Men" SCORE: 7.458737373352051 _id: “573a1398f29313caabce9a19” plot: "A man's wife leaves him to take up with an artist, so the man responds…" genres: Array runtime: 99 ... title: "Men..." SCORE: 7.405402183532715 _id: “573a13f2f29313caabdde0b4” plot: "Men and Chicken is a black comedy about two outcast brothers, who by g…" genres: Array runtime: 104 ... title: "Men & Chicken" SCORE: 7.2005205154418945 _id: “573a1394f29313caabce06c3” plot: "During the Korean War, a battle worn Lt. and his platoon behind enemy …" genres: Array runtime: 102 ... title: "Men in War" SCORE: 7.2005205154418945 _id: “573a1399f29313caabcec167” plot: "A mother of two sons finds life considerably difficult on her own afte…" genres: Array runtime: 115 ... title: "Men Don't Leave"
SCORE: 19.302995681762695 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 19.302995681762695 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 13.835155487060547 _id: “573a1399f29313caabcee64e” plot: "A thief's son cons his father into spending more time with him." genres: Array runtime: 109 ... title: "Getting Even with Dad" SCORE: 13.309324264526367 _id: “573a13cdf29313caabd844f5” plot: "Since his beloved violin was broken, Nasser Ali Khan, one of the most …" genres: Array runtime: 93 ... title: "Chicken with Plums" SCORE: 12.078420639038086 _id: “573a13b8f29313caabd4bcbf” plot: "A graduate student (Nicholson) copes with a recent breakup by conducti…" genres: Array runtime: 80 ... title: "Brief Interviews with Hideous Men" SCORE: 10.180097579956055 _id: “573a13b2f29313caabd3ab9b” fullplot: "A man runs into a woman at a wedding. They start to flirt and talk and…" imdb: Object year: 2005 ... title: "Conversations with Other Women" SCORE: 7.147367477416992 _id: “573a1398f29313caabce9a19” plot: "A man's wife leaves him to take up with an artist, so the man responds…" genres: Array runtime: 99 ... title: "Men..." SCORE: 7.054648399353027 _id: “573a1394f29313caabcde7cc” plot: "Paralized war vet tries to adjust to the world without the use of his …" genres: Array runtime: 85 ... title: "The Men" SCORE: 7.054648399353027 _id: “573a1399f29313caabced53c” plot: "Bitter about being double-crossed by the women he loved, (and with the…" genres: Array runtime: 105 ... title: "Simple Men" SCORE: 7.054648399353027 _id: “573a139af29313caabcf0f51” fullplot: "In a world where both Mutants and Humans fear each other, Marie, bette…" imdb: Object year: 2000 ... title: "X-Men"
SCORE: 16.18875503540039 _id: “573a1391f29313caabcd93a3” plot: "Navy divers clear the torpedo tube of a sunken submarine." genres: Array runtime: 77 ... title: "Men Without Women" SCORE: 15.995916366577148 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 15.995916366577148 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 15.642412185668945 _id: “573a13c8f29313caabd77ab6” plot: "Against the tumultuous backdrop of Iran's 1953 CIA-backed coup d'ètat,…" genres: Array runtime: 95 ... title: "Women Without Men" SCORE: 8.15120792388916 _id: “573a13b8f29313caabd4bcbf” plot: "A graduate student (Nicholson) copes with a recent breakup by conducti…" genres: Array runtime: 80 ... title: "Brief Interviews with Hideous Men" SCORE: 8.118724822998047 _id: “573a13b2f29313caabd3ab9b” fullplot: "A man runs into a woman at a wedding. They start to flirt and talk and…" imdb: Object year: 2005 ... title: "Conversations with Other Women" SCORE: 8.048237800598145 _id: “573a13a5f29313caabd138ca” plot: "This documentary, first shown on the Turner Classic Movies cable chann…" genres: Array runtime: 56 ... title: "Without Lying Down: Frances Marion and the Power of Women in Hollywood" SCORE: 7.620831489562988 _id: “573a13c9f29313caabd7ba99” plot: "The women of a remote Latin American town are forced to pick up the pi…"" genres: Array runtime: 87 ... title: "Without Men" SCORE: 4.35431432723999 _id: “573a1393f29313caabcdcd9d” plot: "A young Canadian nurse (Betsy) comes to the West Indies to care for Je…" genres: Array runtime: 69 ... title: "I Walked with a Zombie" SCORE: 4.35431432723999 _id: “573a1393f29313caabcdd9c7” plot: "Political intrigue and psychological drama run parallel. The queen is …" genres: Array runtime: 93 ... title: "The Eagle with Two Heads"
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Men Without Women' } 4 { title: 'Brief Interviews with Hideous Men' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' } 2 { title: 'Men with Guns' } 3 { title: 'Men with Brooms' } 4 { title: 'Women Without Men' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Men Without Women' } 4 { title: 'Brief Interviews with Hideous Men' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' } 2 { title: 'Men with Guns' } 3 { title: 'Men with Brooms' } 4 { title: 'Women Without Men' }
1 { "title" : "Men with Guns" } 2 { "title" : "Men with Brooms" } 3 { "title" : "Men Without Women" } 4 { "title" : "Brief Interviews with Hideous Men" }
1 { "title" : "Men with Guns" } 2 { "title" : "Men with Brooms" } 3 { "title" : "Getting Even with Dad" } 4 { "title" : "Chicken with Plums" }
1 { "title" : "Men Without Women" } 2 { "title" : "Men with Guns" } 3 { "title" : "Men with Brooms" } 4 { "title" : "Women Without Men" }
1 [{title Men with Guns}] 2 [{title Men with Brooms}] 3 [{title Men Without Women}] 4 [{title Brief Interviews with Hideous Men}]
1 [{title Men with Guns}] 2 [{title Men with Brooms}] 3 [{title Getting Even with Dad}] 4 [{title Chicken with Plums}]
1 [{title Men Without Women}] 2 [{title Men with Guns}] 3 [{title Men with Brooms}] 4 [{title Women Without Men}]
1 {"title": "Men with Guns"} 2 {"title": "Men with Brooms"} 3 {"title": "Men Without Women"} 4 {"title": "Brief Interviews with Hideous Men"}
1 {"title": "Men with Guns"} 2 {"title": "Men with Brooms"} 3 {"title": "Getting Even with Dad"} 4 {"title": "Chicken with Plums"}
1 {"title": "Men Without Women"} 2 {"title": "Men with Guns"} 3 {"title": "Men with Brooms"} 4 {"title": "Women Without Men"}
1 Document{{title=Men with Brooms}} 2 Document{{title=Men with Guns}} 3 Document{{title=Men Without Women}} 4 Document{{title=Brief Interviews with Hideous Men}}
1 Document{{title=Men with Brooms}} 2 Document{{title=Men with Guns}} 3 Document{{title=Getting Even with Dad}} 4 Document{{title=Chicken with Plums}}
1 Document{{title=Men with Guns}} 2 Document{{title=Men with Brooms}} 3 Document{{title=Men Without Women}} 4 Document{{title=Women Without Men}}
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Men Without Women' } 4 { title: 'Brief Interviews with Hideous Men' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' } 2 { title: 'Men with Guns' } 3 { title: 'Men with Brooms' } 4 { title: 'Women Without Men' }
1 {'title': 'Men with Guns'} 2 {'title': 'Men with Brooms'} 3 {'title': 'Men Without Women'} 4 {'title': 'Brief Interviews with Hideous Men'}
1 {'title': 'Men with Guns'} 2 {'title': 'Men with Brooms'} 3 {'title': 'Getting Even with Dad'} 4 {'title': 'Chicken with Plums'}
1 {'title': 'Men Without Women'} 2 {'title': 'Men with Brooms'} 3 {'title': 'Women Without Men'} 4 {'title': 'Men with Guns'}
简单的sequential
示例
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "men with", tokenOrder: "sequential" } } } ]
每个查询都包括:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class AutocompleteTokenOrderSequentialSimpleExample { private const string MongoConnectionString = "<connection-string>"; public static void Main(string[] args) { // allow automapping of the camelCase database fields to our MovieDocument var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); // connect to your Atlas cluster var mongoClient = new MongoClient(MongoConnectionString); var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); // define and run pipeline var results = moviesCollection.Aggregate() .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "men with", SearchAutocompleteTokenOrder.Sequential)) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(4) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
每个查询都包括:
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) // set namespace collection := client.Database("sample_mflix").Collection("movies") // define pipeline stages searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "men with"}, {"path", "title"}, {"tokenOrder", "sequential"}}}}}} limitStage := bson.D{{"$limit", 4}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) if err != nil { panic(err) } // print results var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) } }
每个查询都包括:
import static com.mongodb.client.model.Aggregates.limit; import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.excludeId; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AutocompleteTokenSequential { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("$search", new Document("autocomplete", new Document("query", "men with").append("path", "title").append("tokenOrder", "sequential"))); // run pipeline and print results collection.aggregate(Arrays.asList(agg, limit(4), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
每个查询都包括:
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Projections.* import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { val uri = "<connection-string>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val agg = Document( "\$search", Document( "autocomplete", Document("query", "men with") .append("path", "title") .append("tokenOrder", "sequential") ) ) val resultsFlow = collection.aggregate<Document>( listOf( agg, limit(4), project(fields(excludeId(), include("title"))) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
每个查询都包括:
const { MongoClient } = require("mongodb"); // connect to your Atlas cluster const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { await client.connect(); // set namespace const database = client.db("sample_mflix"); const coll = database.collection("movies"); // define pipeline const agg = [ {$search: {autocomplete: {query: "men with", path: "title", tokenOrder: "sequential"}}}, {$limit: 4}, {$project: {_id: 0,title: 1}} ]; // run pipeline const result = await coll.aggregate(agg); // print results await result.forEach((doc) => console.log(doc)); } finally { await client.close(); } } run().catch(console.dir);
每个查询都包括:
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "sequential"}}}, {"$limit": 4}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
SCORE: 12.644559860229492 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 12.644559860229492 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 7.997925281524658 _id: “573a1391f29313caabcd93a3” plot: "Navy divers clear the torpedo tube of a sunken submarine." genres: Array runtime: 77 ... title: "Men Without Women"
SCORE: 11.758549690246582 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 11.758549690246582 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 7.70704460144043 _id: “573a1399f29313caabcee64e” plot: "A thief's son cons his father into spending more time with him." genres: Array runtime: 109 ... title: "Getting Even with Dad" SCORE: 7.111915588378906 _id: “573a13cdf29313caabd844f5” plot: "Since his beloved violin was broken, Nasser Ali Khan, one of the most …" genres: Array runtime: 93 ... title: "Chicken with Plums"
SCORE: 7.928277015686035 _id: “573a1391f29313caabcd93a3” plot: "Navy divers clear the torpedo tube of a sunken submarine." genres: Array runtime: 77 ... title: "Men Without Women" SCORE: 7.928277015686035 _id: “573a139af29313caabcf0b12” plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …" genres: Array runtime: 127 ... title: "Men with Guns" SCORE: 7.928277015686035 _id: “573a13a4f29313caabd1287f” plot: "Paul Gross stars as the leader of a recently reunited curling team fro…" genres: Array runtime: 102 ... title: "Men with Brooms" SCORE: 7.381933212280273 _id: “573a13c8f29313caabd77ab6” plot: "Against the tumultuous backdrop of Iran's 1953 CIA-backed coup d'ètat,…" genres: Array runtime: 95 ... title: "Women Without Men"
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
1 { title: 'Men with Guns' }, 2 { title: 'Men with Brooms' }, 3 { title: 'Men Without Women' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' }, 2 { title: 'Men with Guns' }, 3 { title: 'Men with Brooms' }, 4 { title: 'Women Without Men' }
1 { title: 'Men with Guns' }, 2 { title: 'Men with Brooms' }, 3 { title: 'Men Without Women' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' }, 2 { title: 'Men with Guns' }, 3 { title: 'Men with Brooms' }, 4 { title: 'Women Without Men' }
1 {"title": "Men with Guns"} 2 {"title": "Men with Brooms"} 3 {"title": "Men Without Women"}
1 { "title" : "Men with Guns" } 2 { "title" : "Men with Brooms" } 3 { "title" : "Getting Even with Dad" } 4 { "title" : "Chicken with Plums" }
1 { "title" : "Men Without Women" } 2 { "title" : "Men with Guns" } 3 { "title" : "Men with Brooms" } 4 { "title" : "Women Without Men" }
1 [{title Men with Guns}] 2 [{title Men with Brooms}] 3 [{title Men Without Women}]
1 [{title Men with Guns}] 2 [{title Men with Brooms}] 3 [{title Getting Even with Dad}] 4 [{title Chicken with Plums}]
1 [{title Men Without Women}] 2 [{title Men with Guns}] 3 [{title Men with Brooms}] 4 [{title Women Without Men}]
1 {"title": "Men with Guns"} 2 {"title": "Men with Brooms"} 3 {"title": "Men Without Women"}
1 { "title" : "Men with Guns" } 2 { "title" : "Men with Brooms" } 3 { "title" : "Getting Even with Dad" } 4 { "title" : "Chicken with Plums" }
1 {"title": "Men Without Women"} 2 {"title": "Men with Guns"} 3 {"title": "Men with Brooms"} 4 {"title": "Women Without Men"}
1 Document{{title=Men with Brooms}} 2 Document{{title=Men with Guns}} 3 Document{{title=Men Without Women}}
1 Document{{title=Men with Brooms}} 2 Document{{title=Men with Guns}} 3 Document{{title=Getting Even with Dad}} 4 Document{{title=Chicken with Plums}}
1 Document{{title=Men with Guns}} 2 Document{{title=Men with Brooms}} 3 Document{{title=Men Without Women}} 4 Document{{title=Women Without Men}}
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Men Without Women' }
1 { title: 'Men with Guns' } 2 { title: 'Men with Brooms' } 3 { title: 'Getting Even with Dad' } 4 { title: 'Chicken with Plums' }
1 { title: 'Men Without Women' } 2 { title: 'Men with Guns' } 3 { title: 'Men with Brooms' } 4 { title: 'Women Without Men' }
1 {'title': 'Men with Guns'} 2 {'title': 'Men with Brooms'} 3 {'title': 'Men Without Women'}
1 {'title': 'Men with Guns'} 2 {'title': 'Men with Brooms'} 3 {'title': 'Getting Even with Dad'} 4 {'title': 'Chicken with Plums'}
1 {'title': 'Men Without Women'} 2 {'title': 'Men with Guns'} 3 {'title': 'Men with Brooms'} 4 {'title': 'Women Without Men'}
突出显示示例
以下查询在movies
集合的 title
字段中搜索 ger
字符,并为 title
字段启用了 highlight
选项。
重要
要突出显示 autocomplete 已索引版本的路径,autocomplete 运算符必须是唯一在此查询中使用该路径的运算符。
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { autocomplete: { path: "title", query: "ger" }, highlight: { path: "title" } } } ]