0Pricing
MongoDB Academy · درس

إنشاء فهرس Atlas Search

سيعرّف المتعلمون تعيين فهرس بحث في واجهة Atlas أو عبر API، ويفهمون كيفية تجزئة Lucene لقيم الحقول وتخزينها.

إنشاء فهرس Atlas Search درس مجاني في MongoDB Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في MongoDB Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is Atlas Search?

Atlas Search is a fully managed, Apache Lucene-based search engine embedded directly into MongoDB Atlas. Unlike MongoDB's native text indexes, Atlas Search provides relevance scoring, fuzzy matching, autocomplete, faceted navigation, and sophisticated analyzers—all accessible through an aggregation pipeline stage called $search. You do not need to run a separate Elasticsearch or Solr cluster; Atlas Search lives alongside your data.

How Atlas Search Works Under the Hood

Atlas Search runs a Lucene engine as a separate process alongside each MongoDB node. When documents are inserted, updated, or deleted, MongoDB streams the changes to the Lucene index asynchronously. This means Atlas Search indexes are eventually consistent with the MongoDB data—there is a small lag (typically milliseconds) between a write and its appearance in search results. For most applications this is perfectly acceptable.

Creating a Search Index via Atlas UI

In the MongoDB Atlas UI, navigate to your cluster, click the Search tab, and choose Create Search Index. You can use the Visual Editor (point-and-click field mapping) or the JSON Editor to write the index definition directly. The index applies to a specific database and collection. After clicking Create, Atlas builds the index asynchronously—a green status indicator signals when it is ready to query.

The Default Search Index Mapping

The simplest Atlas Search index uses dynamic mapping: MongoDB automatically indexes all string, number, date, and boolean fields without requiring you to enumerate them. The default index definition is just { mappings: { dynamic: true } }. This is the fastest way to get started and is suitable for exploration. For production workloads, switch to static mappings to control which fields are indexed and how they are analyzed.

// Default index definition — dynamic mapping
// All string, number, date, boolean fields are indexed automatically
{
  'mappings': {
    'dynamic': true
  }
}

// This is what you paste into the Atlas JSON Editor when creating the index

Static Mapping: Controlling Field Indexing

Static mapping gives you explicit control over which fields are indexed and how they are analyzed. Set dynamic: false and list each field with its type and analyzer. Fields not listed in a static mapping are not indexed. This reduces index size and improves indexing throughput for large collections by avoiding unnecessary indexing of every field.

// Static mapping: only index 'title' and 'description' as searchable strings
{
  'mappings': {
    'dynamic': false,
    'fields': {
      'title': {
        'type': 'string',
        'analyzer': 'lucene.standard'
      },
      'description': {
        'type': 'string',
        'analyzer': 'lucene.standard'
      },
      'category': {
        'type': 'stringFacet' // for faceted navigation
      },
      'price': {
        'type': 'number'
      }
    }
  }
}

Analyzers: How Text Is Tokenized

An analyzer defines how text is broken into tokens and normalized before storage in the Lucene index. lucene.standard lowercases text and splits on whitespace and punctuation. lucene.english also applies stemming (reducing 'running' to 'run') for better recall. lucene.keyword treats the entire string as a single token, useful for exact-match fields like email addresses or SKU codes. The choice of analyzer significantly impacts search quality.

{
  'mappings': {
    'dynamic': false,
    'fields': {
      // 'Standard' analyzer: good for general text
      'title': { 'type': 'string', 'analyzer': 'lucene.standard' },

      // 'English' analyzer: stemming for better recall
      'description': { 'type': 'string', 'analyzer': 'lucene.english' },

      // 'Keyword' analyzer: exact match only
      'sku': { 'type': 'string', 'analyzer': 'lucene.keyword' },

      // Multi-analyzer: both standard and keyword on same field
      'email': {
        'type': 'string',
        'analyzer': 'lucene.keyword',
        'multi': {
          'standard': { 'type': 'string', 'analyzer': 'lucene.standard' }
        }
      }
    }
  }
}

Creating a Search Index via the Atlas CLI

For infrastructure-as-code and CI/CD pipelines, you can create Atlas Search indexes using the Atlas CLI or the Atlas Administration API. This lets you version-control your search index definitions alongside your application code. The Atlas CLI command is atlas clusters search indexes create with a JSON configuration file.

