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
11 changes: 11 additions & 0 deletions docs/docs/cdc-ingestion/mongo-cdc.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ The action uses `_id` to identify records. Updates carry the resulting document,
events may contain only the document identity, so other document fields cannot replace `_id`
as the record key.

Partition keys have the same limitation. A delete, and the retraction written for an update or a
replace, carries only the document key (`_id`, plus the shard key of a sharded collection), so its
other fields are NULL. If a partition key is another document field, or a computed column of one,
the retraction goes to the default partition and misses the stored row: a deleted document stays
in the table, and a document whose partition value changes keeps its old row next to the new one.
By default the primary key is `_id` alone, so such a table cannot use the default `bucket = -1`;
set a fixed `bucket`. A computed column of `_id` does not have this problem, because it is
computed from `_id` again. All of this applies to `mongodb_sync_database` too. There, adding the
partition key to `--primary_keys` does not help: the NULL partition value then fails the job at the
first delete, update or replace.

| `--mongodb_conf` option | Behavior |
| --- | --- |
| `schema.start.mode=dynamic` (default) | Infer the initial fields from the first document in the collection. The collection must contain a document when starting the table action. Add new top-level fields as they appear; nested values remain within their source fields. |
Expand Down
2 changes: 1 addition & 1 deletion docs/generated/mongodb_sync_database.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
<tr>
<td><h5>--partition_keys</h5></td>
<td>The partition keys for Paimon table. If there are multiple partition keys, connect them with comma, for example "dt,hh,mm".
If the keys are not in source table, the sink table won't set partition keys.</td>
If the keys are not in source table, the sink table won't set partition keys. Deletes carry only the document key (<code>_id</code>, plus the shard key of a sharded collection), so with the default primary key and a partition key on another document field, a deleted document or a document whose partition value changes keeps a stale row in its old partition. See <a href="#schema-and-document-identity">Schema and Document Identity</a>.</td>
</tr>
<tr>
<td><h5>--primary_keys</h5></td>
Expand Down
2 changes: 1 addition & 1 deletion docs/generated/mongodb_sync_table.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
</tr>
<tr>
<td><h5>--partition_keys</h5></td>
<td>The partition keys for Paimon table. If there are multiple partition keys, connect them with comma, for example "dt,hh,mm".</td>
<td>The partition keys for Paimon table. If there are multiple partition keys, connect them with comma, for example "dt,hh,mm". Deletes carry only the document key (<code>_id</code>, plus the shard key of a sharded collection), so with the default primary key and a partition key on another document field, a deleted document or a document whose partition value changes keeps a stale row in its old partition. See <a href="#schema-and-document-identity">Schema and Document Identity</a>.</td>
</tr>
<tr>
<td><h5>--computed_column</h5></td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import org.apache.flink.configuration.Configuration;

