Key in map fields cannot be float/double, bytes or message types
Asked Answered
N

1

5

We are planning to move our existing services to move grpc service. so need to convert the services to proto Defined Message Type. In the reponse, we have map with customize object as key.

eg response:

 //java
 Map<key_object, Project>

//proto
map<key_object_not_supported, Project> projects = 3;

In the official doc, they mentioned,

where the key_type can be any integral or string type (so, any scalar type except for floating point types and bytes). The value_type can be any type

Is it any alternative ways to achieve customise object key map in the proto3 ?

Norway answered 7/9, 2016 at 6:10 Comment(0)
O
11

Support for map is a rather new extension. If your key does not match the constraints, you can use the old way instead:

Define a key-pair message and use that as a repeated field. So, in your example:

message KeyValuePair {
  key_object_not_supported key = 1;
  Project value = 2;
}

message MyMap {
  repeated KeyValuePair entries = 1;
}
Ovenware answered 12/9, 2016 at 16:35 Comment(1)
Official recommendation from Google can be found here: developers.google.com/protocol-buffers/docs/proto3#maps. Also, this syntax doesn't seem to allow convenient #get semantics you'd expect from any map, and thus it offers O(n) instead of O(1) access performance.Witchcraft

© 2022 - 2025 — McMap. All rights reserved.