Skip to content
Open
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: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@

## Bugfixes

* (Python) Fixed `ReadFromMongoDB` failing with a `TypeError` on collections whose `_id` values have different types, such as strings and `ObjectId`s. Such collections, and those with `_id` types that can't be split by range, are now read in a single bundle ([#30472](https://github.com/apache/beam/issues/30472)).
* (Python) Fixed RunInference failing with `TypeError: cannot create weak reference to 'dict' object` when `ModelHandler.load_model()` returns a model that can't be weakly referenced, such as a `dict` or `list` ([#41351](https://github.com/apache/beam/issues/41351)).
* (Java) Flink `OrderedListState` now preserves multiple values with the same timestamp when reading state or clearing a different timestamp range ([#39782](https://github.com/apache/beam/issues/39782)).
* (Python) Fixed Vertex AI embedding transforms ignoring `project`, `location` and `credentials` on remote workers ([#41957](https://github.com/apache/beam/pull/41957)).
Expand Down
77 changes: 77 additions & 0 deletions sdks/python/apache_beam/io/mongodbio.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
coll='input',
bucket_auto=True)

The collection is split into bundles by ranges of the ``_id`` field, which
requires every ``_id`` in the collection to be an ``ObjectId``, an integer or a
string. If the ``_id`` values have other types, or a mix of types, the whole
collection is read in a single bundle.


Write to MongoDB:
-----------------
Expand Down Expand Up @@ -78,6 +83,7 @@
from apache_beam.io.range_trackers import LexicographicKeyRangeTracker
from apache_beam.io.range_trackers import OffsetRangeTracker
from apache_beam.io.range_trackers import OrderedPositionRangeTracker
from apache_beam.io.range_trackers import UnsplittableRangeTracker
from apache_beam.transforms import DoFn
from apache_beam.transforms import PTransform
from apache_beam.transforms import Reshuffle
Expand Down Expand Up @@ -208,6 +214,16 @@ def fraction_to_position(
return _ObjectIdHelper.int_to_id(pos)


class _UnsplittableIdRangeTracker(UnsplittableRangeTracker):
"""RangeTracker for reading a whole collection whose _id values can't be
split into ranges, for example because they are of different types.

Positions are the indexes of the documents in the order they are read.
"""
def __init__(self):
super().__init__(OffsetRangeTracker(0, OffsetRangeTracker.OFFSET_INFINITY))


class _BoundedMongoSource(iobase.BoundedSource):
"""A MongoDB source that reads a finite amount of input records.

Expand Down Expand Up @@ -307,10 +323,31 @@ def split(
desired_bundle_size_in_mb = max(desired_bundle_size_in_mb, 1)

is_initial_split = start_position is None and stop_position is None
range_start, range_stop = start_position, stop_position
start_position, stop_position = self._replace_none_positions(
start_position, stop_position
)

if not self._is_splittable_id_range(start_position, stop_position):
# MongoDB only matches range queries against values of the same BSON
# type, so a collection with _id values of mixed or unsupported types
# can't be read by _id ranges.
_LOGGER.info(
"Not splitting MongoDB collection %s.%s: _id values range from %r "
"to %r, which is not a range of a single supported type (ObjectId, "
"int or str). Reading it in a single bundle.",
self.db,
self.coll,
start_position,
stop_position)
yield iobase.SourceBundle(
weight=1,
source=self,
start_position=range_start,
stop_position=range_stop,
)
return

if self.bucket_auto:
# Use $bucketAuto for bundling
split_keys = []
Expand Down Expand Up @@ -373,6 +410,9 @@ def get_range_tracker(
start_position, stop_position
)

if not self._is_splittable_id_range(start_position, stop_position):
return _UnsplittableIdRangeTracker()

if isinstance(start_position, ObjectId):
return _ObjectIdRangeTracker(start_position, stop_position)

Expand Down Expand Up @@ -412,6 +452,10 @@ def read(self, range_tracker):
Returns:
an iterator of data read by the source.
"""
if isinstance(range_tracker, _UnsplittableIdRangeTracker):
yield from self._read_all(range_tracker)
return

with MongoClient(self.uri, **self.spec) as client:
all_filters = self._merge_id_filter(
range_tracker.start_position(), range_tracker.stop_position())
Expand All @@ -424,6 +468,17 @@ def read(self, range_tracker):
return
yield doc

def _read_all(self, range_tracker):
with MongoClient(self.uri, **self.spec) as client:
docs_cursor = (
client[self.db][self.coll].find(
filter=self.filter,
projection=self.projection).sort([("_id", ASCENDING)]))
for index, doc in enumerate(docs_cursor):
if not range_tracker.try_claim(index):
return
yield doc

def display_data(self):
"""Returns the display data associated to a pipeline component."""
res = super().display_data()
Expand All @@ -434,6 +489,28 @@ def display_data(self):
res["bucket_auto"] = self.bucket_auto
return res

@staticmethod
def _id_range_type(_id):
"""Returns the type used to split ranges of the given _id, or None if
ranges of it can't be split."""
if isinstance(_id, ObjectId):
return ObjectId
if isinstance(_id, bool):
return None
if isinstance(_id, int):
return int
if isinstance(_id, str):
return str
return None

@classmethod
def _is_splittable_id_range(cls, start_pos, end_pos):
"""Return `True` if both ends of the range are of the same type, which
can be split into ranges, Return `False` otherwise.
"""
start_type = cls._id_range_type(start_pos)
return start_type is not None and start_type is cls._id_range_type(end_pos)

@staticmethod
def _range_is_not_splittable(
start_pos: Union[int, str, ObjectId],
Expand Down
80 changes: 79 additions & 1 deletion sdks/python/apache_beam/io/mongodbio_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@
from apache_beam.testing.util import equal_to


def _bson_sort_key(value):
"""Sort key ordering values of different types as MongoDB does."""
if isinstance(value, (int, float)):
return (0, value)
if isinstance(value, str):
return (1, value)
if isinstance(value, ObjectId):
return (2, value)
raise TypeError('Unsupported type %s' % type(value))


class _MockMongoColl(object):
"""Fake mongodb collection cursor."""
def __init__(self, docs):
Expand Down Expand Up @@ -77,6 +88,9 @@ def _make_filter(conditions):

def func(doc):
for field, op, value in checks:
# Like MongoDB, only compare values of the same type.
if _bson_sort_key(doc[field])[0] != _bson_sort_key(value)[0]:
return False
if not getattr(doc[field], op)(value):
return False
return True
Expand Down Expand Up @@ -116,7 +130,9 @@ def find(self, filter=None, projection=None, **kwargs):
def sort(self, sort_items):
key, order = sort_items[0]
self.docs = sorted(
self.docs, key=lambda x: x[key], reverse=(order != ASCENDING))
self.docs,
key=lambda x: _bson_sort_key(x[key]),
reverse=(order != ASCENDING))
return self

def limit(self, num):
Expand Down Expand Up @@ -594,6 +610,68 @@ def test_read_from_mongodb(self, mock_client):
assert_that(docs, equal_to(projected_documents))


@parameterized_class(('bucket_auto', ), [(False, ), (True, )])
class MixedIdTypesTest(unittest.TestCase):
"""Collections whose _id values are of different types."""
def setUp(self):
self._docs = [
{
'_id': 7, 'x': 0
},
{
'_id': 'abc', 'x': 1
},
{
'_id': 'xyz', 'x': 2
},
{
'_id': OBJECT_IDS[0], 'x': 3
},
{
'_id': OBJECT_IDS[1], 'x': 4
},
]

def _create_source(self, **kwargs):
return _BoundedMongoSource(
'mongodb://test',
'testdb',
'testcoll',
bucket_auto=self.bucket_auto,
**kwargs)

@mock.patch('apache_beam.io.mongodbio.MongoClient')
def test_split_reads_single_bundle(self, mock_client):
mock_client.return_value = _MockMongoClient(self._docs)
source = self._create_source()
bundles = list(source.split(desired_bundle_size=1024 * 1024))
self.assertEqual(1, len(bundles))
self.assertIsNone(bundles[0].start_position)
self.assertIsNone(bundles[0].stop_position)

range_tracker = source.get_range_tracker(None, None)
self.assertIsNone(range_tracker.try_split(2))
self.assertListEqual(self._docs, list(source.read(range_tracker)))

@mock.patch('apache_beam.io.mongodbio.MongoClient')
def test_read_filtered(self, mock_client):
mock_client.return_value = _MockMongoClient(self._docs)
source = self._create_source(filter={'x': 2})
range_tracker = source.get_range_tracker(None, None)
self.assertListEqual([self._docs[2]], list(source.read(range_tracker)))

@mock.patch('apache_beam.io.mongodbio.MongoClient')
def test_read_from_mongodb(self, mock_client):
mock_client.return_value = _MockMongoClient(self._docs)
with TestPipeline() as p:
docs = p | ReadFromMongoDB(
uri='mongodb://test',
db='db',
coll='collection',
bucket_auto=self.bucket_auto)
assert_that(docs, equal_to(self._docs))


class GenerateObjectIdFnTest(unittest.TestCase):
def test_process(self):
with TestPipeline() as p:
Expand Down