Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion ingestion/.ruff-g004-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -1372,7 +1372,6 @@
"fb144ad7469c455b2a7cd1ae82804f4ac7790d6f8d6b5c71b264543965162da0": 1
},
"ingestion/src/metadata/ingestion/source/database/mongodb/metadata.py": {
"67d33e3b2b6885d114ed81efe16bc11e81a0ec91dfa281987b4a4287e69332d0": 1,
"74729dc04d52d8389f2ad9423942672d2b201e941c333a08b4dfcc6020c56dd5": 1,
"c4a147a8314a530f52dcb063a5eabfc6f3dfe0fb85edfc4556945745c3bfa78e": 1
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import traceback
from abc import ABC, abstractmethod
from collections.abc import Iterable
from typing import Any
from typing import TYPE_CHECKING, Any

from pydantic import BaseModel

Expand All @@ -31,6 +31,7 @@
from metadata.generated.schema.entity.data.databaseSchema import DatabaseSchema
from metadata.generated.schema.entity.data.table import (
Column,
DataType,
Table,
TableConstraint,
TableType,
Expand All @@ -57,19 +58,40 @@
from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure
from metadata.utils import fqn
from metadata.utils.constants import DEFAULT_DATABASE
from metadata.utils.datalake.datalake_utils import DataFrameColumnParser
from metadata.utils.datalake.datalake_utils import GenericDataFrameColumnParser
from metadata.utils.filters import filter_by_schema, filter_by_table
from metadata.utils.helpers import retry_with_docker_host
from metadata.utils.logger import ingestion_logger
from metadata.utils.schema_inference import InferenceLimits, InferenceReport
from metadata.utils.ssl_manager import check_ssl_and_init

if TYPE_CHECKING:
from pandas import DataFrame

logger = ingestion_logger()


SAMPLE_SIZE = 1000


class NoSQLDataFrameColumnParser(GenericDataFrameColumnParser):
"""Preserve native string values in NoSQL documents instead of parsing their contents.

The generic DataFrame parser deliberately guesses CSV/datalake column types from
text (including numeric-looking strings). MongoDB and other NoSQL drivers
provide typed values: a BSON string such as "01051" must stay STRING.
"""

@classmethod
def fetch_col_types(cls, data_frame: "DataFrame", column_name: str) -> DataType:
non_null = data_frame[column_name].dropna()
if len(non_null) and non_null.dtype.name == "object":
values = non_null.values[:SAMPLE_SIZE]
if all(isinstance(value, str) for value in values):
return DataType.STRING
return super().fetch_col_types(data_frame, column_name)


class TableNameAndType(BaseModel):
"""
Helper model for passing down
Expand Down Expand Up @@ -267,7 +289,7 @@ def get_table_columns(self, schema_name: str, table_name: str) -> list[Column]:

df = pd.DataFrame.from_records(list(self.get_table_columns_dict(schema_name, table_name)))
inference_report = InferenceReport()
column_parser = DataFrameColumnParser.create(df, limits=self.inference_limits, report=inference_report)
column_parser = NoSQLDataFrameColumnParser(df, limits=self.inference_limits, report=inference_report)
columns = column_parser.get_columns()
inference_report.emit(self.status, f"{schema_name}.{table_name}", self.inference_limits)
return columns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from pymongo.errors import OperationFailure

from metadata.generated.schema.entity.data.table import TableType
from metadata.generated.schema.entity.services.connections.database.mongoDBConnection import (
MongoDBConnection,
)
Expand Down Expand Up @@ -68,15 +69,22 @@ def get_schema_name_list(self) -> list[str]:
return []

def query_table_names_and_types(self, schema_name: str) -> Iterable[TableNameAndType]:
"""
Method to get list of table names available within schema db
need to be overridden by sources
"""
return self._list_collections(schema_name, {"type": {"$ne": "view"}}, TableType.Regular)

def query_view_names_and_types(self, schema_name: str) -> Iterable[TableNameAndType]:
return self._list_collections(schema_name, {"type": "view"}, TableType.View)

def _list_collections(
self, schema_name: str, collection_filter: dict, table_type: TableType
) -> list[TableNameAndType]:
try:
database = self.mongodb.get_database(schema_name)
return [TableNameAndType(name=name) for name in database.list_collection_names()]
return [
TableNameAndType(name=name, type_=table_type)
for name in database.list_collection_names(filter=collection_filter)
]
except Exception as exp:
logger.debug(f"Failed to list collection names for schema [{schema_name}]: {exp}")
logger.debug("Failed to list %s names for schema [%s]: %s", table_type.value, schema_name, exp)
logger.debug(traceback.format_exc())
return []

Expand Down
25 changes: 21 additions & 4 deletions ingestion/tests/integration/mongodb/test_metadata.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest

from metadata.generated.schema.entity.data.table import Table
from metadata.generated.schema.entity.data.table import Table, TableType
from metadata.workflow.metadata import MetadataWorkflow


Expand Down Expand Up @@ -29,11 +29,12 @@ def prepare_mongodb(mongodbContainer): # noqa: N803
},
)
data = [
{"id": 1, "name": "John Doe", "age": 25},
{"id": 2, "name": "Jane Smith", "age": 30},
{"id": 1, "name": "John Doe", "age": 25, "zip_code": "01051"},
{"id": 2, "name": "Jane Smith", "age": 30, "zip_code": "01052"},
]

db.test_table.insert_many(data)
db.create_collection("test_view", viewOn="test_table", pipeline=[])


@pytest.mark.parametrize(
Expand All @@ -45,6 +46,7 @@ def prepare_mongodb(mongodbContainer): # noqa: N803
"id": {"type": "int", "nullable": False},
"name": {"type": "string", "nullable": False},
"age": {"type": "int", "nullable": True},
"zip_code": {"type": "string", "nullable": True},
},
]
],
Expand All @@ -64,8 +66,23 @@ def test_ingest_metadata(
table = metadata.get_by_name(entity=Table, fqn=table_fqn.format(service=db_service.fullyQualifiedName.root))
assert table
assert table.fullyQualifiedName.root.split(".")[-1] == "test_table"
assert len(table.columns) == 4
assert len(table.columns) == 5
for name, properties in expected_columns.items():
column = next((col for col in table.columns if col.name.root == name), None)
assert column is not None
assert column.dataType.name.lower() == properties["type"]


def test_views_are_ingested_as_views(
patch_passwords_for_db_services,
run_workflow,
ingestion_config,
metadata,
db_service,
prepare_mongodb,
):
run_workflow(MetadataWorkflow, ingestion_config)
service = db_service.fullyQualifiedName.root

assert metadata.get_by_name(entity=Table, fqn=f"{service}.test.test.test_view").tableType == TableType.View
assert metadata.get_by_name(entity=Table, fqn=f"{service}.test.test.test_table").tableType == TableType.Regular
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Copyright 2025 Collate
# Licensed under the Collate Community License, Version 1.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""MongoDB/NoSQL document values carry types that must not be re-parsed from text."""

from unittest.mock import MagicMock

from metadata.generated.schema.entity.data.table import DataType
from metadata.ingestion.source.database.common_nosql_source import CommonNoSQLSource
from metadata.utils.schema_inference import NO_LIMITS


def _columns_from_nosql(records):
source = MagicMock()
source.get_table_columns_dict.return_value = records
source.inference_limits = NO_LIMITS
return CommonNoSQLSource.get_table_columns(source, "schema", "collection")


def test_numeric_looking_mongodb_strings_keep_their_bson_type():
columns = _columns_from_nosql(
[
{"CODIGO": "01051", "COUNT": 10},
{"CODIGO": "01052", "COUNT": 20},
{"CODIGO": "01053", "COUNT": 30},
]
)
by_name = {column.name.root: column for column in columns}

assert by_name["CODIGO"].dataType == DataType.STRING
assert by_name["CODIGO"].dataTypeDisplay == DataType.STRING.value
assert by_name["COUNT"].dataType == DataType.INT


def test_all_string_nosql_columns_remain_string_even_for_numbers_dates_and_bools():
columns = _columns_from_nosql(
[
{"zip": "00501", "year": "2024", "day": "2024-01-01", "flag": "True"},
{"zip": "00502", "year": "2025", "day": "2025-01-01", "flag": "False"},
]
)

assert {column.name.root: column.dataType for column in columns} == {
"zip": DataType.STRING,
"year": DataType.STRING,
"day": DataType.STRING,
"flag": DataType.STRING,
}


def test_nosql_nested_objects_and_arrays_keep_generic_inference():
columns = _columns_from_nosql([{"metadata": {"active": True}, "items": [1, 2], "amount": 3.5}])
types = {column.name.root: column.dataType for column in columns}

assert types["metadata"] == DataType.JSON
assert types["items"] == DataType.ARRAY
assert types["amount"] == DataType.FLOAT
Loading