microsoft/semantic-kernel · error · VectorSearchExecutionException

Failed to search the collection.

Error message

Failed to search the collection.

What it means

Raised by MongoDBAtlasCollection._inner_vector_search (VectorSearchExecutionException, subclass of VectorStoreOperationException) wrapping ANY exception thrown while running the `$vectorSearch` + `$project` aggregation. The original error is chained as `__cause__`. Because the catch is broad (`except Exception`), the message alone is generic — you must inspect the cause to know whether the index is missing, dimensions mismatch, or the connection failed.

Source

Thrown at python/semantic_kernel/connectors/mongodb.py:394

        }
        if filter := self._build_filter(options.filter):
            vector_search_query["filter"] = filter if isinstance(filter, dict) else {"$and": filter}

        projection_query: dict[str, int | dict] = {
            field: 1
            for field in self.definition.get_names(
                include_vector_fields=options.include_vectors,
                include_key_field=False,  # _id is always included
            )
        }
        projection_query[MONGODB_SCORE_FIELD] = {"$meta": "vectorSearchScore"}
        try:
            raw_results = await collection.aggregate([
                {"$vectorSearch": vector_search_query},
                {"$project": projection_query},
            ])
        except Exception as exc:
            raise VectorSearchExecutionException("Failed to search the collection.") from exc
        return KernelSearchResults(
            results=self._get_vector_search_results_from_results(raw_results, options),
            total_count=None,  # no way to get a count before looping through the result cursor
        )

    async def _inner_keyword_hybrid_search(
        self,
        options: VectorSearchOptions,
        values: Any | None = None,
        vector: Sequence[float | int] | None = None,
        **kwargs: Any,
    ) -> KernelSearchResults[VectorSearchResult[TModel]]:
        collection = self._get_collection()
        vector_field = self.definition.try_get_vector_field(options.vector_property_name)
        if not vector_field:
            raise VectorStoreModelException(
                f"Vector field '{options.vector_property_name}' not found in the data model definition."
            )

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect the chained cause: `except VectorSearchExecutionException as e: log(e.__cause__)`.
  2. Verify a vector search index named `index_name` exists on the collection in Atlas and is 'Active'.
  3. Confirm queryVector length equals the index numDimensions and the 'path' matches the indexed field.
  4. Check connectivity/credentials to the Atlas cluster.

Example fix

// before
res = await collection.search(search_type=SearchType.VECTOR, vector=emb)
// after
try:
    res = await collection.search(search_type=SearchType.VECTOR, vector=emb)
except VectorSearchExecutionException as e:
    raise RuntimeError(f'atlas vector search failed: {e.__cause__!r}') from e
Defensive patterns

Strategy: try-catch

Validate before calling

# preflight: ensure a vector index exists with matching dimensions
# (run in Atlas UI or via collection.ensure_index_exists if available)
# then guard the query
assert emb is not None and len(emb) == expected_dim, 'vector dim mismatch'

Try / catch

from semantic_kernel.exceptions import VectorSearchExecutionException
try:
    res = await collection.search(search_type=SearchType.VECTOR, vector=emb)
except VectorSearchExecutionException as e:
    cause = e.__cause__
    if 'vectorSearch' in str(cause).lower() and 'index' in str(cause).lower():
        await ensure_vector_index(collection)  # create/fix index, then retry once
        res = await collection.search(search_type=SearchType.VECTOR, vector=emb)
    else:
        raise

Prevention

When it happens

Trigger: The Atlas `$vectorSearch` aggregation fails: the named search index does not exist; index_name mismatch; queryVector dimensions != index numDimensions; the path field is not indexed; auth/network/timeout errors; Atlas tier/region issues; invalid filter expression from _build_filter.

Common situations: Vector search index not yet created in Atlas (or still building); index_name in code != index name in Atlas; embedding model changed dimensions without re-creating the index; wrong database/collection; expired credentials.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/46c52f21ae12a933. Report an issue: GitHub.