mem0ai/mem0 · error · ValueError

Invalid filter key: {key!r}

Error message

Invalid filter key: {key!r}

What it means

Neptune Analytics builds openCypher queries from your filters, so filter keys are validated against ^[a-zA-Z_~][a-zA-Z0-9_]*$. This error means a key failed that pattern: it is either not a string or contains characters (spaces, dots, dashes, $, unicode) that cannot appear safely as a property key in the generated Cypher.

Source

Thrown at mem0/vector_stores/neptune_analytics.py:24

from pydantic import BaseModel

try:
    from langchain_aws import NeptuneAnalyticsGraph
except ImportError:
    raise ImportError("langchain_aws is not installed. Please install it using pip install langchain_aws")

from mem0.vector_stores.base import VectorStoreBase

logger = logging.getLogger(__name__)

_SAFE_FILTER_KEY = re.compile(r"^[a-zA-Z_~][a-zA-Z0-9_]*$")
_VALID_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")


def _validate_filter(key: str, value: Any) -> None:
    if not isinstance(key, str) or not _SAFE_FILTER_KEY.match(key):
        raise ValueError(f"Invalid filter key: {key!r}")
    if not isinstance(value, (str, int, float, bool)):
        raise ValueError(
            f"Filter value for {key!r} must be str, int, float, or bool, "
            f"got {type(value).__name__}"
        )


def _escape_cypher(value: str) -> str:
    return value.replace("\\", "\\\\").replace("'", "\\'")

class OutputData(BaseModel):
    id: Optional[str]  # memory id
    score: Optional[float]  # distance
    payload: Optional[Dict]  # metadata


class NeptuneAnalyticsVector(VectorStoreBase):
    """

View on GitHub (pinned to 001c235229)

Solutions

  1. Rename filter keys to letters, digits, underscore, with an optional leading tilde (e.g. "user_id", "app_version")
  2. Normalize/whitelist filter keys at your API boundary before they reach Mem0
  3. Store the exotic key inside the payload and filter on a sanitized alias key instead

Example fix

// before
filters = {"user-id": "alice", "app.version": "v2"}

// after
filters = {"user_id": "alice", "app_version": "v2"}
Defensive patterns

Strategy: validation

Validate before calling

import re
SAFE_KEY = re.compile(r"^[a-zA-Z_~][a-zA-Z0-9_]*$")

def sanitize_neptune_keys(filters: dict) -> dict:
    return {re.sub(r"[^a-zA-Z0-9_]", "_", k): v for k, v in (filters or {}).items()
            if isinstance(k, str)}

filters = sanitize_neptune_keys(filters)

Type guard

def is_neptune_safe_key(k) -> bool:
    return isinstance(k, str) and bool(re.match(r"^[a-zA-Z_~][a-zA-Z0-9_]*$", k))

Try / catch

try:
    store.search(q, vec, filters=filters)
except ValueError as e:
    if "Invalid filter key" in str(e):
        filters = sanitize_neptune_keys(filters)
        store.search(q, vec, filters=filters)
    else:
        raise

Prevention

When it happens

Trigger: Passing filters={"user-id": "u1"} (dash), {"user id": "u1"} (space), {"app.version": 2} (dot), or a non-string key (int from JSON with numeric keys) to search/list on the Neptune Analytics backend.

Common situations: Reusing filters written for the Qdrant/OpenSearch backends (which allow dots) against Neptune; forwarding raw HTTP query params as filter keys; camelCase keys with exotic separators from analytics pipelines.

Related errors


AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15). Data as JSON: /api/errors/2550edec367fb04a. Report an issue: GitHub.