# Create a search index using the Atlas CLI
# 1. Save index definition to a file:
# cat search-index.json
# { "name": "products_search", "collectionName": "products",
#   "database": "shop", "mappings": { "dynamic": true } }

# 2. Create the index:
# atlas clusters search indexes create \
#   --clusterName MyCluster \
#   --file search-index.json \
#   --projectId <YOUR_PROJECT_ID>

Index Status and Monitoring

After creating a search index, it goes through the BUILDING state while Lucene processes existing documents. During this time, queries may return incomplete results or fail with an error. Once the status shows READY (green in Atlas UI), the index covers all existing documents. New documents added after index creation are indexed with a small lag. Monitor index status programmatically using the Atlas Administration API or the Atlas CLI.

// Check index status via Atlas Admin API
// GET https://cloud.mongodb.com/api/atlas/v1.0/groups/{groupId}/clusters/{clusterName}/fts/indexes/{collectionName}

// In application code, handle the case where the index is still building:
// - Catch errors with code 1261 (IndexNotFound)
// - Retry after a delay or show a 'search unavailable' message

Nested and Array Field Indexing

Atlas Search can index nested document fields and array elements. Use dot notation in the field path to reference nested fields, just like regular MongoDB queries. For arrays of subdocuments, each element is indexed separately. This allows you to search inside embedded objects—for example, finding products where any color option matches a search term.

// Index definition for a product with nested fields and arrays
{
  'mappings': {
    'dynamic': false,
    'fields': {
      'name': { 'type': 'string', 'analyzer': 'lucene.standard' },
      'variants.color': { 'type': 'string', 'analyzer': 'lucene.keyword' },
      'variants.size': { 'type': 'string', 'analyzer': 'lucene.keyword' },
      'reviews.text': { 'type': 'string', 'analyzer': 'lucene.english' },
      'reviews.rating': { 'type': 'number' }
    }
  }
}

Verifying the Index With $search

Once your Atlas Search index is READY, test it with a $search aggregation stage. The simplest query uses the text operator to search for a keyword across indexed string fields. A successful response confirms the index is built and queries are working. Examine the searchScore in the projected output to understand relevance ranking.

// Quick verification query
db.products.aggregate([
  {
    $search: {
      index: 'default', // name of your search index
      text: {
        query: 'wireless headphones',
        path: { wildcard: '*' } // search all indexed fields
      }
    }
  },
  {
    $project: {
      name: 1,
      category: 1,
      price: 1,
      score: { $meta: 'searchScore' }
    }
  },
  { $limit: 5 }
])

Index Naming and Multiple Indexes

You can create multiple Atlas Search indexes on the same collection, each with a different name, field configuration, and analyzers. This allows different use cases to use specialized indexes—a general search index with dynamic mapping, a strict-matching index with keyword analyzers, and an autocomplete index. When running a $search query, specify the index field to select which search index to use.

// Using a named search index in a $search query
db.products.aggregate([
  {
    $search: {
      index: 'products_autocomplete', // use the autocomplete-specific index
      autocomplete: {
        query: 'wire',
        path: 'name'
      }
    }
  }
]);

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: Atlas Search is a Lucene-based full-text search engine embedded in MongoDB Atlas, dynamic mapping indexes all fields automatically while static mapping requires explicit field definitions for finer control, and analyzers like lucene.standard, lucene.english, and lucene.keyword control how text is tokenized and stored. Next up we explore writing $search aggregation queries including text, phrase, and wildcard operators.

الأسئلة الشائعة

هل درس «إنشاء فهرس Atlas Search» مجاني؟

نعم — نص درس «إنشاء فهرس Atlas Search» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة MongoDB Academy، انتقل إلى CoddyKit PRO. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

ماذا ستتعلم في «إنشاء فهرس Atlas Search»؟

سيعرّف المتعلمون تعيين فهرس بحث في واجهة Atlas أو عبر API، ويفهمون كيفية تجزئة Lucene لقيم الحقول وتخزينها. تتمرن على MongoDB Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ MongoDB Academy؟

لا تُشترط خبرة سابقة. MongoDB Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «إنشاء فهرس Atlas Search»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس MongoDB Academy هذا؟

نعم. كل درس في MongoDB Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. إنشاء فهرس Atlas Search
  2. كتابة استعلامات $search: النص والعبارة والبدل
  3. الإكمال التلقائي والمطابقة التقريبية
  4. الواجهات الجانبية والاستعلامات المركبة
← العودة إلى MongoDB Academy