ERP/shipments_redis_structure.md

101 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 发货记录 Redis 存储结构说明
## Redis 数据结构
### Hash 表shipment_sn_mapping
用于存储 SN/MAC 到出货信息的映射关系。
**数据类型**: Redis Hash
**Key**: `shipment_sn_mapping`
**结构**:
```
Hash Key (Field) -> Hash Value
SN/MAC 号 -> JSON 格式的出货信息
```
### 存储示例
```redis
HSET shipment_sn_mapping "SN0001" '{"date":"2025-11-20","box":"BOX001","ts":"2025-11-20T10:30:00"}'
HSET shipment_sn_mapping "SN0002" '{"date":"2025-11-20","box":"BOX001","ts":"2025-11-20T10:30:00"}'
HSET shipment_sn_mapping "SN0021" '{"date":"2025-11-20","box":"BOX002","ts":"2025-11-20T10:30:00"}'
```
### JSON 值格式
```json
{
"date": "2025-11-20", // 出货日期
"box": "BOX001", // 箱号
"ts": "2025-11-20T10:30:00" // 记录时间戳
}
```
## 查询方式
### 1. 通过 API 查询
**接口**: `GET /api/shipments/query-by-sn?sn=SN0001`
**响应示例**:
```json
{
"found": true,
"sn": "SN0001",
"date": "2025-11-20",
"box": "BOX001",
"ts": "2025-11-20T10:30:00"
}
```
### 2. 直接使用 Redis 命令查询
```bash
# 查询单个 SN
redis-cli HGET shipment_sn_mapping "SN0001"
# 查询多个 SN
redis-cli HMGET shipment_sn_mapping "SN0001" "SN0002" "SN0003"
# 查看所有记录数量
redis-cli HLEN shipment_sn_mapping
# 查看所有 SN谨慎使用数据量大时会很慢
redis-cli HKEYS shipment_sn_mapping
# 扫描部分数据
redis-cli HSCAN shipment_sn_mapping 0 COUNT 100
```
## 数据导入流程
1. 用户上传 Excel 文件包含出货日期、箱号、SN1-SN20
2. 系统解析 Excel 文件
3. 提取每行的出货日期、箱号和所有 SN
4. 将数据保存到 SQLite用于统计和列表展示
5. 同时将每个 SN 映射关系写入 Redis Hash用于快速查询
## 性能特点
- **查询速度**: O(1) 时间复杂度,毫秒级响应
- **存储效率**: Hash 结构比单独的 Key-Value 更节省内存
- **批量写入**: 使用 Pipeline 批量写入,提高导入速度
- **容错性**: Redis 写入失败不影响 SQLite 数据保存
## 使用场景
1. **快速查询**: 扫描 SN 后立即查询出货信息
2. **追溯管理**: 根据 MAC 地址追溯出货批次
3. **质量追踪**: 结合不良品记录,追溯出货批次
4. **客户服务**: 快速响应客户关于产品出货信息的查询
## 维护建议
1. **定期备份**: 使用 Redis RDB 或 AOF 持久化
2. **监控容量**: 定期检查 Hash 大小 `HLEN shipment_sn_mapping`
3. **数据清理**: 根据业务需求定期清理过期数据
4. **索引优化**: 如需按日期或箱号查询,可建立额外的索引结构