0Pricing
MongoDB Academy · 강의

자동 완성 및 퍼지 일치

학습자는 필드에 자동 완성 분석기를 구성하고 퍼지 쿼리를 작성해 사용자 검색 입력의 오타를 처리합니다.

자동 완성 및 퍼지 일치은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Autocomplete and Fuzzy Search Matter

Modern search experiences require two key features: autocomplete (suggesting completions as the user types) and fuzzy matching (finding results even when the user misspells a query). These features significantly improve user experience—autocomplete reduces search friction by guiding users to valid queries, while fuzzy matching ensures a typo does not result in 'no results found'. Atlas Search provides both through dedicated operators and analyzers.

Configuring an Autocomplete Analyzer

Autocomplete requires a special field configuration in the Atlas Search index. Use the autocomplete data type in the index mapping for the field you want to support type-ahead. This causes Atlas to index n-grams and edge n-grams of the field value—substrings that match partial inputs. The tokenization option can be 'edgeGram' (left-anchored substrings) or 'nGram' (all substrings), with optional minGrams and maxGrams sizes.

// Atlas Search index definition with autocomplete field
{
  'mappings': {
    'dynamic': false,
    'fields': {
      'name': [
        {
          'type': 'string',           // for regular text search
          'analyzer': 'lucene.standard'
        },
        {
          'type': 'autocomplete',     // for type-ahead queries
          'tokenization': 'edgeGram', // 'mongod' -> 'm', 'mo', 'mon', 'mong', 'mongo', 'mongod'
          'minGrams': 2,
          'maxGrams': 10
        }
      ]
    }
  }
}

Running an Autocomplete Query

Use the autocomplete operator inside a $search stage to perform type-ahead queries. Specify the query (the partial input typed so far) and the path (the autocomplete-indexed field). As the user types each character, send a new query and return the top suggestions sorted by score. Limit results to 5-10 suggestions for a responsive UI.

// As user types 'mon', suggest matching product names
async function getAutocompleteSuggestions(partialQuery) {
  const results = await db.collection('products').aggregate([
    {
      $search: {
        autocomplete: {
          query: partialQuery,  // e.g., 'mon' -> suggests 'Monitor', 'MongoDB Atlas', etc.
          path: 'name'
        }
      }
    },
    { $limit: 8 },
    { $project: { name: 1, _id: 0 } }
  ]).toArray();
  return results.map(r => r.name);
}

EdgeGram vs nGram Tokenization

edgeGram creates substrings anchored at the start of each word: 'MongoDB' produces 'Mo', 'Mon', 'Mong', 'Mongo', 'MongoD', 'MongoDB'. This matches queries that start with the correct characters—a good default for name search. nGram creates all substrings of a word, enabling mid-word matching: 'ongo' would also match 'MongoDB'. nGram is more flexible but produces a much larger index and can return less precise suggestions.

// edgeGram: 'Python' generates:
// 'Py', 'Pyt', 'Pyth', 'Pytho', 'Python'
// -> matches queries starting with 'Py', 'Pyt', etc.

// nGram: 'Python' generates:
// 'Py', 'yt', 'th', 'ho', 'on', 'Pyt', 'yth', 'tho', ... etc.
// -> matches mid-word queries like 'ytho'

// For product name autocomplete, edgeGram is almost always the right choice

Fuzzy Matching With the fuzzy Option

The text operator supports a fuzzy option that enables edit-distance based matching. It finds documents whose tokens are within a specified number of character edits (insertions, deletions, substitutions, transpositions) from the query tokens. This makes your search tolerant of typos. The maxEdits parameter controls tolerance (1 = one typo allowed, 2 = two typos).

// Fuzzy search: 'Monggodb' matches 'MongoDB' (1 extra 'g')
db.tutorials.aggregate([
  {
    $search: {
      text: {
        query: 'Monggodb aggregaton',  // two typos
        path: 'title',
        fuzzy: {
          maxEdits: 1,     // allow 1 edit per token
          prefixLength: 3  // first 3 chars must match exactly
        }
      }
    }
  },
  { $limit: 10 }
])

Fuzzy Parameters: maxEdits and prefixLength

maxEdits can be 1 or 2 (Lucene does not support higher values). Higher values increase recall but reduce precision—with maxEdits: 2, many unrelated words may match. prefixLength specifies how many characters at the start of each query token must match exactly before fuzzy matching applies. A prefix length of 2-3 balances performance and accuracy, preventing the algorithm from fuzzy-matching against every token in the index.

// Conservative fuzzy: only 1 edit, first 3 chars must be exact
// Good for search boxes where users make occasional typos
fuzzy: { maxEdits: 1, prefixLength: 3 }

// Aggressive fuzzy: 2 edits, no prefix requirement
// Useful for voice-to-text or low-quality input
fuzzy: { maxEdits: 2, prefixLength: 0 }

// Balanced (recommended default):
fuzzy: { maxEdits: 1, prefixLength: 2, maxExpansions: 50 }

Combining Autocomplete and Fuzzy

