【发布时间】:2022-01-22 00:31:27
【问题描述】:
以下是我的示例 JSONB 数据,其中包含少量元素。我在这个专栏上有一个杜松子酒索引。
{
"customer_data": {
"name": "abc",
"country": [
"xyz",
"abc",
"def"
],
"account_details": [
{
"account_id": 1016084,
"account_branch": "xyz",
"account_balance": 2000,
"transaction_dates": [
20180125,
20190125,
20200125,
20200525
]
},
{
"account_id": 1016087,
"account_branch": "abc",
"account_balance": 12010,
"transaction_dates": [
20180125,
20190125,
20200125
]
}
],
"incorporated_year": 2020
}
}
JSONB 国家属性是一个数组。在应用程序中,此列是多选。如果 jsonb 中国家/地区数组中的任何值与任何输入国家/地区值匹配(如 SQL 查询中的 IN 条件),我需要选择数据。我从应用程序以逗号分隔的形式获取输入,该输入使用 string_to_array 并基于与 jsonb 列的匹配进行拆分。除了国家,其他过滤器也通过了。所有这些我结合起来并动态地形成了总过滤标准。如果它与通过的过滤器匹配,我想返回该行。
所以我尝试将 JSONB 中的国家/地区数组属性与传入的输入进行匹配。
以下查询有效。但我觉得它会很慢,因为我需要动态添加其他过滤器并认为将其作为单个表达式来做会更快
SELECT *
FROM customer_data_ms.test_customer
WHERE customer_Details -> 'customer_data' -> 'country'
?| array['xyz','gkl','jkl']
我希望选择任何值为“xyz”或“gkl”或“jkl”的行。我想将它作为总表达式的一部分包含在内,因为我还将拥有其他过滤条件并尝试以下方式。
SELECT *
FROM customer_data_ms.test_customer
WHERE customer_Details @? '$.customer_data.country ?| array[''xyz'',''gkl'',''jkl'']'
SELECT *
FROM customer_data_ms.test_customer
WHERE customer_Details @? '$.customer_data.country ?| (array[''xyz'',''gkl'',''jkl''])'
ERROR: syntax error, unexpected $undefined, expecting '(' at or near "|" of jsonpath input
LINE 2: customer_Details @? '$.customer_data.country ?| array[''xyz'...
我正在努力将数组与输入数组进行比较。任何指导都会有很大帮助。
【问题讨论】:
-
不要使用 JSON 对此类数据进行建模。使用标准化数据模型。
标签: arrays postgresql query-optimization jsonb