Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Menu Docs
Página inicial do Docs
/
Atlas
/

Consultas e índices

The relationship between search queries and search indexes dictates how efficiently and effectively you can find data within your MongoDB collections using MongoDB Search.

MongoDB Search queries specify the criteria for finding documents within a database. MongoDB Search queries take the form of an aggregation pipeline that begins with the $search or $searchMeta pipeline stage. You can use operators, collectors, and search options inside the pipeline stages to implement complex search functionality like full-text search, relevance-based ranking, faceted search, filtering, and sorting.

Before you can run an MongoDB Search query, you must create an MongoDB Search index on the fields that you want to search. Search indexes are data structures that are optimized to quickly retrieve documents that meet the search criteria of your query. When you define a search index, you specify which fields to index and how these fields should be tokenized.

Queries de pesquisa eficazes dependem de índices de pesquisa bem definidos. Os campos que você pretende pesquisar devem ser indexados, e a configuração do índice determina se sua pesquisa oferece suporte a ordenação, facetas, preenchimento automático e outras funcionalidades de pesquisa. Você pode iterar tanto no design da query quanto no design do índice para equilibrar a precisão da pesquisa com o desempenho.

This page describes how to plan your MongoDB Search search experience and define an MongoDB Search index and query to fit your search requirements.

When planning your MongoDB Search implementation, start by defining the search experience you want to deliver:

  • Identifique claramente quais tipos de pesquisa seu aplicativo precisa realizar. Você está desenvolvendo um recurso de pesquisa para um blog que necessita de pesquisa de texto completo e autocompletar para títulos de artigos, ou um site de e-commerce que requer pesquisa facetada e filtro por categorias de produtos?

  • Determine como os usuários interagirão com seu aplicação. Priorize recursos que melhorarão a experiência do usuário, como tempos de resposta rápidos ou sugestões precisas de preenchimento automático.

Then, consider the following questions to help determine the structure of your MongoDB Search indexes and queries based on those user needs:

Before you can search your data using MongoDB Search, you must create one or more MongoDB Search indexes to be used during your MongoDB Search query. This section demonstrates how to apply your query preferences to the JSON configuration syntax of an MongoDB Search index.

Para usar a sintaxe JSON nesta seção da sua definição de índice, substitua os espaços reservados por valores válidos e assegure-se de que sua definição completa de índice inclua as opções necessárias.

To learn how to add your MongoDB Search index to your Atlas cluster, see the MongoDB Search Quick Start.

1

If you know which fields you want to query in your collection, enable static mappings and specify the fields in your MongoDB Search index definition. Otherwise, you can enable dynamic mappings to automatically index all the fields of supported types.

Para saber mais, consulte Mapeamentos estáticos e dinâmicos.

Observação

If your collection contains documents that are 16MB or larger, MongoDB Search fails to index your data. This issue can also occur when update operations on large documents cause the change stream event to exceed the 16MB BSON limit. To avoid this, consider the following best practices:

  • Estruture seus documentos para minimizar o tamanho de subdocumentos ou arrays.

  • Evite operações que atualizem ou substituam campos grandes, subdocumentos ou arrays.

Para aprender mais, veja Recomendações de Produção de Change Streams e Reduzir o Tamanho de Documentos Grandes.

1{
2 "mappings": {
3 "dynamic": true,
4 "fields": { // Optional, use this to configure individual fields
5 "<field-name>": {
6 "type": "<field-type>",
7 ...
8 },
9 ...
10 }
11 }
12}
1{
2 "mappings": {
3 "dynamic": false, // Optional, if omitted defaults to "false"
4 "fields": {
5 "<field-name>": {
6 "type": "<field-type>",
7 ...
8 },
9 ...
10 }
11 }
12}
2

Se você tiver requisitos especiais de idioma ou análise, poderá aplicar as seguintes opções à definição do índice:

Especifique quais analisadores internos aplicar aos campos de string que você está indexando nos campos analyzer, searchAnalyzer ou fields.<field-name>.analyzer.

1{
2 "analyzer": "<index-analyzer-name>", // top-level index analyzer, used if no analyzer is set in the field mappings
3 "searchAnalyzer": "<search-analyzer-name>", // query text analyzer, typically the same as the index analyzer
4 "mappings": {
5 "dynamic": <boolean>,
6 "fields":{
7 "<field-name>": [
8 {
9 "type": "string",
10 "analyzer": "<field-analyzer-name>" // field-specific index analyzer
11 }
12 ]
13 }
14 }
15}

Define custom analyzers for your MongoDB Search index in the analyzers field.

1{
2 "analyzers": [
3 {
4 "name": "<custom-analyzer-name>",
5 "tokenizer": {
6 "type": "<tokenizer-type>"
7 }
8 },
9 ...
10 ]
11}

Defina sinônimos para termos que tenham significados iguais ou semelhantes no campo synonyms.

1{
2 "synonyms": [
3 {
4 "name": "<synonym-mapping-name>",
5 "source": {
6 "collection": "<source-collection-name>"
7 },
8 "analyzer": "<synonym-mapping-analyzer>"
9 }
10 ]
11}
3

If you want to optimize your query performance on a large dataset, you can add the following options to your index definition to limit the amount of data that your MongoDB Search query must traverse:

