개요
In this guide, you can learn how to use the Rust driver to run a text query. A text query allows you to efficiently query fields with string values.
중요
MongoDB text queries differ from the more powerful Atlas Search feature. To learn more, see the Atlas Search documentation.
이 가이드에는 다음 섹션이 포함되어 있습니다.
Sample Data for Examples presents the sample data that is used by the text query examples
텍스트 인덱스 는 문자열 값 필드 에 텍스트 인덱스 를 만드는 방법을 설명합니다.
Text Query describes how to perform text queries with different search criteria
Aggregation describes how to perform text queries by using aggregation pipelines
추가 정보에서 이 가이드에 언급된 유형 및 메소드에 대한 리소스 및 API 문서 링크를 찾을 수 있습니다.
예시용 샘플 데이터
이 가이드의 예시에서는 다음 Dish
구조체를 menu
collection의 문서 모델로 사용합니다.
struct Dish { name: String, description: String, }
이 예제에서는 레스토랑에서 주문할 수 있는 요리를 설명하는 다음 샘플 문서를 사용합니다.
{ "name": "Shepherd’s Pie", "description": "A vegetarian take on the classic dish that uses lentils as a base. Serves 2." }, { "name": "Green Curry", "description": "A flavorful Thai curry, made vegetarian with tofu. Vegetarian and vegan friendly." }, { "name": "Herbed Branzino", "description": "Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4." }, { "name": "Kale Tabbouleh", "description": "A bright, herb-based salad. A perfect starter for vegetarians and vegans." }, { "name": "Garlic Butter Trout", "description": "Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2." }
Text Index
Before you perform a text query, you must create a text index on the collection. A text index specifies the string or string array field on which you can perform text queries.
The examples in this guide perform text queries on the description
field of documents in the menu
collection. To enable text queries on the description
field, create a text index as shown in the following code:
let index = IndexModel::builder() .keys(doc! { "description": "text" }) .build(); let idx_res = my_coll.create_index(index).await?;
텍스트 쿼리
A text query retrieves documents that contain a specified term or phrase in the value of the indexed field. A term is a sequence of characters that excludes whitespace characters. A phrase is a sequence of terms with any number of whitespace characters.
To perform a text query, include the $text
evaluation query operator, followed by the $search
field in your query filter. The $text
operator specifies that you are performing a text query on the text-indexed fields. The $search
field specifies the term or phrase to search for in the text-indexed field or fields.
Filters for text queries use the following format:
let filter = doc! { "$text": { "$search": "<search term or phrase>" } };
용어 검색
텀을 검색하려면 쿼리 필터에서 해당 텀을 문자열로 지정합니다. 여러 텀을 검색하려면 각 텀을 공백으로 구분합니다.
참고
여러 텀을 검색할 때 find()
메서드는 텍스트 인덱스 필드 또는 필드에 텀 중 하나 이상이 포함된 문서를 반환합니다.
예를 들어 검색어가 "one two
three"
인 경우 MongoDB는 인덱싱된 필드에 "one"
, "two"
, "three"
또는 이러한 용어 중 하나 이상이 포함된 문서를 반환합니다.
예시
다음 예에서는 description
필드에 "herb"
텀이 포함된 문서 검색을 수행합니다.
let filter = doc! { "$text": { "$search": "herb" } }; let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Dish { name: "Kale Tabbouleh", description: "A bright, herb-based salad. A perfect starter for vegetarians and vegans." } Dish { name: "Herbed Branzino", description: "Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4." }
팁
Even though the search term is "herb"
, the text query also matches documents in which the description
field contains "herbs"
. This is because a MongoDB text index uses suffix stemming to match similar words. To learn more about how MongoDB matches terms, see Index Entries in the Server manual.
구문 검색
구문을 검색하려면 쿼리 필터에 이스케이프 따옴표가 포함된 구문을 지정합니다.
let filter = doc! { "$text": { "$search": "\"<some phrase>\"" } };
문구 주위에 이스케이프 따옴표를 추가하지 않으면 Atlas Search는 용어 Atlas Search를 수행합니다.
예시
다음 예에서는 description
필드에 "serves 2"
구문이 포함된 문서 검색을 수행합니다.
let filter = doc! { "$text": { "$search": "\"serves 2\"" } }; let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Dish { name: "Shepherd's Pie", description: "A vegetarian take on the classic dish that uses lentils as a base. Serves 2." } Dish { name: "Garlic Butter Trout", description: "Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2." }
검색에서 텀 제외
To specify a term or phrase you want to exclude from your text query, prefix it with a minus sign in your query filter:
let filter = doc! { "$text": { "$search": "<term> -<excluded term>" } };
중요
검색에서 다른 용어를 제외하려면 하나 이상의 용어 또는 구를 검색해야 합니다. 텀만 제외하면 검색 시 어떤 문서도 반환되지 않습니다.
예시
다음 예에서는 description
필드에 "vegan"
라는 용어가 포함되어 있지만 "tofu"
라는 용어는 포함되어 있지 않은 문서를 검색합니다.
let filter = doc! { "$text": { "$search": "vegan -tofu" } }; let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Dish { name: "Kale Tabbouleh", description: "A bright, herb-based salad. A perfect starter for vegetarians and vegans." }
관련성 기준 정렬
A text query assigns a numerical text score to indicate how closely each result matches the string in your query filter. A higher text score indicates that the result is more relevant to your query. To reveal the text score in your output, use a projection to retrieve the textScore
field from the metadata. You can sort the text score in descending order by specifying a sort on the textScore
metadata field.
예시
이 예에서는 다음 조치를 수행합니다.
description
필드에"vegetarian"
이라는 용어가 포함된 문서 검색을 수행합니다.텍스트 점수에서 내림차순으로 결과 정렬
출력에
name
및score
필드만 포함합니다.
let filter = doc! { "$text": { "$search": "vegetarian" } }; let sort = doc! { "score": { "$meta": "textScore" } }; let projection = doc! { "_id": 0, "name": 1, "score": { "$meta": "textScore" } }; let doc_coll: Collection<Document> = my_coll.clone_with_type(); let mut cursor = doc_coll.find(filter) .sort(sort) .projection(projection) .await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Document({"name": String("Green Curry"), "score": Double(0.9166666666666667)}) Document({"name": String("Kale Tabbouleh"), "score": Double(0.5625)}) Document({"name": String("Shepherd’s Pie"), "score": Double(0.5555555555555556)})
집계
You can include the $text
evaluation query operator in a $match aggregation stage to perform a text query in an aggregation pipeline.
The following sections demonstrate how to perform text queries by using aggregation pipelines instead of the find()
method.
검색어 일치
다음 예에서는 애그리게이션을 사용하여 description
필드에 "herb"
텀이 포함된 문서를 검색합니다.
let match_stage = doc! { "$match": { "$text": { "$search": "herb" } } }; let mut cursor = my_coll.aggregate([match_stage]).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Document({"_id": ObjectId("..."), "name": String("Kale Tabbouleh"), "description": String("A bright, herb-based salad. A perfect starter for vegetarians and vegans.")}) Document({"_id": ObjectId("..."), "name": String("Herbed Branzino"), "description": String("Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4.")})
관련성 기준 정렬
이 예에서는 애그리게이션을 사용하여 다음 조치를 수행합니다.
description
필드에"vegetarian"
이라는 용어가 포함된 문서 검색을 수행합니다.텍스트 점수에서 내림차순으로 결과 정렬
출력에
name
및score
필드만 포함합니다.
let match_stage = doc! { "$match": { "$text": { "$search": "vegetarian" } } }; let sort_stage = doc! { "$sort": { "score": { "$meta": "textScore" } } }; let proj_stage = doc! { "$project": { "_id": 0, "name": 1, "score": { "$meta": "textScore" } } }; let pipeline = [match_stage, sort_stage, proj_stage]; let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Document({"name": String("Green Curry"), "score": Double(0.9166666666666667)}) Document({"name": String("Kale Tabbouleh"), "score": Double(0.5625)}) Document({"name": String("Shepherd’s Pie"), "score": Double(0.5555555555555556)})
추가 정보
find()
메서드를 사용하는 실행 가능한 예시 는 여러 문서 찾기 사용 예시 참조하세요.
이 가이드의 작업에 대해 자세히 알아보려면 다음 문서를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.