🚀 Elasticsearch Mapping 一键生成 Proto 文件(支持嵌套 + 注释过滤)
📌 前言
在微服务架构中,越来越多团队开始使用:
👉 gRPC + Protocol Buffers(Proto)
但当你在项目中同时使用 Elasticsearch 时,一个非常现实的问题来了:
👉 如何把 ES Mapping 转成 Proto 定义?
😩 常见开发痛点
假设你有一份 Elasticsearch Mapping:
json
{
// 用户订单
"properties": {
"order": {
"properties": {
"id": { "type": "keyword" },
"amount": { "type": "double" },
"items": {
"type": "nested",
"properties": {
"name": { "type": "text" },
"price": { "type": "double" }
}
}
}
}
}
}
你需要手动写 Proto:
proto
message Item {
string name = 1;
double price = 2;
}
message Order {
string id = 1;
double amount = 2;
repeated Item items = 3;
}
message Document {
Order order = 1;
}
问题是:
- ❌ 字段编号要手动维护(很容易乱)
- ❌ 嵌套结构写起来很复杂
- ❌ Mapping 有注释,JSON 直接解析失败
- ❌ 类型转换不统一
🛠 解决方案
我在 gotool.top 上实现了一个工具:
👉 ES Mapping → Proto 自动生成
并支持:
🔥 嵌套结构解析
🔥 repeated 自动处理
🔥 JSON 注释自动过滤
⚡ 核心能力
✅ 1. 自动生成 message
- 自动生成 Proto message
- 自动处理嵌套结构
- 自动拆分子结构
✅ 2. 自动字段编号(重点)
Proto 中:
proto
string name = 1;
👉 每个字段必须有编号!
工具自动:
- 按顺序编号
- 避免冲突
- 保证规范
✅ 3. nested → repeated
| ES 类型 | Proto 类型 |
|---|---|
| nested | repeated message |
| object | message |
示例:
json
"type": "nested"
👉 自动生成:
proto
repeated Item items = 3;
✅ 4. 类型自动映射
| ES 类型 | Proto 类型 |
|---|---|
| keyword / text | string |
| integer | int32 |
| long | int64 |
| double | double |
| float | float |
| boolean | bool |
| date | string(或 int64 时间戳) |
✅ 5. 自动过滤 JSON 注释(非常关键)
支持:
json
// 单行注释
/* 多行注释 */
👉 直接粘贴 mapping 即可,无需清理!
🔥 一键生成效果
输入 👇
json
{
"properties": {
"user": {
"properties": {
"name": { "type": "keyword" },
"tags": {
"type": "nested",
"properties": {
"label": { "type": "text" }
}
}
}
}
}
}
输出 👇
proto
message Tag {
string label = 1;
}
message User {
string name = 1;
repeated Tag tags = 2;
}
message Document {
User user = 1;
}
类型映射
go
var typeMap = map[string]string{
"keyword": "string",
"integer": "int32",
"long": "int64",
}
💡 使用场景
这个工具非常适合:
- gRPC 微服务开发
- Go / Java 服务通信协议定义
- ES 数据 → RPC 接口
- 数据中台统一协议建模
🚀 为什么这个工具很有价值?
❌ 传统方式
- 手写 proto(极易出错)
- 字段编号难维护
- 嵌套结构复杂
- mapping 不规范直接失败
✅ 使用工具
- 一键生成 ⚡
- 自动编号 💯
- 支持复杂结构 🧠
- 注释自动处理 🔥
🌐 在线体验
搜索:ES Mapping 转 Proto
🏁 总结
一句话总结:
👉 从 ES Mapping 到 Proto,自动生成 + 自动编号 + 自动处理嵌套!