Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MongoDB: More ad hoc fixes for supporting real-world data #255

Merged
merged 12 commits into from
Sep 10, 2024
Merged

Conversation

amotl
Copy link
Member

@amotl amotl commented Sep 2, 2024

About

  • Add support for UUID types.
  • Improve reading timestamps in previous BSON formats like end_date: Long('1455141600000').
  • Make ctk load table use the data OBJECT(DYNAMIC) mapping strategy.
  • Add relevant end-to-end integration test.
  • Sanitize lists of varying objects.
  • Add --treatment option for applying special treatments to certain items on real-world data.
  • Improve Zyp Transformations (--transformation option) for applying special treatments to certain items on real-world data.
  • Use pagination on source collection, for creating batches towards CrateDB.
  • Unlock importing MongoDB Extended JSON files using file+bson://....

Documentation

https://cratedb-toolkit--255.org.readthedocs.build/io/mongodb/loader.html

Install

pip install --upgrade 'cratedb-toolkit[mongodb] @ git+https://github.com/crate/cratedb-toolkit.git@mongodb-more'

Backlog

  • Add relevant software tests.
  • Documentation. For example, parameter batch-size.

/cc @hlcianfagna, @hammerhead, @lservini, @zolbatar, @juanpardo, @widmogrod

Comment on lines 68 to 75
if isinstance(value, dict):
if len(value) == 1:
if "$binary" in value and value["$binary"]["subType"] in ["03", "04"]:
decoded = UUID(bytes=base64.b64decode(value["$binary"]["base64"]))
return extract_value(decoded, parent_type)
for k, v in value.items():
if k.startswith("$"):
return extract_value(v, k.lstrip("$"))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure enough, decoding MongoDB Extended JSON should not be performed manually, but should use _json_convert instead, like the CDC subsystem is doing it already.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Through decode_bson, the machinery now uses BSON's _json_convert.

# Converge multiple MongoDB documents into SQL parameters for `executemany` operation.
parameters: t.List[DocumentDict] = []
for document in data:
record = self.converter.convert(self.decode_bson(document))
oid: str = self.get_document_key(record)
parameters.append({"oid": oid, "record": record})
return SQLOperation(sql, parameters)

cratedb_toolkit/io/mongodb/extract.py Show resolved Hide resolved
Comment on lines 36 to 65
DOCUMENT_IN = {
"id": bson.Binary.from_uuid(UUID("d575540f-759d-4653-a4c4-4a9e410f1aa1")),
"value": {
"name": "foobar",
"active": True,
"created": dateutil.parser.parse("2020-06-19T15:03:53.727Z"),
"timestamp": bson.datetime_ms.DatetimeMS(1455141600000),
},
}
DOCUMENT_OUT = {
"__id": mock.ANY,
"id": "d575540f-759d-4653-a4c4-4a9e410f1aa1",
"value": {
"name": "foobar",
"active": True,
"created": 1592579033000,
"timestamp": 1455141600000,
},
}
DOCUMENT_DDL = """
CREATE TABLE IF NOT EXISTS "testdrive"."demo" (
"__id" TEXT,
"id" TEXT,
"value" OBJECT(DYNAMIC) AS (
"name" TEXT,
"active" BOOLEAN,
"created" TIMESTAMP WITH TIME ZONE,
"timestamp" TIMESTAMP WITH TIME ZONE
)
)""".lstrip()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Best view into the integration test added with bf78869 and 249cac1.

@amotl amotl force-pushed the mongodb-more branch 15 times, most recently from 66399b9 to c899a30 Compare September 4, 2024 00:08
Copy link

@wierdvanderhaar wierdvanderhaar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets a go.

@amotl amotl force-pushed the mongodb-more branch 6 times, most recently from 7c8e999 to bc9362b Compare September 5, 2024 08:13
Comment on lines 152 to 164
"""
# Manual treatment.
# Some nested objects have been defined as strings, probably in previous schema versions.
if "users" in value:
for user_item in value["users"]:
if "user" in user_item and not isinstance(user_item["user"], dict):
user_item["user"] = {"id": user_item["user"]}
"""

if "createdBy" in value and not isinstance(value["createdBy"], dict):
value["createdBy"] = {"id": value["createdBy"]}

# Prune invalid date representations.
for key in ["start_date", "end_date"]:
if key in value:
if not isinstance(value[key], dict):
del value[key]
elif "date" in value[key]:
if isinstance(value[key]["date"], str):
del value[key]
Copy link
Member Author

@amotl amotl Sep 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While others are configurable per --treatment=Path option using a corresponding YAML file now, those three special treatments have not been generalized yet.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those rules now have been generalized further to be controlled using the treatment file.

convert_dict:
  - name: createdBy
    wrapper_name: id
  - name: user
    wrapper_name: id
prune_invalid_date:
  - "start_date"
  - "end_date"

Copy link
Member Author

@amotl amotl Sep 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The --treatment option has been dissolved again. Special treatments have been integrated into Zyp.

zyp-treatment-all.yaml is an example file representing a Zyp project that includes definitions of special treatments for a specific collection.

@amotl amotl force-pushed the mongodb-more branch 2 times, most recently from 6ec4aab to 5802e19 Compare September 6, 2024 08:24
pyproject.toml Outdated
Comment on lines 162 to 164
"commons-codec[mongodb,zyp]>=0.0.14",
"commons-codec[mongodb,zyp] @ git+https://github.com/crate/commons-codec@zyp-treatments",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, this needs another release of commons-codec beforehand.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

commons-codec v0.0.15 has been released.

-- https://pypi.org/project/commons-codec/

@amotl amotl marked this pull request as ready for review September 10, 2024 13:23
@amotl amotl mentioned this pull request Sep 10, 2024
8 tasks
... to use double leading underscores.
bson.errors.InvalidBSON: year 292278994 is out of range

Consider Using CodecOptions(datetime_conversion=DATETIME_AUTO) or MongoClient(datetime_conversion='DATETIME_AUTO').

See: https://pymongo.readthedocs.io/en/stable/examples/datetimes.html#handling-out-of-range-datetimes
By default, assume `TEXT` as inner type.
This means relevant column definitions will not be included into the
SQL DDL.
- Use `--transformation` option for applying special treatments.
  Certain fields should be stored as lists, some need to be ignored for
  now, others need to be treated manually, etc.

- Use pagination on source collection, for creating batches towards
  CrateDB.
@amotl amotl merged commit 8fc1a22 into main Sep 10, 2024
31 checks passed
@amotl amotl deleted the mongodb-more branch September 10, 2024 17:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants