{"record":{"id":"1ee0505b9b73dd3e","repo":"mem0ai/mem0","slug":"filter-value-for-key-r-must-be-str-int-float-1ee050","errorCode":null,"errorMessage":"Filter value for {key!r} must be str, int, float, or bool, got {type(value).__name__}","messagePattern":"Filter value for (.+?) must be str, int, float, or bool, got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mem0/vector_stores/elasticsearch.py","lineNumber":32,"sourceCode":"from mem0.vector_stores.base import VectorStoreBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass OutputData(BaseModel):\n    id: str\n    score: float\n    payload: Dict\n\n\n_SAFE_FILTER_KEY = re.compile(r\"^[a-zA-Z_][a-zA-Z0-9_]*$\")\n\n\ndef _validate_filter(key: str, value: Any) -> None:\n    if not isinstance(key, str) or not _SAFE_FILTER_KEY.match(key):\n        raise ValueError(f\"Invalid filter key: {key!r}\")\n    if not isinstance(value, (str, int, float, bool)):\n        raise ValueError(\n            f\"Filter value for {key!r} must be str, int, float, or bool, \"\n            f\"got {type(value).__name__}\"\n        )\n\n\nclass ElasticsearchDB(VectorStoreBase):\n    def __init__(self, **kwargs):\n        config = ElasticsearchConfig(**kwargs)\n\n        # Initialize Elasticsearch client\n        if config.cloud_id:\n            self.client = Elasticsearch(\n                cloud_id=config.cloud_id,\n                api_key=config.api_key,\n                verify_certs=config.verify_certs,\n                ca_certs=config.ca_certs,\n                headers= config.headers or {},\n            )","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/vector_stores/elasticsearch.py#L14-L50","documentation":"ValueError from _validate_filter in elasticsearch.py when a filter value is not str, int, float, or bool. The value is placed directly into the ES term query, so unrenderable types (None, list, dict, datetime) are rejected up front rather than producing a malformed query or a confusing server error.","triggerScenarios":"search/get with filters={'role': None}, {'tags': ['a']}, {'ts': datetime.now()}, or nested operator dicts ({'gte': 1}). bool is accepted (subclass of int); None is not.","commonSituations":"Optional filters left as None instead of omitted; passing range/query DSL fragments from other libraries; datetime objects not converted to ISO strings.","solutions":["Omit keys whose value is None: {k: v for k, v in filters.items() if v is not None}.","Convert datetimes to strings and flatten lists to a single scalar or repeated equality terms as supported.","For range queries, pre-compute a boolean/bucketed field because only equality filtering is supported here."],"exampleFix":"# before\ndb.search(query, vectors, filters={\"since\": {\"gte\": \"2024-01-01\"}})  # ValueError: got dict\n\n# after\nfilters = {\"user_id\": \"alice\"}  # scalars only; convert/remove the rest\ndb.search(query, vectors, filters=filters)","handlingStrategy":"type-guard","validationCode":"def scalarize_filters(filters: dict) -> dict:\n    out = {}\n    for k, v in (filters or {}).items():\n        if v is None:\n            continue\n        if hasattr(v, \"isoformat\"):\n            v = v.isoformat()\n        if not isinstance(v, (str, int, float, bool)):\n            raise ValueError(f\"filter {k!r} must be scalar, got {type(v).__name__}\")\n        out[k] = v\n    return out\n\ndb.search(query, vectors, filters=scalarize_filters(filters))","typeGuard":"def is_scalar_filter_value(v) -> bool:\n    return isinstance(v, (str, int, float, bool)) and not hasattr(v, \"isoformat\")","tryCatchPattern":null,"preventionTips":["Type filter dicts as Mapping[str, str|int|float|bool] in your codebase.","Convert datetimes to ISO strings and drop None values before calling search.","Reserve ranges/lists for application-side filtering; this path supports equality only."],"tags":["elasticsearch","filters","validation","type-error"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}