Redis中支持按字段增删改的天气预报JSON存储结构选型咨询
推荐Redis数据结构及操作方案
最优选择:Hash 结构(兼容性最高,无需额外模块)
你的场景下用Redis原生Hash结构就能完美满足需求,几万条数据量级对于Redis来说完全没有性能压力,具体实现可以按如下规则设计:
为每个城市单独分配一个Hash类型的key,命名规则建议为weather:city:{城市名},Hash的每个field对应你JSON结构中的字段(city、weather、lastPrediction、source)。
对应操作的实现命令
- 新增/覆盖整条城市天气预报
HSET weather:city:London city "London" weather "SUNNY" lastPrediction "2024-05-20 12:00:00" source "China Meteorological Administration"
- 按城市名查询整条天气预报
HGETALL weather:city:London
- 按城市名更新单个指定字段(比如更新伦敦的天气为雨天)
HSET weather:city:London weather "RAINY"
- 按城市名删除单个指定字段(比如删除source字段)
HDEL weather:city:London source
- 按城市名删除整条天气预报
DEL weather:city:London
可选进阶方案:RedisJSON(需要服务端支持RedisJSON模块)
如果你的Redis实例已经安装了RedisJSON模块,也可以选择该结构,原生支持JSON格式存储,无需手动拆分字段,更适合后续有复杂JSON操作的场景:
对应操作的实现命令
- 新增/覆盖整条城市天气预报
JSON.SET weather:city:London $ '{"city":"London","weather":"SUNNY","lastPrediction":"2024-05-20 12:00:00","source":"China Meteorological Administration"}'
- 按城市名查询整条天气预报
JSON.GET weather:city:London $
- 按城市名更新单个指定字段
JSON.SET weather:city:London $.weather '"RAINY"'
- 按城市名删除单个指定字段
JSON.DEL weather:city:London $.source
- 按城市名删除整条天气预报
DEL weather:city:London
内容的提问来源于stack exchange,提问作者pixel
相关产品推荐
相关产品推荐

