我在 Postgres 9.4.1 中有两个表,events
并event_refs
具有以下模式:
events
桌子
CREATE TABLE events (
id serial NOT NULL PRIMARY KEY,
event_type text NOT NULL,
event_path jsonb,
event_data jsonb,
created_at timestamp with time zone NOT NULL
);
-- Index on type and created time
CREATE INDEX events_event_type_created_at_idx
ON events (event_type, created_at);
Run Code Online (Sandbox Code Playgroud)
event_refs
桌子
CREATE TABLE event_refs (
event_id integer NOT NULL,
reference_key text NOT NULL,
reference_value text NOT NULL,
CONSTRAINT event_refs_pkey PRIMARY KEY (event_id, reference_key, reference_value),
CONSTRAINT event_refs_event_id_fkey FOREIGN KEY (event_id) …
Run Code Online (Sandbox Code Playgroud) postgresql performance execution-plan group-by postgresql-9.4 postgresql-performance
在我的 API 中,当存在具有该唯一键的行时,用户可能会发送一个尝试创建新行的请求。
目前,我正在捕获唯一键错误并返回一条消息,指出 X 已存在。但是,首先查找该行(在同一连接上)并且仅在该行不存在时才运行 INSERT 语句是否会更高效?
我的直觉告诉我,从 PostgreSQL 读取错误应该会更有效,但我想确保我正在按照惯用的方式做事。
PostgreSQL 版本为 12
我的 API 中的唯一键不是代理 ID 值,它是由外键与文本值组合而成的组合。如果唯一键约束没有失败,数据库确实已经为此行生成了自己的代理 ID 。所以该行的 ID 不是我要检查的内容。正确的行为是不插入行,因为 FK/文本值在表中需要是唯一的。如果请求包含表中已存在的 FK/文本值,则不应插入任何行。
我有一个大约 3.25M 行的表格,在 Postgres 9.4.1 中遵循以下格式
CREATE TABLE stats
(
id serial NOT NULL,
type character varying(255) NOT NULL,
"references" jsonb NOT NULL,
path jsonb,
data jsonb,
"createdAt" timestamp with time zone NOT NULL,
CONSTRAINT stats_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
Run Code Online (Sandbox Code Playgroud)
本type
是一个简单的字符串长度不超过50个字符。
该references
列是一个带有键值列表的对象。基本上任何简单的键值列表,只有 1 级深,值总是字符串。它可能是
{
"fruit": "plum"
"car": "toyota"
}
Run Code Online (Sandbox Code Playgroud)
或者它可能是
{
"project": "2532"
}
Run Code Online (Sandbox Code Playgroud)
该createdAt
时间戳并不总是从数据库中生成的(但它会默认如果值不被提供)
我目前使用的表格只有测试数据。在此数据中,每一行都有一个project
键作为参考。所以有 3.25M 行有一个项目键。project
引用正好有 400,000 个不同的值。该type
字段只有 5 个不同的值,在生产中可能不会超过几百个。
所以我试图索引表以快速执行以下查询: …
postgresql performance index database-design postgresql-performance