查询 JSON 数据
Oracle
-- Extract a scalar value with JSON_VALUE:
SELECT JSON_VALUE(data, '$.customer.city') AS city FROM orders;
-- Expand into rows with JSON_TABLE:
SELECT t.product, t.quantity
FROM orders s,
JSON_TABLE(s.data, '$.items[*]'
COLUMNS (product VARCHAR2(50) PATH '$.product',
quantity NUMBER PATH '$.quantity')) t;Oracle(12c+)通过 SQL/JSON 路径表达式查询 JSON 数据。JSON_VALUE 返回单个标量值,JSON_QUERY 返回对象/数组片段,JSON_TABLE 将 JSON 转换为关系型行列结构。21c+ 支持原生 JSON 数据类型。
PostgreSQL
-- jsonb operators:
SELECT data->'customer'->>'city' AS city FROM orders;
-- Containment (@>) and a GIN index:
CREATE INDEX ix ON orders USING GIN (data);
SELECT * FROM orders
WHERE data @> '{"status": "approved"}';PostgreSQL jsonb 类型提供丰富的运算符:->(json 对象/元素)、->>(文本值)、#>(路径)、@>(包含)、?(键存在)。GIN 索引可加速 @> 和 ? 查询。也可以通过 jsonb_path_query 进行 SQL/JSON 路径查询。
MySQL
-- JSON_EXTRACT or shorthand operators:
SELECT JSON_EXTRACT(data, '$.customer.city') AS city FROM orders;
-- ->> returns unquoted text:
SELECT data->>'$.customer.city' AS city FROM orders
WHERE data->>'$.status' = 'approved';MySQL(5.7+)使用 JSON_EXTRACT() 查询原生 JSON 类型;-> 运算符是 JSON_EXTRACT 的简写,->> 是 JSON_UNQUOTE(JSON_EXTRACT()) 的简写。对 JSON 字段的搜索可通过生成列 + 索引加速。
SQL Server
-- Extract a scalar value with JSON_VALUE:
SELECT JSON_VALUE(data, '$.customer.city') AS city FROM orders;
-- Expand into rows with OPENJSON:
SELECT k.product, k.quantity
FROM orders s
CROSS APPLY OPENJSON(s.data, '$.items')
WITH (product NVARCHAR(50) '$.product', quantity INT '$.quantity') k;SQL Server(2016+)将 JSON 存储在 NVARCHAR 列中。JSON_VALUE 返回标量值,JSON_QUERY 返回对象/数组,OPENJSON 将 JSON 转换为表格形式。ISJSON() 用于验证。对 JSON 路径的查找可通过计算列 + 索引加速。
MongoDB
// MongoDB is natively a document (BSON/JSON) database.
// Access nested fields with dot notation:
db.orders.find({ "customer.city": "Ankara" })
// Array element and projection:
db.orders.find(
{ "items.product": "pen" },
{ "items.$": 1 }
)MongoDB 将所有数据存储为文档(类 JSON 的 BSON);查询是原生的。点号表示法可访问嵌套字段和数组元素。复杂转换通过 Aggregation Pipeline 完成,索引可实现对嵌套字段的快速查找。
Redis
# Requires the RedisJSON module (Redis Stack).
# Write a JSON document:
JSON.SET order:1 $ '{"customer":{"city":"Ankara"},"status":"approved"}'
# Read a value with JSONPath:
JSON.GET order:1 $.customer.city核心 Redis 没有 JSON 类型;RedisJSON 模块(Redis Stack)通过 JSON.SET/JSON.GET 提供基于 JSONPath 的读写。与 RediSearch 结合可对 JSON 文档进行索引和查询。没有该模块时,JSON 以字符串存储并在应用中解析。
Elasticsearch
# Documents are already JSON; query fields directly:
GET orders/_search
{ "query": { "term": { "customer.city": "Ankara" } } }
# For nested arrays, use the nested type and a nested query:
GET orders/_search
{ "query": { "nested": { "path": "items",
"query": { "match": { "items.product": "pen" } } } } }Elasticsearch 以 JSON 原生存储和索引文档。要在嵌套对象数组中保留元素边界,使用 'nested' 字段类型和 nested 查询;否则 object 类型的数组会被扁平化(存在交叉匹配风险)。object 与 nested 的区别对结果正确性至关重要。