String de query
Definição
Sintaxe
queryString
tem a seguinte sintaxe:
1 { 2 "$search": { 3 "index": <index name>, // optional, defaults to "default" 4 "queryString": { 5 "defaultPath": "<default-field-to-search>", 6 "query": "(<field-to-search>: (<search-values>) AND|OR (<search-values>)) AND|OR (<search-values>)" 7 } 8 } 9 }
Opções
queryString
usa os seguintes termos para construir uma consulta:
Campo | Tipo | Descrição | necessidade | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| string | O campo indexado para pesquisar por padrão. O Atlas Search pesquisa somente o campo no | sim | ||||||||||||||||||||
| string | Um ou mais campos e valores indexados para pesquisar. Campos e valores são delimitados por ponto e vírgula. Por exemplo, para pesquisar o campo Você pode combinar os campos e valores utilizando o seguinte:
Você pode executar queries de expressão regular e curinga utilizando o seguinte:
| sim | ||||||||||||||||||||
| objeto | A pontuação atribuída aos resultados de pesquisa correspondentes. Você pode modificar a pontuação padrão usando as seguintes opções:
Ao fazer query de valores de array, o Atlas Search atribui a mesma pontuação, independentemente de quantos valores na array correspondem à query. Para obter informações sobre como utilizar o | no |
Exemplos
Os exemplos seguintes utilizam a movies
coleção no sample_mflix
banco de dados . Se você tiver o conjunto de dados de amostra no seu cluster, você poderá criar o índice Atlas Search denominado default
com mapeamentos dinâmicos e executar as queries de exemplo no seu cluster.
Queries de operadores booleanos
Exemplos básicos
O exemplo a seguir usa o operador queryString
para consultar filmes com o título Rocky
e ou IV
, 4
ou Four
no caminho title
na coleção movies
. Na seguinte consulta, um campo é especificado no defaultPath
, mas nenhum campo é especificado no query
. A consulta inclui um estágio $project
para excluir todos os campos, exceto title
.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "Rocky AND (IV OR 4 OR Four)" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1 14 } 15 } 16 ])
Para esta consulta, o Atlas Search executa uma pesquisa no defaultPath
porque não há campos no query
. Retorna os seguintes resultados:
{ "title" : "Rocky IV" }
O exemplo a seguir usa o queryString
operador para consultar filmes com o título Rocky
e não qualquer forma dos números,,2
3
4
ou 5
no caminho title
no{7} coleção. Na seguinte consulta, um campo é especificado defaultPath
no, mas nenhum campo é especificado query
no. A consulta inclui um $project
estágio para excluir todos os campos,title
exceto.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "Rocky AND NOT ((II OR 2 OR Two) OR (III OR 3 OR Three) OR (IV OR 4 OR Four) OR (V OR 5 OR Five))" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1 14 } 15 } 16 ])
[ { title: 'Rocky' }, { title: 'Rocky Marciano' }, { title: 'Rocky Balboa' }, { title: 'The Rocky Horror Picture Show' }, { title: 'The Adventures of Rocky & Bullwinkle' } ]
O exemplo a seguir usa o operador queryString
para consultar uma combinação de campos para filmes com o título The
Italian
no gênero Drama
. O campo plot
no defaultPath
será pesquisado somente se nenhum resultado correspondente puder ser encontrado em qualquer um dos campos especificados no campo query
. O campo query
contém aspas duplas como delimitadores da frase a ser pesquisada.
A query inclui uma fase $project
para:
Exclua todos os campos, exceto
_id
,title
,plot
egenres
Adicione um campo chamado
score
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:\"The Italian\" AND genres:Drama" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 1, 13 "title": 1, 14 "plot": 1, 15 "genres": 1, 16 score: { $meta: "searchScore" } 17 } 18 } 19 ])
{ "_id" : ObjectId("573a1390f29313caabcd56df"), "plot" : "An immigrant leaves his sweetheart in Italy to find a better life across the sea in the grimy slums of New York. They are eventually reunited and marry. But life in New York is hard and ...", "genres" : [ "Drama" ], "title" : "The Italian", "score" : 4.975106716156006 } { "_id" : ObjectId("573a13b3f29313caabd3e36c"), "plot" : "Set in 2002, an abandoned 5-year-old boy living in a rundown orphanage in a small Russian village is adopted by an Italian family.", "genres" : [ "Drama" ], "title" : "The Italian", "score" : 4.975106716156006 } { "_id" : ObjectId("573a13c7f29313caabd756ee"), "plot" : "A romantic fairy tale about a 19-year old orphan girl who, as her sole inheritance, gets an antique key that unlocks both an old Italian villa and the secrets of her family history.", "genres" : [ "Comedy", "Drama", "Romance" ], "title" : "The Italian Key", "score" : 4.221206188201904 } { "_id" : ObjectId("573a13caf29313caabd7d1e4"), "plot" : "A chronicle of the 1969 bombing at a major national bank in Milan and its aftermath.", "genres" : [ "Drama" ], "title" : "Piazza Fontana: The Italian Conspiracy", "score" : 3.4441356658935547 }
O exemplo seguinte utiliza o operador queryString
para fazer uma query de uma combinação de termos, captain
ou kirk
e enterprise
, no campo plot
. Inclui um estágio do $limit
para limitar o resultado para 3
resultados e um estágio do $project
para:
Exclua todos os campos, exceto
title
,plot
efullplot
Adicione um campo chamado
score
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:(captain OR kirk) AND enterprise" 7 } 8 } 9 }, 10 { 11 $limit: 3 12 }, 13 { 14 $project: { 15 "_id": 0, 16 "title": 1, 17 "plot": 1, 18 "fullplot": 1, 19 score: { $meta: "searchScore" } 20 } 21 } 22 ])
{ "plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.", "fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.", "title" : "Star Trek: Generations", "score" : 11.274821281433105 } { "plot" : "Captain Kirk and his crew must deal with Mr. Spock's long-lost half-brother who hijacks the Enterprise for an obsessive search for God at the center of the galaxy.", "fullplot" : "When the newly-christened starship Enterprise's shakedown cruise goes poorly, Captain Kirk and crew put her into Spacedock for repairs. But an urgent mission interrupts their Earth-bound shore leave. A renegade Vulcan named Sybok has taken three ambassadors hostage on Nimbus III, the Planet of Galactic Peace. This event also attracts the attention of a Klingon captain who wants to make a name for himself and sets out to pursue the Enterprise. Sybok's ragtag army captures the Enterprise and takes her on a journey to the center of the galaxy in search of the Supreme Being.", "title" : "Star Trek V: The Final Frontier", "score" : 9.889547348022461 } { "plot" : "When an alien spacecraft of enormous power is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine and hopefully stop the intruder.", "fullplot" : "A massive alien spacecraft of enormous power is approaching Earth, destroying everything in its path. The only star ship in range is the USS Enterprise still in dry-dock after a major overhaul. As Captain Willard Decker readies his ship and his crew to face this menace, Admiral James T. Kirk arrives with orders to take command of the Enterprise and intercept the alien intruder. But it has been three years since Kirk last commanded the Enterprise on its historic five year mission... is he up to the task of saving the Earth?", "title" : "Star Trek: The Motion Picture", "score" : 8.322310447692871 }
Os documentos nos resultados correspondem porque:
No primeiro documento, o campo
plot
, que é o campo a ser pesquisado de acordo com oquery
, contémcaptain
ekirk
, embora somente um seja necessário para atender aos critérios de uma correspondência. Para o termoenterprise
, o Atlas Search pesquisa o campofullplot
, que é odefaultPath
, porque o campoplot
não contémenterprise
e localizaenterprise
no campofullplot
.No segundo documento, o campo
plot
contém todos os três termos de pesquisa.No terceiro documento, o campo
plot
contémkirk
eenterprise
.
Exemplos avançados
Os exemplos nesta seção usam o operador queryString
para fazer uma query de gráficos de filme que contêm os termos captain
, kirk
e chess
. Estes exemplos mostram como o cluster diferente dos mesmos termos de pesquisa usando parênteses pode resultar em documentos diferentes a serem incluídos nos resultados da pesquisa.
As queries também incluem um estágio do $project
para:
Exclua todos os campos, exceto
title
,plot
efullpath
Adicione um campo chamado
score
A consulta a seguir procura chess
e captain
ou kirk
no campo plot
.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:(captain OR kirk) AND chess" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1, 14 "plot": 1, 15 "fullplot": 1, 16 score: { $meta: "searchScore" } 17 } 18 } 19 ])
{ "fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.", "plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.", "title" : "Star Trek Into Darkness", "score" : 7.968792915344238 }
O documento nos resultados é uma correspondência, pois o plot
contém os termos captain
e kirk
, embora apenas um seja necessário para atender aos critérios para uma correspondência, e o termo chess
, embora não no plot
, aparece no fullplot
, que é o defaultPath
.
A consulta a seguir procura captain
ou kirk
e chess
no campo plot
.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:captain OR (kirk AND chess)" 7 } 8 } 9 }, 10 { 11 $limit: 5 12 }, 13 { 14 $project: { 15 "_id": 0, 16 "title": 1, 17 "plot": 1, 18 "fullplot": 1, 19 score: { $meta: "searchScore" } 20 } 21 } 22 ])
{ "fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.", "plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.", "title" : "Star Trek Into Darkness", "score" : 9.227973937988281 } { "plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.", "title" : "Star Trek: Generations", "fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.", "score" : 3.3556222915649414 } { "plot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every ...", "title" : "Scent of a Woman", "fullplot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every situation, nicknames the youth Ciccio (\"Babyfat\"), and spends the next few days ordering him about and generally behaving badly in public. In Rome, Fausto summons a priest to ask for his blessing; in Naples, where Fausto joins a blind lieutenant for drinking and revelry, the two soldiers talk quietly and seriously about \"going through with it.\" Also in Naples is Sara, in love with Fausto, but treated cruelly by him. What do the blind soldiers plan? Can Sara soften Fausto's hardened heart?", "score" : 3.2553727626800537 } { "plot" : "A seductive woman falls in love with a mysterious ship's captain.", "title" : "Pandora and the Flying Dutchman", "fullplot" : "Albert Lewin's interpretation of the legend of the Flying Dutchman. In a little Spanish seaport named Esperanza, during the 30s, appears Hendrick van der Zee, the mysterious captain of a yacht (he is the only one aboard). Pandora is a beautiful woman (who men kill and die for). She's never really fallen in love with any man, but she feels very attracted to Hendrick... We are soon taught that Hendrick is the Flying Dutchman, this sailor of the 17th century that has been cursed by God to wander over the seas until the Doomsday... unless a woman is ready to die for him...", "score" : 3.2536067962646484 } { "plot" : "The adventures of pirate Captain Red and his first mate Frog.", "title" : "Pirates", "fullplot" : "Captain Red runs a hardy pirate ship with the able assistance of Frog, a dashing young French sailor. One day Capt. Red is captured and taken aboard a Spanish galleon, but thanks to his inventiveness, he raises the crew to mutiny, takes over the ship, and kidnaps the niece of the governor of Maracaibo. The question is, can he keep this pace up?", "score" : 3.2536067962646484 }
Os documentos nos resultados correspondem porque o campo plot
contém o termo captain
. O primeiro documento obtém uma pontuação maior porque o Atlas Search também encontra os termos kirk
e chess
no campo fullplot
, embora os termos não precisem estar presentes para atender aos critérios de uma correspondência.
Queries de intervalo
O exemplo a seguir usa o operador queryString
para consultar os títulos de filme um intervalo de valores textuais dos caracteres count
para qualquer caractere (definido usando o caractere curinga *
) em ordem alfabética crescente.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:[count TO *]" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'Blacksmith Scene' }, 3 { title: 'The Great Train Robbery' }, 4 { title: 'The Land Beyond the Sunset' }, 5 { title: 'A Corner in Wheat' }, 6 { title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics' }, 7 { title: 'Traffic in Souls' }, 8 { title: 'Gertie the Dinosaur' }, 9 { title: 'In the Land of the Head Hunters' }, 10 { title: 'The Perils of Pauline' }, 11 { title: 'The Birth of a Nation' } 12 ]
Os resultados do Atlas Search incluem filmes com títulos Blacksmith Scene
e A Corner in Wheat
, embora o intervalo na consulta comece com os caracteres count
. Quando você indexa com o analisador padrão, lucene.standard
, o Atlas Search cria tokens separados para os termos no campo title
e faz a correspondência entre o termo da consulta e os tokens individuais. Especificamente, o Atlas Search cria os seguintes tokens, dos quais pelo menos um (indicado por √) corresponde aos critérios de consulta:
Título | Tokens de analisador padrão |
---|---|
Cena de ferreiro |
|
Um Cantinho no Trigo |
|
Se você indexar usando o analisador de lucene.keyword
, o Atlas Search criará um único token para toda a cadeia de caracteres no campo title
, resultando em resultados semelhantes aos seguintes para a mesma consulta:
[ { title: 'è Nous la Libertè' }, { title: 'tom thumb' }, { title: 'è nos amours' }, { title: 'èke och hans vèrld' }, { title: 'èdipussi' }, { title: 's/y Glèdjen' }, { title: 'èAy, Carmela!' }, { title: 'èlisa' }, { title: 'èxtasis' }, { title: 'eXistenZ' } ]
O exemplo a seguir usa o operador queryString
para consultar os gêneros de filmes em drama
e os títulos de uma variedade de valores textuais entre man
e men
, incluindo ambos, em ordem alfabética ascendente.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:[man TO men] AND genres: Drama" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1, 17 "genres": 1 18 } 19 } 20 ])
1 [ 2 { genres: [ 'Drama' ], title: 'The Wedding March' }, 3 { genres: [ 'Drama' ], title: 'Maria Chapdelaine' }, 4 { genres: [ 'Drama' ], title: 'Of Mice and Men' }, 5 { genres: [ 'Drama' ], title: 'All the King's Men' }, 6 { genres: [ 'Drama' ], title: 'Wuya yu maque' }, 7 { genres: [ 'Drama' ], title: 'The Men' }, 8 { genres: [ 'Drama' ], title: 'The Member of the Wedding' }, 9 { genres: [ 'Drama' ], title: 'The Great Man' }, 10 { genres: [ 'Drama' ], title: 'A Matter of Dignity' }, 11 { genres: [ 'Drama' ], title: 'The Last Angry Man' } 12 ]
Os documentos nos resultados coincidem porque o campo genres
contém o termo drama
e o campo filme title
contém termos entre Man
e Men
em ordem alfabética (Man
, Maque
, March
, Maria
, Matter
, Member
, e Men
nos resultados).
Queries curinga
Os exemplos seguintes utilizam o operador queryString
para consultar títulos de filmes utilizando expressões difusas, curingas e regulares. As queries incluem um estágio $project
para excluir todos os campos, exceto title
.
A consulta a seguir usa fuzzy (~
) para fazer uma pesquisa fuzzy no campo title
para títulos de filmes que contêm termos semelhantes a catch
com uma variação de até dois caracteres.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "catch~2" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'Catch-22' }, 3 { title: 'Catch That Girl' }, 4 { title: 'Catch That Kid' }, 5 { title: 'Catch a Fire' }, 6 { title: 'Catch Me Daddy' }, 7 { title: 'Death Watch' }, 8 { title: 'Patch Adams' }, 9 { title: "Batch '81" }, 10 { title: 'Briar Patch' }, 11 { title: 'Night Watch' } 12 ]
A query a seguir usa uma expressão curinga para o Atlas Search no campo title
para títulos de filmes que contenham caracteres cou*t?*
, em que *
indica qualquer número adicional de caracteres e ?
indica qualquer caractere único.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "cou*t?*" 7 } 8 } 9 }, 10 { 11 "$limit": 5 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'A Day in the Country' }, 3 { title: 'Diary of a Country Priest' }, 4 { title: 'Cry, the Beloved Country' }, 5 { title: 'The Country Girl' }, 6 { title: 'Raintree County' } 7 ]
Os documentos nos resultados correspondem porque o campo title
contém o termo Country
ou County
, que corresponde aos critérios da query para caracteres que começam com cou
seguidos por qualquer número de caracteres (n
nos resultados) e em seguida, t
seguido por pelo menos um ou muitos caracteres (r
como em country
ou y
como em county
nos resultados).
A query a seguir usa uma expressão regular para pesquisar no campo title
títulos de filmes que contenham caracteres que comecem com qualquer caractere seguido pelos caracteres tal
e y
ou ian
após tal
.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "/.tal(y|ian)/" 7 } 8 } 9 }, 10 { 11 "$limit": 5 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'The Italian' }, 3 { title: 'Journey to Italy' }, 4 { title: 'Divorce Italian Style' }, 5 { title: 'Marriage Italian Style' }, 6 { title: 'Jealousy, Italian Style' } 7 ]
Os documentos nos resultados correspondem porque o campo title
contém o termo Italy
ou Italian
, que corresponde aos critérios de query para qualquer caractere (I
nos resultados) seguido por tal
com y
(como em Italy
nos resultados) ou ian
(como em Italian
nos resultados).
Query de metadados
A seguinte query pesquisa o campo title
na coleção movies
para Marvel
, Avengers
, Iron Man
ou Captain
America
.