자동 완성 기능
이 페이지의 내용
정의
autocomplete
autocomplete
연산자는 불완전한 입력 문자열에서 문자 시퀀스를 포함하는 단어나 구문을 검색합니다.autocomplete
연산자를 사용하여 쿼리하려는 필드는 컬렉션의 인덱스 정의에 있는 자동 완성 데이터 유형으로 인덱싱되어야 합니다. 자동 완성을 위한 인덱스를 구성하는 방법을 알아보려면 자동 완성을 위한 필드 인덱싱 방법을 참조하세요.
참고
Atlas Search는 단일 문자열에 세 개 이상의 단어가 포함된 쿼리에 대해 부정확한 결과를 반환할 수 있습니다.
샘플 사용 사례
입력 시 실시간 검색 애플리케이션에서 autocomplete
연산자를 사용하면 애플리케이션의 검색 필드에 문자가 입력될 때 단어를 더욱 정확하게 예측할 수 있습니다. autocomplete
는 자동 완성을 위해 인덱스 정의에 지정된 토큰화 전략을 기반으로 한 예측 단어가 포함된 결과를 반환합니다.
Atlas Search autocomplete
연산자를 사용하여 추천 또는 드롭다운을 작성하려는 경우 추천 검색어 모음을 쿼리하거나 과거 검색어를 사용하여 드롭다운을 채우는 것이 좋습니다. 제안된 검색어의 별도 컬렉션을 만들면 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 }
옵션
필드 | 유형 | 설명 | 필요성 | 기본값 | ||||||
---|---|---|---|---|---|---|---|---|---|---|
| 문자열 또는 문자열 배열 | 검색할 문자열을 하나 이상 입력합니다. 한 문자열에 여러 개의 용어가 있는 경우 Atlas Search는 문자열의 각 용어에 대해 개별적으로 일치하는 항목을 찾습니다. | 네 | |||||||
| 문자열 | 검색할 인덱싱된 필드입니다. 이 필드는
여러 필드에 걸친 연산자 쿼리 의 예시 는 여러 필드에 걸친 검색 또는 Atlas Search 에서 자동완성을 사용하는 방법의 고급 예제를 참조하세요. | 네 | |||||||
| 객체 | 퍼지 검색을 활성화하도록 설정합니다. 검색어 또는 용어와 유사한 문자열을 찾습니다. | no | |||||||
fuzzy .maxEdits | integer | 지정된 검색 용어와 일치하는 데 필요한 최대 단일 문자 편집 수입니다. 값은 | no |
| ||||||
fuzzy .prefixLength | integer | 정확히 일치해야 하는 결과의 각 용어 시작 부분에 있는 문자 수입니다. | no |
| ||||||
fuzzy .maxExpansions | integer | 생성하고 검색할 수 있는 최대 변형 수입니다. 이 한도는 토큰 단위로 적용됩니다. | no |
| ||||||
| 객체 | 일치하는 검색어 결과에 할당할 점수입니다. 다음 옵션 중 하나를 사용하여 기본 점수를 수정합니다:
쿼리에서 | no | |||||||
| 문자열 | 토큰을 검색할 순서입니다. 값은 다음 중 하나일 수 있습니다:
| no |
|
채점 동작
autocomplete
연산자로 쿼리된 결과 중 정확히 일치하는 결과는 정확히 일치하지 않는 결과보다 낮은 점수를 받습니다. 자동 완성 인덱싱된 토큰의 하위 문자열만 지정된 경우, Atlas Search는 쿼리 문자열이 인덱싱된 텍스트와 정확히 일치하는지 여부를 판단할 수 없습니다. 정확한 일치의 점수를 높이려면 다음과 같은 해결 방법을 시도해 볼 수 있습니다.
참고
하지만, 이 우회 방법이 모든 경우에 정확히 일치하는 결과에 더 높은 점수를 보장하는 것은 아닙니다.
Atlas Search의
autocomplete
는autocomplete
필드가string
으로도 인덱싱되어 있을 때 정확한 일치 항목을 강화하여, 일치 항목의 점수를 증가시킵니다.복합 연산자를 사용하여 쿼리합니다.
이 해결 방법의 데모는 여러 필드에 걸친 검색을 참조하세요.
예시
다음 예시에서는 sample_mflix
데이터베이스의 movies
컬렉션을 사용합니다. 클러스터에 샘플 데이터 세트를 로드한 경우 자동 완성을 위한 정적 인덱스를 생성하고 클러스터에서 예시 쿼리를 실행할 수 있습니다.
팁
샘플 데이터 집합을 이미 로드한 경우, Atlas Search 시작하기 자습서에 따라 인덱스 정의를 만들고 Atlas Search 쿼리를 실행하세요.
인덱스 정의
다음 탭에는 edgeGram
, rightEdgeGram
, nGram
토큰화 전략에 대한 샘플 인덱스 정의가 포함되어 있습니다. 자동 완성 유형 외에도 샘플 인덱스 정의에는 title
필드에 문자열 및 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에서 쿼리 구문을 보고 편집하려면 다음을 수행하세요.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
mongosh
프롬프트에서 다음 명령을 실행하여 sample_mflix
데이터베이스를 사용합니다.
use sample_mflix
기본 예시
다음 쿼리는 title
필드에 off
문자가 포함된 영화를 검색합니다.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
[ { $search: { autocomplete: { path: "title", query: "off" } } } ]
쿼리에는 다음이 포함됩니다.
movies
colection의 Aggregations 탭에서 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 각 파이프라인 단계를 구성합니다. Add Stage를 클릭하여 단계를 추가합니다.
파이프라인 단계 | 쿼리 | ||||||
---|---|---|---|---|---|---|---|
|
| ||||||
|
| ||||||
|
|
쿼리에는 다음이 포함됩니다.
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)
참고
고객의 결과는 다를 수 있음
Atlas Search는 자동 완성 유형에 대한 인덱스 정의에 구성된 토큰화 전략에 따라 다른 결과를 반환합니다. 자세히 알아보려면 자동 완성을 위한 필드 인덱싱 방법을 참조하세요.
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
문자가 포함된 영화를 검색합니다. 쿼리는 다음을 사용합니다.
필드 | 설명 |
| 쿼리를 문서의 단어와 일치시키기 위해 쿼리 문자열 |
| 쿼리를 문서의 단어와 일치시킬 때 쿼리 문자열 |
| 쿼리 문자열을 문서의 단어와 일치시킬 때 |
다음 쿼리를 복사하여 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
colection의 Aggregations 탭에서 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 각 파이프라인 단계를 구성합니다. Add Stage를 클릭하여 단계를 추가합니다.
파이프라인 단계 | 쿼리 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||||
|
| |||||||||||
|
|
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)
참고
고객의 결과는 다를 수 있음
Atlas Search는 자동 완성 유형에 대한 인덱스 정의에 구성된 토큰화 전략에 따라 다른 결과를 반환합니다. 자세히 알아보려면 자동 완성을 위한 필드 인덱싱 방법을 참조하세요.
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" } } } ]
각 쿼리에는
movies
colection의 Aggregations 탭에서 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 각 파이프라인 단계를 구성합니다. Add Stage를 클릭하여 단계를 추가합니다.
파이프라인 단계 | 쿼리 | |||||||
---|---|---|---|---|---|---|---|---|
|
| |||||||
|
| |||||||
|
|
각 쿼리에는
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" } } } ]
각 쿼리에는
movies
colection의 Aggregations 탭에서 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 각 파이프라인 단계를 구성합니다. Add Stage를 클릭하여 단계를 추가합니다.
파이프라인 단계 | 쿼리 | |||||||
---|---|---|---|---|---|---|---|---|
|
| |||||||
|
| |||||||
|
|
각 쿼리에는
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() }