Autocomplete and fuzzy matching serve different use cases but can be combined in a compound query. The autocomplete operator handles prefix matching as the user types, while fuzzy matching in a text operator helps when users submit a complete but misspelled query. A common pattern is to try autocomplete first (during typing) and switch to fuzzy text search when the user submits their query.

// Hybrid: autocomplete for prefix + fuzzy for full query
async function search(query, isTyping) {
  if (isTyping) {
    // During typing: use autocomplete
    return db.collection('products').aggregate([
      { $search: { autocomplete: { query, path: 'name' } } },
      { $limit: 6 },
      { $project: { name: 1 } }
    ]).toArray();
  } else {
    // On submit: use fuzzy text search
    return db.collection('products').aggregate([
      { $search: { text: { query, path: ['name', 'description'], fuzzy: { maxEdits: 1 } } } },
      { $limit: 20 },
      { $project: { name: 1, price: 1, score: { $meta: 'searchScore' } } }
    ]).toArray();
  }
}

Token Order in Autocomplete

By default, the autocomplete operator matches the partial query against individual tokens (words) in the field. You can set tokenOrder: 'sequential' to require that the tokens appear in order—useful for multi-word inputs like 'node js' suggesting 'Node.js Developer Guide'. The default tokenOrder: 'any' returns results where any word starts with the prefix, regardless of order.

// Sequential token order: 'node js' must match 'Node.js' in order
db.courses.aggregate([
  {
    $search: {
      autocomplete: {
        query: 'node js',
        path: 'title',
        tokenOrder: 'sequential'  // words must appear in this order
      }
    }
  },
  { $limit: 5 }
])

// Any order: 'js node' would also match 'Node.js'
db.courses.aggregate([
  {
    $search: {
      autocomplete: { query: 'js node', path: 'title', tokenOrder: 'any' }
    }
  }
])

Debouncing Autocomplete Requests

Autocomplete queries fire on every keystroke, which can overwhelm your backend with rapid requests. Always implement debouncing on the client side—wait 200-300ms after the last keystroke before sending the query. Also cancel in-flight requests when a new one is issued to avoid out-of-order responses. In React, use a debounce hook or library; in a simple frontend, use clearTimeout and setTimeout.

// Simple debounce in JavaScript
let debounceTimer;

function onSearchInput(event) {
  const query = event.target.value;
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(async () => {
    if (query.length < 2) return; // minimum length check
    const suggestions = await fetch('/api/autocomplete?q=' + encodeURIComponent(query));
    renderSuggestions(await suggestions.json());
  }, 250); // 250ms debounce
}

Scoring and Relevance in Autocomplete

Atlas Search returns autocomplete results in order of their relevance score. Fields that have the query prefix at the beginning of the entire field value (rather than later in the string) receive higher scores. You can further influence scoring using the score option to boost, constant-score, or decay results based on other factors like popularity or recency. This ensures the most useful suggestions appear first.

// Boost products with higher view counts in autocomplete results
db.products.aggregate([
  {
    $search: {
      autocomplete: {
        query: 'wire',
        path: 'name',
        score: {
          boost: {
            path: 'viewCount',     // boost by view count field
            modifier: 'log1p'      // log1p smoothing prevents extreme boosts
          }
        }
      }
    }
  },
  { $limit: 8 },
  { $project: { name: 1, viewCount: 1 } }
])

Minimum Query Length Best Practice

Avoid running autocomplete queries on very short inputs (1 character) as they return an overwhelming number of irrelevant suggestions and are expensive for the Lucene engine. Enforce a minimum query length of 2-3 characters before firing the autocomplete request. Similarly, for fuzzy matching, enable fuzzy only after the user has typed at least 3-4 characters to give Lucene enough context for meaningful edit-distance computation. These limits improve both performance and suggestion quality.

// Client-side minimum length enforcement
async function handleSearchInput(query) {
  if (query.length < 2) {
    clearSuggestions(); // don't search on 0 or 1 char
    return;
  }
  // Autocomplete: good from 2 chars
  if (query.length <= 4) {
    return getAutocompleteSuggestions(query);
  }
  // Fuzzy search: enable after 4 chars for better precision
  return getFuzzySearchResults(query);
}

Quick Check

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

Lesson Recap

In this lesson you learned: autocomplete requires an 'autocomplete' data type in the index mapping with tokenization (edgeGram or nGram) to index substrings, the autocomplete operator in $search enables prefix matching for type-ahead suggestions, and the text operator's fuzzy option uses edit-distance matching to handle typos with configurable maxEdits and prefixLength parameters. Next up we explore facets and compound queries for sophisticated search experiences.

자주 묻는 질문

“자동 완성 및 퍼지 일치” 강의는 무료인가요?

네 — “자동 완성 및 퍼지 일치” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“자동 완성 및 퍼지 일치”에서 뭘 배우나요?

학습자는 필드에 자동 완성 분석기를 구성하고 퍼지 쿼리를 작성해 사용자 검색 입력의 오타를 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“자동 완성 및 퍼지 일치” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Atlas Search 인덱스 만들기
  2. $search 쿼리 작성하기: 텍스트, 구문, 와일드카드
  3. 자동 완성 및 퍼지 일치
  4. 패싯 및 복합 쿼리
← MongoDB Academy(으)로 돌아가기