我想在 PostgreSQL 的 JSONB 列中存储对象数组。我正在使用 Rails 5.2。我使用自定义序列化程序来确保分配给 JSONB 字段的值是数组而不是哈希。当我向该字段分配类似内容时遇到错误[{a: 1}]。这是代码:
模型:
class Printing
serialize :card_faces, CardFacesSerializer
end
Run Code Online (Sandbox Code Playgroud)
序列化器:
class CardFacesSerializer
include JSONBArraySerializer
def allowed_attributes
%i[name image]
end
end
Run Code Online (Sandbox Code Playgroud)
序列化器关注点:
module JSONBArraySerializer
extend ActiveSupport::Concern
def initialize(data)
return [] if data.blank?
if data.is_a?(String)
json = Oj.load(data, symbol_keys: true)
end
raise ArgumentError, "#{json} must be [{},{}], not {}" if json.is_a?(Hash)
# Will only set the properties that are allowed
json.map do |hash|
hash.slice(self.allowed_attributes)
end
end
class_methods do
def …Run Code Online (Sandbox Code Playgroud) 我希望将 postgres jsonb 列与数组一起使用并能够对它们进行过滤,所以我有一个带有列的模式:
CREATE TABLE testtable
(
id varchar(32) NOT NULL,
refs jsonb NULL,
)
Run Code Online (Sandbox Code Playgroud)
该列包含 Json 格式的数据:
{ "refs": ["one-1-0", "two-3-2", "two-3-4" ] }
Run Code Online (Sandbox Code Playgroud)
我希望能够返回包含以(例如)“two-3-”开头的数组元素的所有行
我已经尝试了几件事,但无法让它按我想要的方式工作(我最接近的是将数组部分作为文本获取并将其作为字符串搜索 - 但这很讨厌)
我还想为此列添加合适的索引以支持此查询。
任何建议都将非常出色并受到热烈欢迎!谢谢
使用 postgresql 10.6。我有一个名为place的表,其中包含城市的 jsonb 字段,其中包含一个 json 数组。我创造了杜松子酒指数。城市 json 数组将有数万条记录。我需要在 where 子句中查询该数组以获取 5000 个城市名称。该查询绝对应该使用 gin 索引来提高性能。正如我在执行计划中看到的那样,下面小提琴中的示例查询没有使用索引。应如何编写此查询以使用索引,使其运行速度更快。
表定义:
CREATE TABLE place (
cities jsonb NULL
);
CREATE INDEX "IX_place_cities" ON place USING gin (cities);
INSERT INTO place
(cities)
VALUES('[{"name": "paris", "continent": "europe"},
{"name": "london", "continent": "europe"},
{"name": "berlin", "continent": "europe"},
{"name": "istanbul", "continent": "europe"},
{"name": "prag", "continent": "europe"},
{"name": "rome", "continent": "europe"},
{"name": "wien", "continent": "europe"},
{"name": "tokyo", "continent": "asia"},
{"name": "beijing", "continent": "asia"},
{"name": "dakar", "continent": …Run Code Online (Sandbox Code Playgroud) (这是Postgresql - Count freuency of array or jsonb object之后的后续问题)
在postgresql12+ 中,给出以下输入行:
输出expected是:
uid tag_freq
1 {'a':2, 'b':1, 'c':1}
2 {'a':1, 'b':2, 'c':2, 'e':1}
...
Run Code Online (Sandbox Code Playgroud)
输出列tag_freq是jsonb对象,它是用户的合并结果。
有没有办法写这样的查询?
我有一个包含两列的表,其中包含 ID 和 JSON 对象 (jsonb)。每个 json 对象都包含多个嵌套在对象内部的值(例如 url)。我可以使用 jsonb_path_query 使用 [*] 提取所有这些值,但它们以每行一个值的形式返回。如何以结果表与原始表具有相同行数的方式聚合返回值?
这是示例:
CREATE TABLE IF NOT EXISTS test (
oid integer,
object jsonb
);
INSERT INTO test
VALUES
(1, '{"links": [
{"title": "a", "url": "w"},
{"title": "b", "url": "x"}
]}'),
(2, '{"links": [
{"title": "c", "url": "y"},
{"title": "d", "url": "z"}
]}');
SELECT
oid,
jsonb_path_query(object, '$.links[*].url')
FROM test;
Run Code Online (Sandbox Code Playgroud)
select 查询返回下表:
| oid | jsonb_path_query |
| --- | ---------------- |
| 1 | w |
| 1 | …Run Code Online (Sandbox Code Playgroud) 我有一个 Kotlin SpringBoot 项目。这是一个相对简单的 API,可将数据保存到 Postgres JsonB 数据库。我@TypeDef在实体类上使用该注释,但升级到此注释后SpringBoot Version 3.0不再hibernate-core:6.1.7.Final
可用。
这是我的实体类::
import com.vladmihalcea.hibernate.type.json.JsonBinaryType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.annotations.Type
import org.hibernate.annotations.TypeDef // not available with latest hibernate-core
import java.io.Serializable
import java.security.SecureRandom
import kotlin.math.abs
@Entity
@Table(name = "myTable")
@TypeDef(name = "jsonb", typeClass = JsonBinaryType::class) // not available :(
data class RecommendationEntity(
@Id
open var id: Long = abs(SecureRandom().nextInt().toLong()),
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
var data: MyModel
)
data class MyModel( …Run Code Online (Sandbox Code Playgroud) 刚刚安装了 9.4 并尝试使用 JSONB 字段类型。
我制作了一个带有 jsonb 字段的表格,并且可以从中进行选择:
select statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as profitable_perc FROM trade_statistics
Run Code Online (Sandbox Code Playgroud)
工作正常。
现在我想根据字段值过滤结果:
select statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as profitable_perc FROM trade_statistics WHERE profitable_perc > 1
//There is no "profitable_perc" column
Run Code Online (Sandbox Code Playgroud)
不起作用。
如果我尝试将结果转换为双精度,也不起作用。
select cast(statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as double precision) as profitable_perc FROM trade_statistics
//cant convert jsonb into double precision
Run Code Online (Sandbox Code Playgroud)
在 jsonb 的情况下,我应该如何在 WHERE 子句中使用选择结果?
我尝试找到一种使用 Postgres 连接 JSONB 值的方法。
例如我有两行:
INSERT INTO "testConcat" ("id", "json_data", "groupID")
VALUES (1, {"name": "JSON_name1", "value" : "Toto"}, 5);
INSERT INTO "testConcat" ("id", "json_data", "groupID")
VALUES (2, {"name": "JSON_name2"}, 5);
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情:
SELECT GROUP_CONCAT(json_data)
FROM testConcat
GROUP BY groupID
Run Code Online (Sandbox Code Playgroud)
并且作为获得类似结果的结果:
[{"name": "JSON_name1", "value": "Toto"}, {"name": "JSON_name2"}]
Run Code Online (Sandbox Code Playgroud)
我尝试创建聚合函数,但是当 JSON 中有相同的键时,它们会被合并并且只保留最后一个值:
DROP AGGREGATE IF EXISTS jsonb_merge(jsonb);
CREATE AGGREGATE jsonb_merge(jsonb) (
SFUNC = jsonb_concat(jsonb, jsonb),
STYPE = jsonb,
INITCOND = '{}'
);
Run Code Online (Sandbox Code Playgroud)
当我在这里使用此功能时:
SELECT jsonb_merge(json_data)
FROM testConcat
GROUP BY groupID
Run Code Online (Sandbox Code Playgroud)
结果是:
{"name": "JSON_name2", …Run Code Online (Sandbox Code Playgroud) 我目前正在寻找例外的解决方案
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist;
Run Code Online (Sandbox Code Playgroud)
我当前的@Query注释是:
@Query(
nativeQuery = true,
value = "SELECT * FROM thgcop_order_placement WHERE \"order_info\" @> '{\"parentOrderNumber\":\" :param \"}'")
Run Code Online (Sandbox Code Playgroud)
我想它position [1] did not exist来自双引号加双引号加单引号。
我该如何进行这项工作?
该查询正在使用Postgres JSONB数据类型。列定义为ORDER_INFO JSONB
以下本地查询在Postgres客户端中可以正常运行:
SELECT * FROM thgcop_order_placement
WHERE "order_info" @> '{"parentOrderNumber":"ORD123"}'
Run Code Online (Sandbox Code Playgroud) jsonb ×9
postgresql ×9
aggregate ×2
activerecord ×1
arrays ×1
group-concat ×1
hibernate ×1
kotlin ×1
spring ×1
spring-boot ×1
sql ×1
upgrade ×1