简体   繁体   English

PostgreSQL-键值对规范化

[英]PostgreSQL - key-value pair normalization

I'm trying to design a schema (on Postgres but any other SQL's fine) that supports the following requirements: 我正在尝试设计一种支持以下要求的架构(在Postgres上,但其他SQL都不错):

  • Each document (a row in table documents ) has a unique string ID ( id field) and several other data fields. 每个文档(表documents的一行)都有一个唯一的字符串ID( id字段)和其他几个数据字段。
  • Each document can have 0 or more tags (which is string key-value pairs) attached to it, and, the goal is to build a system that lets users to sort or filter documents using those string key-value pairs. 每个文档可以附加0个或多个标签(字符串键值对),目标是构建一个系统,该系统使用户可以使用这些字符串键值对对文档进行排序或过滤。 Eg "Show me all documents that have a tag of "key1" with "value1" value AND sort the output using the tag value of "key3". 例如,“向我显示所有带有“ value1”值的带有“ key1”标签的文档,并使用标签值“ key3”对输出进行排序。

So DDL should look like this: (simplified) 所以DDL应该看起来像这样:(简化)

create table documents
(
  id char(32) not null
    constraint documents_pkey
    primary key,
  data varchar(2000),
  created_at timestamp,
  updated_at timestamp
)

create table document_tags
(
  id serial not null
    constraint document_tags_pkey
    primary key,
  document_id char(32) not null
    constraint document_tags_documents_id_fk
    references documents
    on update cascade on delete cascade,
  tag_key varchar(200) not null,
  tag_value varchar(2000) not null
)

Now my question is how can I build a query that does filtering/sorting using the tag key values? 现在我的问题是如何建立一个使用标签键值进行过滤/排序的查询? Eg Returns all documents (possibly with LIMIT/OFFSET) that does have "key1" = "value1" tag and "key2" = "value2" tags, sorted by the value of "key3" tag. 例如, 返回所有具有“ key1” =“ value1”标签和“ key2” =“ value2”标签的所有文档(可能带有LIMIT / OFFSET),并按“ key3”标签的值排序。

You can use group by and having : 您可以使用group byhaving

select dt.document_id
from document_tags dt
where dt.tag_key = 'key1' and dt.tag_value = 'value1'
group by dt.document_id
order by max(case when dt.tag_key = 'key2' then dt.tag_value end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM