{"record":{"id":"ad4f81079def0a91","repo":"deepset-ai/haystack","slug":"query-should-be-a-non-empty-string","errorCode":null,"errorMessage":"Query should be a non-empty string","messagePattern":"Query should be a non-empty string","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"haystack/document_stores/in_memory/document_store.py","lineNumber":740,"sourceCode":"\n        sorted_keys = sorted(unique_values, key=lambda k: (k[1], k[0]))\n        paginated_keys = sorted_keys[from_ : from_ + size]\n        return [unique_values[k] for k in paginated_keys], len(sorted_keys)\n\n    def bm25_retrieval(\n        self, query: str, filters: dict[str, Any] | None = None, top_k: int = 10, scale_score: bool = False\n    ) -> list[Document]:\n        \"\"\"\n        Retrieves documents that are most relevant to the query using BM25 algorithm.\n\n        :param query: The query string.\n        :param filters: A dictionary with filters to narrow down the search space.\n        :param top_k: The number of top documents to retrieve. Default is 10.\n        :param scale_score: Whether to scale the scores of the retrieved documents. Default is False.\n        :returns: A list of the top_k documents most relevant to the query.\n        \"\"\"\n        if not query:\n            raise ValueError(\"Query should be a non-empty string\")\n\n        content_type_filter = {\"field\": \"content\", \"operator\": \"!=\", \"value\": None}\n        if filters:\n            if \"operator\" not in filters:\n                raise ValueError(\n                    \"Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering for details.\"\n                )\n            filters = {\"operator\": \"AND\", \"conditions\": [content_type_filter, filters]}\n        else:\n            filters = content_type_filter\n\n        all_documents = self.filter_documents(filters=filters)\n        if len(all_documents) == 0:\n            logger.info(\"No documents found for BM25 retrieval. Returning empty list.\")\n            return []\n\n        # A tokenless corpus (every stored document has empty content) has no vocabulary and an\n        # average document length of zero, which would make all three BM25 algorithms divide by","sourceCodeStart":722,"sourceCodeEnd":758,"githubUrl":"https://github.com/deepset-ai/haystack/blob/e318778c9bf60a1963e3b5f451359655dd696c30/haystack/document_stores/in_memory/document_store.py#L722-L758","documentation":"InMemoryDocumentStore.bm25_retrieval raises ValueError when the query argument is empty (or falsy). BM25 scoring is undefined for an empty query, so the store fails fast instead of returning meaningless results.","triggerScenarios":"Calling bm25_retrieval(query=\"\") or bm25_retrieval(query=None); passing a query variable that was never filled (empty string from a failed upstream component or blank user input).","commonSituations":"Chat pipelines receiving empty user messages, templates leaving a placeholder unfilled, stripping/normalizing the query down to an empty string before retrieval.","solutions":["Guard the call: only invoke bm25_retrieval when query.strip() is non-empty","Return an empty result or a friendly message to the user when the query is blank","Fix the upstream component so it emits a real query instead of an empty string"],"exampleFix":"// before\nresults = store.bm25_retrieval(query=user_input, top_k=10)\n// after\nif not user_input or not user_input.strip():\n    results = []\nelse:\n    results = store.bm25_retrieval(query=user_input, top_k=10)","handlingStrategy":"validation","validationCode":"if not isinstance(query, str) or not query.strip():\n    raise ValueError(\"query must be a non-empty string before bm25_retrieval\")","typeGuard":"def is_non_empty_str(x) -> bool:\n    return isinstance(x, str) and bool(x.strip())","tryCatchPattern":"try:\n    docs = store.bm25_retrieval(query=query, top_k=10)\nexcept ValueError as e:\n    if \"Query should be a non-empty string\" in str(e):\n        docs = []  # or return a 'no query provided' message\n    else:\n        raise","preventionTips":["Validate/normalize user input before retrieval; reject blank queries early","Check upstream components (e.g. query reformulators) don't emit empty strings","Strip and re-check the query after any preprocessing that could empty it"],"tags":["bm25","retrieval","validation","python"],"backgroundTag":"empty-query-parameter","analyzedSha":"e318778c9bf60a1963e3b5f451359655dd696c30","analyzedAt":"2026-08-30T11:45:20.711Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}