{"record":{"id":"19f50febb6ebc8e9","repo":"run-llama/llama_index","slug":"value-for-metadata-key-must-be-one-of-str-int","errorCode":null,"errorMessage":"Value for metadata {key} must be one of (str, int, float, None)","messagePattern":"Value for metadata (.+?) must be one of \\(str, int, float, None\\)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"llama-index-core/llama_index/core/vector_stores/utils.py","lineNumber":35,"sourceCode":")\n\n\nDEFAULT_TEXT_KEY = \"text\"\nDEFAULT_TEXT_RESOURCE_KEY = \"text_resource\"\nDEFAULT_EMBEDDING_KEY = \"embedding\"\nDEFAULT_DOC_ID_KEY = \"doc_id\"\n\n\ndef _validate_is_flat_dict(metadata_dict: dict) -> None:\n    \"\"\"\n    Validate that metadata dict is flat,\n    and key is str, and value is one of (str, int, float, None).\n    \"\"\"\n    for key, val in metadata_dict.items():\n        if not isinstance(key, str):\n            raise ValueError(\"Metadata key must be str!\")\n        if not isinstance(val, (str, int, float, type(None))):\n            raise ValueError(\n                f\"Value for metadata {key} must be one of (str, int, float, None)\"\n            )\n\n\ndef node_to_metadata_dict(\n    node: BaseNode,\n    remove_text: bool = False,\n    text_field: str = DEFAULT_TEXT_KEY,\n    text_resource_field: str = DEFAULT_TEXT_RESOURCE_KEY,\n    flat_metadata: bool = False,\n) -> Dict[str, Any]:\n    \"\"\"Common logic for saving Node data into metadata dict.\"\"\"\n    # Using mode=\"json\" here because BaseNode may have fields of type bytes (e.g. images in ImageBlock),\n    # which would cause serialization issues.\n    node_dict = node.model_dump(mode=\"json\")\n    metadata: Dict[str, Any] = node_dict.get(\"metadata\", {})\n\n    if flat_metadata:","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/vector_stores/utils.py#L17-L53","documentation":"Companion check to the key validation: `_validate_is_flat_dict` requires every metadata value to be a str, int, float, or None when flat metadata is enabled. Lists, dicts, booleans-subclassed types, datetimes, and nested objects are rejected because flat-metadata vector stores cannot filter on structured values. The message names the offending key, which usually points straight at the problematic field.","triggerScenarios":"Adding nodes with `metadata={\"authors\": [\"a\", \"b\"]}`, `\"date\": datetime(...)`, `\"attrs\": {...}}` etc. through `node_to_metadata_dict(..., flat_metadata=True)`; ingesting rich dicts from APIs or ORMs without flattening.","commonSituations":"Ingesting JSON documents with nested objects or arrays directly as metadata; ORM model dumps containing datetime/Decimal; wanting list-valued filters on a store that only supports scalars; switching a store from one that tolerated complex metadata to one that validates.","solutions":["Flatten or stringify complex values before adding: `\"authors\": \", \".join(authors)`, `str(datetime)`, `json.dumps(nested)`.","Keep only filterable scalar fields in metadata and move the rest into node content or a separate store.","Use a store/code path that supports structured metadata (not flat_metadata mode) if you truly need nested values.","Add a pre-ingestion normalizer that raises your own descriptive error on unsupported types."],"exampleFix":"# before\nnode = TextNode(text=\"...\", metadata={\"authors\": [\"A\", \"B\"], \"date\": dt})\n\n# after\nnode = TextNode(\n    text=\"...\",\n    metadata={\"authors\": \", \".join([\"A\", \"B\"]), \"date\": dt.isoformat()},\n)","handlingStrategy":"validation","validationCode":"ALLOWED = (str, int, float, type(None))\n\ndef validate_flat_metadata(metadata: dict) -> None:\n    for k, v in metadata.items():\n        if not isinstance(v, ALLOWED):\n            raise TypeError(f\"metadata[{k!r}] has unsupported type {type(v).__name__}\")","typeGuard":"def is_flat_scalar_dict(d: dict) -> bool:\n    return all(\n        isinstance(k, str) and isinstance(v, (str, int, float, type(None)))\n        for k, v in d.items()\n    )","tryCatchPattern":null,"preventionTips":["Flatten lists/dicts at ingestion (join, json.dumps, or per-field columns).","Convert datetimes/Decimals to str or float explicitly.","Run a metadata lint step in CI over sample documents."],"tags":["metadata","validation","ingestion","type-error","python"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}