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

Include sharding key if it is available in the document #102

Merged
merged 1 commit into from
Oct 23, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,37 @@ internal data class InsertReplaceChangeEvent(

fun fromMongoChangeStreamDocument(
changeStreamDocument: ChangeStreamDocument<BsonDocument>,
shardingKey: String?
): InsertReplaceChangeEvent =
InsertReplaceChangeEvent(
changeStreamDocument.operationType,
upsertKey(changeStreamDocument.documentKey!!, shardingKey),
shardingKey: String?,
): InsertReplaceChangeEvent {
val documentFromEvent =
changeStreamDocument.fullDocument?.toBsonDocument(
BsonDocument::class.java,
codecRegistry
codecRegistry,
)

return InsertReplaceChangeEvent(
changeStreamDocument.operationType,
upsertKey(changeStreamDocument.documentKey!!, shardingKey, documentFromEvent),
documentFromEvent,
)
}

// This addresses "Failed to target upsert by query :: could not extract exact shard key" error for sharded destination collections
// https://www.mongodb.com/docs/manual/reference/method/db.collection.update/#sharded-collections
private fun upsertKey(documentKey: BsonDocument, shardingKey: String?): BsonDocument {
if (shardingKey == null) return documentKey // When no shardingKey, don't change documentKey
if (documentKey.containsKey(shardingKey)) return documentKey // When sharding key is already in documentKey, don't change documentKey
return documentKey.append(shardingKey, BsonNull.VALUE) // When there is no shardingKey, add "shardingKey: null" to documentKey
private fun upsertKey(
documentKey: BsonDocument,
shardingKey: String?,
documentFromEvent: BsonDocument?,
): BsonDocument {
// When no shardingKey, don't change documentKey
if (shardingKey == null) return documentKey
// When sharding key is already in documentKey, don't change documentKey
if (documentKey.containsKey(shardingKey)) return documentKey
// When destination collection is sharded, and there is no shardingKey, add "shardingKey: <value>" to documentKey
return documentKey.append(
shardingKey,
documentFromEvent?.get(shardingKey, BsonNull.VALUE) ?: BsonNull.VALUE,
)
}
}

Expand Down
Loading