Apache Beam Java MongoDbIO的sink/upsert操作不保留给定的字段顺序是由于MongoDB的特性造成的,它不保证存储文档的字段顺序。如果需要保留字段的顺序,可以将字段序列化为字符串,并在写入MongoDB之前对其进行排序。
以下是一个代码示例,演示如何实现这个解决方法:
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.mongodb.MongoDbIO;
import org.apache.beam.sdk.io.mongodb.MongoDbWriteTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoDbIOExample {
public static void main(String[] args) {
Pipeline pipeline = Pipeline.create();
// 读取PCollection数据
PCollection documents = pipeline.apply(/* 读取数据 */);
// 对每个Document进行字段排序
PCollection sortedDocuments = documents.apply(ParDo.of(new SortFieldsFn()));
// 将排序后的Documents写入MongoDB
sortedDocuments.apply(MongoDbIO.write()
.withUri("mongodb://localhost:27017")
.withDatabase("mydb")
.withCollection("mycollection")
.withBatchSizeBytes(1024)
.withMaxNumRetries(3));
// 运行Pipeline
pipeline.run().waitUntilFinish();
}
public static class SortFieldsFn extends DoFn {
@ProcessElement
public void processElement(ProcessContext c) {
Document input = c.element();
// 获取Document的所有字段名称
List fieldNames = new ArrayList<>(input.keySet());
// 对字段名称进行排序
fieldNames.sort(String::compareTo);
// 构建排序后的Document
Document sortedDoc = new Document();
for (String fieldName : fieldNames) {
sortedDoc.append(fieldName, input.get(fieldName));
}
// 输出排序后的Document
c.output(sortedDoc);
}
}
}
在上述代码中,我们首先通过ParDo
转换使用SortFieldsFn
对每个Document
进行字段排序。然后,我们使用MongoDbIO.write()
将排序后的Document
数据写入MongoDB。
请注意,由于MongoDB的特性,即使排序了字段,MongoDB也不能保证存储文档的字段顺序。因此,即使在写入MongoDB之前对字段进行排序,读取文档时字段的顺序也可能发生变化。