新的 pg hstore 看起来棒极了
http://www.postgresql.org/docs/devel/static/hstore.html
但是好像不像MongoDB那样支持原子递增?
db.mycoll.update({mykey: myval}, {my_counter: {$inc: 1}})
如何使用 PostgreSQL Hstore 做到这一点?
最佳答案
MongoDB 需要一个 $inc
运算符,因为:
- 如果没有特定的低级支持,MongoDB 中的原子操作会很困难。
- 接口(interface)不够丰富,无法在没有特殊运算符的情况下表达
c = c + 1
。
你只需要用 hstores 表达 c = c + 1
。这个任务有点复杂,因为 hstores 对键和值都使用字符串,这会让你的转换变得一团糟。我认为您遇到了这样令人讨厌的事情:
update t
set h = h || hstore('my_counter', ((h -> 'my_counter')::integer + 1)::text)
where mykey = myval
(h -> 'my_counter')::integer + 1
通过提取值 (h -> 'my_counter'
) 进行递增,将其转换为一个整数,然后加一。然后你用 hstore('my_counter', ...)
和一个显式的 ::text
构建一个元素 hstore 来确保 PostgreSQL 知道你使用哪个函数想。最后,您使用 h || 将新键值连接到原始 hstore hstore(...)
替换旧值。
如果你不想一直使用那种有点讨厌的困惑,那么你可以将它包装成一个简单的函数并说:
update t
set h = hstore_inc(h, 'my_counter', 1)
where ...
隐藏脏话。
我确信还有其他方法可以做到这一点(也许使用各种 to/from array 函数)但上面的方法应该有效。
关于postgresql - 在 PostgreSQL hstore 中以原子方式递增,就像 MongoDB 中的 $inc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849778/