英文:
Ordering of Protobuf maps
问题
我正在创建 proto3 中的消息对象,并使用自动生成的 Java 类。
我想为每个消息对象分配唯一的键。
message Obj {
    ...
    string unique_key = 1;
    ...
}
在构建 Obj 时,它会从一个微服务接收一个名为 metaData 的 proto 对象,其定义如下:
message metaData {
     map<string, string> keyFields = 1;
}
根据 metaData 对象中的条目,unique_key 是通过迭代映射并对每个条目进行哈希运算来创建的。(keyFields 中最多有 10 个条目)
Protobuf 文档说,无法定义键的排序。我应该如何确保具有相同 keyFields 条目的不同 metaData 对象生成相同的 unique_key?
英文:
I am creating message objects in proto3 and using auto-generated java classes.
I want to have unique key assigned to each of the message object.
message Obj {
    ...
    string unique_key = 1;
    ...
}
During construction of Obj, it receives from a microservice, a proto object called metaData, which is defined as follows:
message metData {
     map<string, string> keyFields = 1;
}
Based on entries in metaData object, unique_key is created by iterating over the map and hashing each of the entries.(There are upto 10 entries in keyFields)
The protobuf documentation says, the ordering of keys can't be defined. How should I guarantee that different metaData objects with same entries in keyFields generate same unique_key?
答案1
得分: 2
你有两个一般选项:
- 实现一个可交换的哈希函数。例如,获取键的哈希值,然后简单地将它们相加,忽略溢出。
 - 获取键并对它们进行排序。然后对排序后的键进行哈希。如果有“许多”键,考虑缓存哈希值。
 
英文:
You have two options in general:
- Implement a commutative hash function. E.g. get the hashes of the keys and simply sum them ignoring overflow.
 - Get the keys and sort them. Then hash them sorted. If there are "many" keys, consider caching the hash value.
 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论