Use the numPartitions option to configure partitions for your index. When you partition your index, MongoDB Search automatically distributes the index objects between sub-indexes in an optimal way.

1{
2 "numPartitions": <integer>,
3}

Use the storedSource option to specify fields in the source document that MongoDB Search must store.

1{
2 "storedSource": true | false | {
3 "include" | "exclude": [
4 "<field-name>",
5 ...
6 ]
7 }
8}

After you create an MongoDB Search index for all the fields that you want to search in your collection, you can run an MongoDB Search query. This section demonstrates how to apply your goals for your application's search experience to the JSON syntax of an MongoDB Search query.

To use the JSON syntax in this section in your MongoDB Search query aggregation pipeline, replace the placeholders with valid values and ensure that your full query pipeline contains the required $search fields or $searchMeta fields.

To learn how to run a Search query, see the MongoDB Search Quick Start.

1

The first stage of your MongoDB Search query aggregation pipeline must be either the $search or $searchMeta stage, depending on whether you're searching for documents or metadata:

Estágio do pipeline de agregação
Propósito

Retornar resultados da pesquisa de texto completo.

Retornar metadados sobre seus resultados de pesquisa.

2

Para definir seus critérios de pesquisa, você deve aplicar um ou mais operadores ou coletores ao seu $search ou $searchMeta fase do pipeline.

MongoDB Search operators allow you to locate and retrieve relevant data from your Atlas cluster according to content, format, or data tyoe. To learn which operators support searches for each field type, see the table in the operators reference section. You must specify one or more indexed search fields in the operator's query path parameter:

1{
2 $search: {
3 "<operator-name>"|"<collector-name>": {
4 <operator-specification>|<collector-specification>
5 }
6 }
7}
[
{
_id: <result-document-id>,
...
},
{
_id: <result-document-id>,
...
},
...
]
1{
2 $searchMeta: {
3 "<operator-name>"|"<collector-name>": {
4 <operator-specification>|<collector-specification>
5 }
6 }
7}
[
{
count: {
total: <results-count>
}
}
]

Dica

Você pode combinar múltiplos operadores em uma única operação usando o operador composto. Você também pode usar a cláusula de filtro do operador composto para filtrar a saída da query que corresponda a uma determinada cláusula.

3

If you want to retrieve metadata from your MongoDB Search query, you can apply one of the following configurations to choose between the count or facet (Atlas Search Operator) type of metadata results document:

Para retornar a contagem total ou com limite inferior dos resultados da pesquisa, defina a opção de contagem no estágio de agregação.

O estágio $searchMeta retorna os resultados de metadados count, enquanto o estágio $search armazena os resultados de metadados na variável de agregação $$SEARCH_META e retorna somente os resultados da pesquisa. Para ver um exemplo de como recuperar os resultados de metadados count da variável $$SEARCH_META, consulte Contagem de resultados.

1{
2 "$search" | "$searchMeta": {
3 "<operator-name>": {
4 <operator-specifications>
5 },
6 "count": {
7 "type": "lowerBound" | "total",
8 "threshold": <number-of-documents> // Optional
9 }
10 }
11}

Para executar uma query de faceta, que agrupa resultados por valores ou intervalos e retorna a contagem para cada um desses grupos, use o coletor facet (Operador de Atlas Search) em seu estágio de agregação.

A fase $searchMeta retorna facet resultados de metadados, enquanto a fase $search armazena os resultados de metadados na variável de agregação $$SEARCH_META e retorna apenas os resultados da pesquisa. Para um exemplo de como recuperar os resultados de metadados facet da variável $$SEARCH_META, consulte Resultados de faceta.

1{
2 "$search" | "$searchMeta": {
3 "facet": {
4 "facets": {
5 <facet-definitions>
6 }
7 }
8 }
9}
4

Você pode recuperar informações adicionais sobre os resultados da fase $search usando as seguintes opções:

Opção
Caso de uso

Exiba seus termos de pesquisa em seu contexto original como campos no resultado da consulta.

Retrieve a detailed breakdown of the score for each document MongoDB Search returns.

Rastreie e forneça informações analíticas para seus termos de pesquisa de query.

Retrieve analytics about which Lucene queries MongoDB Search executed to satify your query, and how much time your query spends in the various stages of execution.

5

Você pode implementar uma funcionalidade especial de ordenação para seus resultados de $search com as seguintes opções:

Opção
Caso de uso

Modify the relevance score of the documents in the results to ensure MongoDB Search returns relevant results.

Classifique seus resultados por número, string e campos de data ou por pontuação.

Defina um ponto de referência para parar ou iniciar seus resultados ordenados

6

Otimize o desempenho da query usando as seguintes opções de $search:

Opção
Caso de uso

Run your MongoDB Search query more efficiently by only retrieving fields stored on mongot as specified in your MongoDB Search index definition for a collection.

Paralelize a procura entre segmentos em nós de pesquisa dedicados.

To learn how to build and run an MongoDB Search index and MongoDB Search query, see the MongoDB Search Quick Start.

To learn more about the MongoDB Search query configuration options mentioned in this tutorial, see the following reference pages:

To learn more about the MongoDB Search index configuration options mentioned in this tutorial, see the following reference pages:

Voltar

Facetas