import java.util.Collections;
Expand Down Expand Up @@ -138,7 +139,15 @@ static Map<String, String> parseFieldsFromJsonRecord(
Map<String, String> parsedRow = new HashMap<>();

for (int i = 0; i < parseNames.length; i++) {
Object evaluate = JsonPath.read(record, parseNames[i]);
Object evaluate;
try {
evaluate = JsonPath.read(record, parseNames[i]);
} catch (PathNotFoundException e) {
// A delete or update event carries only the _id of the document, and a document
// does not have to contain every configured field.
parsedRow.put(columnNames[i], null);
continue;
}
String stringValue = evaluate != null ? evaluate.toString() : null;
parsedRow.put(columnNames[i], Optional.ofNullable(stringValue).orElse("{}"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,56 @@ public void testComputedColumn() throws Exception {
Collections.singletonList("_id"));
}

@Test
@Timeout(60)
public void testSpecifiedModeCDCOperations() throws Exception {
String mongoDatabase = createRecordsToMongoDB("event-insert", "table/event");

Map<String, String> mongodbConfig = getBasicMongoDBConfig();
mongodbConfig.put("database", mongoDatabase);
mongodbConfig.put("collection", "event");
mongodbConfig.put("field.name", "_id,name,description");
mongodbConfig.put("parser.path", "$._id,$.name,$.description");
mongodbConfig.put("schema.start.mode", "specified");

MongoDBSyncTableAction action =
syncTableActionBuilder(mongodbConfig)
.withTableConfig(getBasicTableConfig())
.build();
JobClient client = runActionWithDefaultEnv(action);

FileStoreTable table = getFileStoreTable(tableName);
List<String> primaryKeys = Collections.singletonList("_id");
RowType rowType =
RowType.of(
new DataType[] {
DataTypes.STRING().notNull(), DataTypes.STRING(), DataTypes.STRING()
},
new String[] {"_id", "name", "description"});
waitForResult(
client,
Arrays.asList(
"+I[100000000000000000000101, scooter, Small 2-wheel scooter]",
"+I[100000000000000000000102, car battery, 12V car battery]",
"+I[100000000000000000000103, 12-pack drill bits, 12-pack of drill bits with sizes ranging from #40 to #3]"),
table,
rowType,
primaryKeys);

// Update, replace and delete events carry only the _id in their document key.
writeRecordsToMongoDB("event-update", mongoDatabase, "table/event");
writeRecordsToMongoDB("event-replace", mongoDatabase, "table/event");
writeRecordsToMongoDB("event-delete", mongoDatabase, "table/event");
waitForResult(
client,
Arrays.asList(
"+I[100000000000000000000101, scooter, Updated scooter description]",
"+I[100000000000000000000102, new car battery, New 12V car battery]"),
table,
rowType,
primaryKeys);
}

@Test
@Timeout(60)
public void testMongoDBCDCOperations() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/

package org.apache.paimon.flink.action.cdc.mongodb.strategy;

import org.apache.paimon.flink.sink.cdc.CdcRecord;
import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
import org.apache.paimon.flink.sink.cdc.RichCdcRecord;
import org.apache.paimon.types.RowKind;
import org.apache.paimon.utils.JsonSerdeUtil;

import org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;

import org.apache.flink.configuration.Configuration;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.paimon.flink.action.cdc.mongodb.MongoDBActionUtils.FIELD_NAME;
import static org.apache.paimon.flink.action.cdc.mongodb.MongoDBActionUtils.PARSER_PATH;
import static org.apache.paimon.flink.action.cdc.mongodb.MongoDBActionUtils.START_MODE;
import static org.assertj.core.api.Assertions.assertThat;

/** Test for {@link Mongo4VersionStrategy}. */
class Mongo4VersionStrategyTest {

private static final String ID = "{\"_id\": {\"$oid\": \"507f1f77bcf86cd799439011\"}}";
private static final String DOCUMENT =
"{\"_id\": {\"$oid\": \"507f1f77bcf86cd799439011\"}, \"name\": \"scooter\"}";

@Test
void testSpecifiedModeDelete() throws Exception {
List<CdcRecord> records = extract(changeEvent("delete", null, ID));

assertThat(records).hasSize(1);
assertThat(records.get(0).kind()).isEqualTo(RowKind.DELETE);
assertThat(records.get(0).data())
.containsEntry("_id", "507f1f77bcf86cd799439011")
.containsEntry("name", null);
}

@Test
void testSpecifiedModeUpdate() throws Exception {
List<CdcRecord> records = extract(changeEvent("update", DOCUMENT, ID));

assertThat(records)
.extracting(CdcRecord::kind)
.containsExactly(RowKind.DELETE, RowKind.INSERT);
assertThat(records.get(1).data())
.containsEntry("_id", "507f1f77bcf86cd799439011")
.containsEntry("name", "scooter");
}

@Test
void testSpecifiedModeInsertWithoutConfiguredField() throws Exception {
List<CdcRecord> records = extract(changeEvent("insert", ID, ID));

assertThat(records).hasSize(1);
assertThat(records.get(0).data()).containsEntry("name", null);
}

private static List<CdcRecord> extract(JsonNode root) throws Exception {
Configuration config = new Configuration();
config.set(START_MODE, "specified");
config.set(FIELD_NAME, "_id,name");
config.set(PARSER_PATH, "$._id,$.name");
return new Mongo4VersionStrategy("db", "coll", Collections.emptyList(), config)
.extractRecords(root).stream()
.map(RichCdcMultiplexRecord::toRichCdcRecord)
.map(RichCdcRecord::toCdcRecord)
.collect(Collectors.toList());
}

private static JsonNode changeEvent(String op, String fullDocument, String documentKey) {
ObjectNode root = JsonSerdeUtil.OBJECT_MAPPER_INSTANCE.createObjectNode();
root.put("operationType", op);
if (fullDocument != null) {
root.put("fullDocument", fullDocument);
}
root.put("documentKey", documentKey);
return root;
}
}
Loading