zombodb 索引创建
索引的创建是zombodb 的核心,我们都是需要先创建table,然后创建索引,创建的时候我们可以指定es 集群的地址,同时可能需要使用
一些地址api(比如数据直接存储在es 中而不是pg 中)
表创建
CREATE TABLE products (
id SERIAL8 NOT NULL PRIMARY KEY,
name text NOT NULL,
keywords varchar(64)[],
short_summary text,
long_description zdb.fulltext,
price bigint,
inventory_count integer,
discontinued boolean default false,
availability_date date,
manufacturer_id bigint
);
索引所有列
使用.*
参考
CREATE INDEX idxproducts
ON products
USING zombodb ((products.*))
WITH (...);
索引指定列
一般我们会使用自定义类型,方便索引的创建,如下:
CREATE TYPE products_idx_type AS (
id bigint,
name varchar,
short_summary text
);
CREATE INDEX idxproducts
ON products
USING zombodb ((
ROW(
id,
name,
short_summary
)::products_idx_type
))
WITH (...)
配置基于sql 逻辑的索引
CREATE TYPE products_idx_type AS (
id bigint,
name varchar,
description text
);
CREATE INDEX idxproducts
ON products
USING zombodb ((
ROW(
id,
name,
COALESCE(short_summary, '') || ' ' || COALESCE(long_description, '')
)::products_idx_type
))
WITH (...)
基于函数的索引
我们可以使用函数来创建比较复杂的索引
如下,通过函数索引表的每行数据
- 创建表
CREATE TABLE manufacturer (
id SERIAL8 NOT NULL PRIMARY KEY,
name text NOT NULL,
address1 text,
address2 text,
city varchar,
state varchar(2),
zip_code varchar,
phone varchar,
fax varchar,
support_email varchar
);
- 创建自定义类型
CREATE TYPE products_idx_type AS (
id bigint,
name varchar,
short_summary text,
manufacturer jsonb
);
- 函数创建
CREATE FUNCTION products_with_manufacturer(products) RETURNS products_idx_type IMMUTABLE STRICT LANGUAGE SQL AS $$
SELECT ROW($1.id, $1.name, $1.short_summary, (SELECT row_to_json(m) FROM manufacturer m WHERE m.id = $1.manufacturer_id))::products_idx_type;
$$;
- 创建索引
CREATE INDEX idxproducts
ON products
USING zombodb (products_with_manufacturer(products))
WITH (...);
- 数据检索,使用嵌套对象数据
SELECT * FROM products WHERE products ==> 'manufacturer.name:Sears';
- 说明
注意函数的实现语言,支持postgres 支持的任何语言,不只是sql,修改函数的实现,会触发数据的重新索引
参考资料
https://github.com/zombodb/zombodb/blob/master/CREATE-INDEX.md