typeql

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeQL Language Reference for TypeDB 3.8+

TypeDB 3.8+ 版 TypeQL 语言参考

This skill provides comprehensive guidance for writing TypeQL queries against TypeDB databases.
Note (3.8+): Trailing commas are now allowed in all comma-separated contexts (variable lists, statements, reductions) for easier query composition.
Note (3.8+): Unicode identifiers are now supported. Type names, attribute names, and variable names can use any Unicode XID_START character followed by XID_CONTINUE characters (e.g.,
名前
,
prénom
,
город
).
本技能为针对TypeDB数据库编写TypeQL查询提供全面指导。
注意(3.8+版本): 现在在所有逗号分隔的场景(变量列表、语句、聚合操作)中都允许使用尾随逗号,以便更轻松地编写查询。
注意(3.8+版本): 现在支持Unicode标识符。类型名称、属性名称和变量名称可以使用任何Unicode XID_START字符,后跟XID_CONTINUE字符(例如:
名前
prénom
город
)。

Quick Reference

快速参考

Transaction Types

事务类型

TypeUse ForCommit
schema
Define/undefine types, functionsYes
write
Insert, update, delete dataYes
read
Match, fetch, select queriesNo (use
close
)
类型适用场景提交方式
schema
定义/取消定义类型、函数是(需Commit)
write
插入、更新、删除数据是(需Commit)
read
匹配、获取、选择查询否(使用
close

Query Structure

查询结构

text
[with ...]                   -- Inline function preamble
[define|undefine|redefine]   -- Schema operations
[match]                      -- Pattern matching
[insert|put|update|delete]   -- Data mutations
[select|sort|offset|limit]   -- Stream operators
[require|distinct]           -- Filtering operators
[reduce ... groupby]         -- Aggregations
[fetch]                      -- JSON output
;                            -- EVERY query MUST end with a semicolon

text
[with ...]                   -- 内联函数前置声明
[define|undefine|redefine]   -- 模式操作
[match]                      -- 模式匹配
[insert|put|update|delete]   -- 数据变更
[select|sort|offset|limit]   -- 流操作符
[require|distinct]           -- 过滤操作符
[reduce ... groupby]         -- 聚合操作
[fetch]                      -- JSON输出
;                            -- 每个查询必须以分号结尾

1. Schema Definition

1. 模式定义

Schema definitions create types and constraints. Run in
schema
transactions.
模式定义用于创建类型和约束,需在
schema
事务中运行。

Root Types (TypeDB 3.x)

根类型(TypeDB 3.x)

In TypeDB 3.x,
thing
is no longer a valid root. The three roots are:
  • entity
  • relation
  • attribute
在TypeDB 3.x中,
thing
不再是有效的根类型,三个根类型为:
  • entity
    (实体)
  • relation
    (关系)
  • attribute
    (属性)

Attribute Types

属性类型

typeql
define
  # Basic value types
  attribute name, value string;
  attribute age, value integer;
  attribute salary, value double;
  attribute is_active, value boolean;
  attribute created_at, value datetime;

  # With constraints
  attribute email, value string @regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
  attribute priority, value integer @range(1..5);
  attribute status, value string @values("pending", "active", "completed");
typeql
define
  # 基础值类型
  attribute name, value string;
  attribute age, value integer;
  attribute salary, value double;
  attribute is_active, value boolean;
  attribute created_at, value datetime;

  # 带约束的属性
  attribute email, value string @regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
  attribute priority, value integer @range(1..5);
  attribute status, value string @values("pending", "active", "completed");

Entity Types

实体类型

typeql
define
  # Simple entity
  entity person;

  # Entity with attributes
  entity person,
    owns name,
    owns email @key,        # Unique identifier
    owns age @card(0..1);   # Optional (0 or 1)

  # Abstract entity (cannot be instantiated)
  entity artifact @abstract,
    owns name,
    owns created_at;

  # Entity inheritance
  entity user sub artifact,
    owns email @key;
typeql
define
  # 简单实体
  entity person;

  # 带属性的实体
  entity person,
    owns name,
    owns email @key,        # 唯一标识符
    owns age @card(0..1);   # 可选(0或1个)

  # 抽象实体(无法实例化)
  entity artifact @abstract,
    owns name,
    owns created_at;

  # 实体继承
  entity user sub artifact,
    owns email @key;

Relation Types

关系类型

typeql
define
  # Basic relation with roles
  relation employment,
    relates employer,
    relates employee;

  # Entities playing roles
  entity company,
    plays employment:employer;

  entity person,
    plays employment:employee;

  # Relation with cardinality on roles
  relation manages,
    relates manager @card(1),      # Exactly one manager
    relates report @card(1..);     # One or more reports

  # Relation owning attributes
  relation employment,
    relates employer,
    relates employee,
    owns start_date,
    owns end_date @card(0..1);

  # Self-referential relation
  relation friendship,
    relates friend;  # Same role played twice

  entity person,
    plays friendship:friend;
typeql
define
  # 带角色的基础关系
  relation employment,
    relates employer,
    relates employee;

  # 扮演角色的实体
  entity company,
    plays employment:employer;

  entity person,
    plays employment:employee;

  # 角色带基数约束的关系
  relation manages,
    relates manager @card(1),      # 恰好一个管理者
    relates report @card(1..);     # 一个或多个下属

  # 拥有属性的关系
  relation employment,
    relates employer,
    relates employee,
    owns start_date,
    owns end_date @card(0..1);

  # 自引用关系
  relation friendship,
    relates friend;  # 同一角色被两次扮演

  entity person,
    plays friendship:friend;

Role Overriding (Inheritance)

角色重写(继承)

typeql
define
  # Base relation
  relation relationship,
    relates partner;

  # Specialized relation with role override
  relation marriage sub relationship,
    relates spouse as partner;  # 'spouse' overrides 'partner'

  entity person,
    plays marriage:spouse;
typeql
define
  # 基础关系
  relation relationship,
    relates partner;

  # 带角色重写的特殊关系
  relation marriage sub relationship,
    relates spouse as partner;  # 'spouse'重写'partner'

  entity person,
    plays marriage:spouse;

Type Aliases

类型别名

typeql
define
  # Create an alias for an existing type
  attribute username alias name;  # username is an alias for name
typeql
define
  # 为现有类型创建别名
  attribute username alias name;  # username是name的别名

Annotations Reference

注解参考

AnnotationUsageDescription
@key
owns name @key
Unique identifier for type
@unique
owns email @unique
Unique but not primary key
@card(n)
owns age @card(0..1)
Cardinality constraint
@regex(...)
value string @regex(...)
Pattern validation
@range(...)
value integer @range(1..100)
Value range
@values(...)
value string @values("a","b")
Enum-like constraint
@abstract
entity @abstract
Cannot be instantiated
@cascade
owns ref @cascade
Cascade delete when owner deleted
@independent
owns tag @independent
Attribute exists independently of owner
@distinct
owns item @distinct
Each value can only be owned once
@subkey(...)
owns code @subkey(region)
Composite key with another attribute
Note:
@key
and
@unique
can only be put on
owns
, not directly on an attribute value definition.

注解使用方式描述
@key
owns name @key
类型的唯一标识符
@unique
owns email @unique
唯一但非主键
@card(n)
owns age @card(0..1)
基数约束
@regex(...)
value string @regex(...)
模式验证
@range(...)
value integer @range(1..100)
值范围约束
@values(...)
value string @values("a","b")
枚举式约束
@abstract
entity @abstract
无法实例化
@cascade
owns ref @cascade
所有者删除时级联删除属性
@independent
owns tag @independent
属性可独立于所有者存在
@distinct
owns item @distinct
每个值只能被拥有一次
@subkey(...)
owns code @subkey(region)
与其他属性组成复合主键
注意:
@key
@unique
只能用于
owns
声明,不能直接用于属性值定义。

2. Schema Modification

2. 模式修改

Undefine (Remove Schema Elements)

取消定义(移除模式元素)

typeql
undefine
  # Remove entire type
  person;

  # Remove capability from type
  owns email from person;
  plays employment:employee from person;
  relates employee from employment;

  # Remove annotation from type
  @abstract from artifact;

  # Remove annotation from capability
  @key from person owns email;

  # Remove role specialization
  as spouse from marriage relates spouse;

  # Remove function
  fun get_active_users;

  # Remove struct
  struct address;
typeql
undefine
  # 移除整个类型
  person;

  # 移除类型的能力
  owns email from person;
  plays employment:employee from person;
  relates employee from employment;

  # 移除类型的注解
  @abstract from artifact;

  # 移除能力的注解
  @key from person owns email;

  # 移除角色特化
  as spouse from marriage relates spouse;

  # 移除函数
  fun get_active_users;

  # 移除结构体
  struct address;

Redefine (Modify Existing Schema)

重新定义(修改现有模式)

typeql
redefine
  # Change annotation on type
  entity person @abstract;

  # Change annotation on capability
  person owns age @card(1..1);  # Make required

  # Redefine function (replaces entirely)
  fun count_users() -> integer:
    match $u isa user, has status "active";
    return count;

typeql
redefine
  # 修改类型的注解
  entity person @abstract;

  # 修改能力的注解
  person owns age @card(1..1);  # 设置为必填

  # 重新定义函数(完全替换)
  fun count_users() -> integer:
    match $u isa user, has status "active";
    return count;

3. Data Operations (CRUD)

3. 数据操作(CRUD)

Insert

插入

typeql
undefined
typeql
undefined

Insert entity with attributes

插入带属性的实体

insert $p isa person, has name "Alice", has email "alice@example.com";
insert $p isa person, has name "Alice", has email "alice@example.com";

Insert using anonymous variable (when reference not needed)

使用匿名变量插入(无需引用时)

insert $_ isa person, has name "Bob";
insert $_ isa person, has name "Bob";

Insert relation (match entities first)

插入关系(先匹配实体)

match $p isa person, has email "alice@example.com"; $c isa company, has name "Acme Inc"; insert $_ isa employment (employer: $c, employee: $p), has start_date 2024-01-15;
undefined
match $p isa person, has email "alice@example.com"; $c isa company, has name "Acme Inc"; insert $_ isa employment (employer: $c, employee: $p), has start_date 2024-01-15;
undefined

Put (Upsert)

新增/更新(Upsert)

typeql
undefined
typeql
undefined

Put creates if not exists, matches if exists

Put操作:不存在则创建,存在则匹配

Useful for idempotent operations

适用于幂等操作

match $c isa company, has name "Acme Inc"; put $p isa person, has email "alice@example.com", has name "Alice"; insert employment (employer: $c, employee: $p);
match $c isa company, has name "Acme Inc"; put $p isa person, has email "alice@example.com", has name "Alice"; insert employment (employer: $c, employee: $p);

Put finds existing person by email (key) or creates new one

Put操作通过email(主键)查找现有用户或创建新用户

Then insert creates the relation

然后插入关系

undefined
undefined

Update

更新

typeql
undefined
typeql
undefined

Update single-cardinality attribute (implicit replacement)

更新单基数属性(隐式替换)

match $p isa person, has email "alice@example.com"; update $p has email "alice.smith@example.com";
match $p isa person, has email "alice@example.com"; update $p has email "alice.smith@example.com";

Update multi-cardinality: delete old, insert new

更新多基数属性:先删除旧值,再插入新值

match $p isa person, has name "Alice"; $p has nickname $old; delete $p has $old; insert $p has nickname "Ally";
undefined
match $p isa person, has name "Alice"; $p has nickname $old; delete $p has $old; insert $p has nickname "Ally";
undefined

Delete

删除

typeql
undefined
typeql
undefined

Delete entity

删除实体

match $p isa person, has email "alice@example.com"; delete $p;
match $p isa person, has email "alice@example.com"; delete $p;

Delete attribute from entity

删除实体的属性

match $p isa person, has email "alice@example.com", has nickname $n; delete $p has $n;
match $p isa person, has email "alice@example.com", has nickname $n; delete $p has $n;

Alternative: delete attribute using 'of'

替代方式:使用'of'删除属性

match $p isa person, has email "alice@example.com", has nickname $n; delete has $n of $p;
match $p isa person, has email "alice@example.com", has nickname $n; delete has $n of $p;

Delete relation

删除关系

match $p isa person, has email "alice@example.com"; $c isa company, has name "Acme Inc"; $e isa employment (employer: $c, employee: $p) ; delete $e;
match $p isa person, has email "alice@example.com"; $c isa company, has name "Acme Inc"; $e isa employment (employer: $c, employee: $p) ; delete $e;

Delete role player from relation (keeps relation)

从关系中删除角色参与者(保留关系)

match $rel isa membership (member: $old_member, group: $g) ; $old_member has email "alice@example.com"; delete links ($old_member) of $rel;
match $rel isa membership (member: $old_member, group: $g) ; $old_member has email "alice@example.com"; delete links ($old_member) of $rel;

Optional delete (try) - no error if not found

可选删除(try)- 未找到时无错误

match $p isa person, has email "alice@example.com"; delete try { $p has nickname $n; };

---
match $p isa person, has email "alice@example.com"; delete try { $p has nickname $n; };

---

4. Querying Data

4. 数据查询

Match + Fetch (Primary Query Pattern)

Match + Fetch(主要查询模式)

typeql
undefined
typeql
undefined

Fetch specific attributes

获取指定属性

match $p isa person, has name $n, has email $e; fetch { "name": $n, "email": $e }
match $p isa person, has name $n, has email $e; fetch { "name": $n, "email": $e }

Fetch all attributes of entity

获取实体的所有属性

match $p isa person, has email "alice@example.com"; fetch { "person": { $p.* } }
match $p isa person, has email "alice@example.com"; fetch { "person": { $p.* } }

Fetch with attribute projection

带属性投影的获取

match $p isa person; fetch { "name": $p.name, "email": $p.email }
match $p isa person; fetch { "name": $p.name, "email": $p.email }

Fetch multi-valued attributes as list

将多值属性作为列表获取

match $p isa person, has email "alice@example.com"; fetch { "name": $p.name, "all_nicknames": [ $p.nickname ] }
match $p isa person, has email "alice@example.com"; fetch { "name": $p.name, "all_nicknames": [ $p.nickname ] }

Nested fetch for related data

嵌套获取关联数据

match $c isa company, has name "Acme Inc"; fetch { "company": $c.name, "employees": [ match employment (employer: $c, employee: $p); fetch { "name": $p.name } ] }
match $c isa company, has name "Acme Inc"; fetch { "company": $c.name, "employees": [ match employment (employer: $c, employee: $p); fetch { "name": $p.name } ] }

Fetch with inline function

带内联函数的获取

match $c isa company; fetch { "company": $c.name, "employee_count": ( match (employer: $c, employee: $e) isa employment; reduce $count = count; ) }
undefined
match $c isa company; fetch { "company": $c.name, "employee_count": ( match (employer: $c, employee: $e) isa employment; reduce $count = count; ) }
undefined

Filtering Patterns

过滤模式

typeql
undefined
typeql
undefined

Filter by type

按类型过滤

match $x isa person;
match $x isa person;

Filter by exact type (not subtypes)

按精确类型过滤(排除子类型)

match $x isa! person;
match $x isa! person;

Filter by attribute value

按属性值过滤

match $p isa person, has age > 30;
match $p isa person, has age > 30;

Filter by relation

按关系过滤

match $c isa company, has name "Acme Inc"; employment (employer: $c, employee: $p);
match $c isa company, has name "Acme Inc"; employment (employer: $c, employee: $p);

Filter by relation with relation variable

带关系变量的关系过滤

match $c isa company, has name "Acme Inc"; $rel isa employment, links (employer: $c, employee: $p);
match $c isa company, has name "Acme Inc"; $rel isa employment, links (employer: $c, employee: $p);

Comparison operators: ==, !=, <, <=, >, >=, like, contains

比较操作符:==, !=, <, <=, >, >=, like, contains

match $p isa person, has name $n; $n like "^A.*"; # Regex match
match $p isa person, has bio $b; $b contains "engineer"; # Substring match
undefined
match $p isa person, has name $n; $n like "^A.*"; # 正则匹配
match $p isa person, has bio $b; $b contains "engineer"; # 子串匹配
undefined

Identity Check (is)

身份检查(is)

typeql
undefined
typeql
undefined

Check if two variables refer to the same concept

检查两个变量是否指向同一概念

match $p1 isa person; $p2 isa person; friendship (friend: $p1, friend: $p2); not { $p1 is $p2; }; # Exclude self-friendship fetch { "person": $p1.name }
undefined
match $p1 isa person; $p2 isa person; friendship (friend: $p1, friend: $p2); not { $p1 is $p2; }; # 排除自交友 fetch { "person": $p1.name }
undefined

Conjunction (Grouping with AND)

合取(AND分组)

typeql
undefined
typeql
undefined

Explicit grouping with curly braces

使用大括号显式分组

match $p isa person; { $p has age > 18; $p has status "active"; }; # Both conditions must be true
undefined
match $p isa person; { $p has age > 18; $p has status "active"; }; # 两个条件必须同时满足
undefined

Disjunction (OR)

析取(OR)

typeql
match
  $p isa person, has email $e;
  {
    $p has name "Alice";
  } or {
    $p has name "Bob";
  };
fetch { "email": $e }
typeql
match
  $p isa person, has email $e;
  {
    $p has name "Alice";
  } or {
    $p has name "Bob";
  };
fetch { "email": $e }

Negation (NOT)

否定(NOT)

typeql
undefined
typeql
undefined

Find persons not employed by Acme

查找未受雇于Acme的人员

match $p isa person; not { $c isa company, has name "Acme Inc"; employment (employer: $c, employee: $p); }; fetch { "unemployed": $p.name }
undefined
match $p isa person; not { $c isa company, has name "Acme Inc"; employment (employer: $c, employee: $p); }; fetch { "unemployed": $p.name }
undefined

Optional Patterns (TRY)

可选模式(TRY)

typeql
undefined
typeql
undefined

Match with optional pattern

带可选模式的匹配

match $p isa person, has name $n; try { $p has email $e; }; fetch { "name": $n, "email": $e # May be null if no email }

---
match $p isa person, has name $n; try { $p has email $e; }; fetch { "name": $n, "email": $e # 无邮箱时可能为null }

---

5. Stream Operators

5. 流操作符

Order must be:
sort
,
offset
,
limit
typeql
undefined
顺序必须为:
sort
,
offset
,
limit
typeql
undefined

Sort results

排序结果

match $p isa person, has name $n; sort $n asc;
match $p isa person, has name $n; sort $n asc;

Sort descending

降序排序

match $p isa person, has age $a; sort $a desc;
match $p isa person, has age $a; sort $a desc;

Pagination

分页

match $p isa person, has name $n; sort $n asc; offset 10; limit 10;
match $p isa person, has name $n; sort $n asc; offset 10; limit 10;

Select specific variables (like SQL SELECT)

选择指定变量(类似SQL SELECT)

match $p isa person, has name $n, has email $e; select $n, $e;
match $p isa person, has name $n, has email $e; select $n, $e;

Distinct results

去重结果

match $p isa person, has name $n; distinct;
match $p isa person, has name $n; distinct;

Require variables to be bound (filter nulls from try)

要求变量已绑定(过滤try产生的null)

match $p isa person, has name $n; try { $p has email $e; }; require $e; # Only return rows where email exists

---
match $p isa person, has name $n; try { $p has email $e; }; require $e; # 仅返回邮箱存在的行

---

6. Aggregations

6. 聚合操作

typeql
undefined
typeql
undefined

Count

计数

match $p isa person; reduce $count = count;
match $p isa person; reduce $count = count;

Count specific variable

对特定变量计数

match $p isa person, has email $e; reduce $count = count($e);
match $p isa person, has email $e; reduce $count = count($e);

Multiple aggregations

多聚合操作

match $p isa person, has salary $s; reduce $max = max($s), $min = min($s), $avg = mean($s);
match $p isa person, has salary $s; reduce $max = max($s), $min = min($s), $avg = mean($s);

Group by

分组

match $c isa company; employment (employer: $c, employee: $e); reduce $count = count groupby $c;
match $c isa company; employment (employer: $c, employee: $e); reduce $count = count groupby $c;

Multiple groupby variables

多变量分组

match $c isa company, has industry $ind; employment (employer: $c, employee: $e); $e has department $dept; reduce $count = count groupby $ind, $dept;
undefined
match $c isa company, has industry $ind; employment (employer: $c, employee: $e); $e has department $dept; reduce $count = count groupby $ind, $dept;
undefined

Available Reducers

可用聚合函数

ReducerUsageDescription
count
count
or
count($var)
Count results
sum($var)
sum($salary)
Sum numeric values
min($var)
min($age)
Minimum value
max($var)
max($age)
Maximum value
mean($var)
mean($score)
Average
median($var)
median($score)
Median
std($var)
std($score)
Standard deviation
list($var)
list($name)
Collect into list

聚合函数使用方式描述
count
count
count($var)
计数结果数量
sum($var)
sum($salary)
数值求和
min($var)
min($age)
最小值
max($var)
max($age)
最大值
mean($var)
mean($score)
平均值
median($var)
median($score)
中位数
std($var)
std($score)
标准差
list($var)
list($name)
收集为列表

7. Expressions and Computed Values

7. 表达式与计算值

Arithmetic Operators

算术操作符

typeql
match
  $p isa product, has price $price, has quantity $qty;
let $subtotal = $price * $qty;           # Multiplication
let $with_tax = $subtotal * 1.1;         # More multiplication
let $discount = $subtotal / 10;          # Division
let $final = $subtotal - $discount;      # Subtraction
let $total = $final + 5.00;              # Addition (shipping)
let $squared = $price ^ 2;               # Power/exponent
let $remainder = $qty % 3;               # Modulo
fetch {
  "product": $p.name,
  "total": $total
}
typeql
match
  $p isa product, has price $price, has quantity $qty;
let $subtotal = $price * $qty;           # 乘法
let $with_tax = $subtotal * 1.1;         # 乘法运算
let $discount = $subtotal / 10;          # 除法
let $final = $subtotal - $discount;      # 减法
let $total = $final + 5.00;              # 加法(运费)
let $squared = $price ^ 2;               # 幂运算
let $remainder = $qty % 3;               # 取模
fetch {
  "product": $p.name,
  "total": $total
}

Assignment and Literals

赋值与字面量

typeql
match
  $p isa product, has price $price;
let $vat_rate = 0.2;                     # Assign literal
let $price_with_vat = $price * (1 + $vat_rate);
fetch {
  "price_with_vat": $price_with_vat
}
typeql
match
  $p isa product, has price $price;
let $vat_rate = 0.2;                     # 赋值字面量
let $price_with_vat = $price * (1 + $vat_rate);
fetch {
  "price_with_vat": $price_with_vat
}

Built-in Functions

内置函数

typeql
match
  $p isa product, has price $price, has name $name;
typeql
match
  $p isa product, has price $price, has name $name;

NOTE: ceil, floor, round only work on double/decimal, not integers

注意:ceil、floor、round仅适用于double/decimal类型,不适用于整数

let $rounded = round($price); # Round to nearest integer let $ceiling = ceil($price); # Round up let $floored = floor($price); # Round down let $absolute = abs($price - 100); # Absolute value let $name_len = len($name); # String length (note: len, not length) let $higher = max($price, 10.0); # Maximum of two values let $lower = min($price, 100.0); # Minimum of two values fetch { "stats": { $rounded, $ceiling, $floored } }
let $rounded = round($price); # 四舍五入到最近整数 let $ceiling = ceil($price); # 向上取整 let $floored = floor($price); # 向下取整 let $absolute = abs($price - 100); # 绝对值 let $name_len = len($name); # 字符串长度(注意:是len而非length) let $higher = max($price, 10.0); # 取两个值的最大值 let $lower = min($price, 100.0); # 取两个值的最小值 fetch { "stats": { $rounded, $ceiling, $floored } }

String concatenation

字符串拼接

match $u isa user, has first_name $fn, has last_name $ln; let $full = concat($fn, " ", $ln); fetch { "full_name": $full }
match $u isa user, has first_name $fn, has last_name $ln; let $full = concat($fn, " ", $ln); fetch { "full_name": $full }

Get IID of a concept (3.8+)

获取概念的IID(3.8+)

match $p isa person, has email "alice@example.com"; fetch { "iid": iid($p) # Get internal identifier }
match $p isa person, has email "alice@example.com"; fetch { "iid": iid($p) # 获取内部标识符 }

Get type label (3.8+) - NOTE: label() works on TYPE variables, not instances!

获取类型标签(3.8+)- 注意:label()仅适用于TYPE变量,不适用于实例!

Must bind the exact type first using isa! and a type variable

必须先使用isa!和类型变量绑定精确类型

match $p isa! $t, has email "alice@example.com"; $t sub person; # Bind $t to exact type of $p fetch { "iid": iid($p), "type": label($t) # label() on TYPE variable $t }

---
match $p isa! $t, has email "alice@example.com"; $t sub person; # 将$t绑定到$p的精确类型 fetch { "iid": iid($p), "type": label($t) # 对TYPE变量$t使用label() }

---

8. List Operations

8. 列表操作

List Literals

列表字面量

typeql
match
  $p isa person, has name $name;
let $tags = ["active", "verified", "premium"];  # List literal
fetch { "name": $name, "tags": $tags }
typeql
match
  $p isa person, has name $name;
let $tags = ["active", "verified", "premium"];  # 列表字面量
fetch { "name": $name, "tags": $tags }

List Indexing

列表索引

typeql
match
  $p isa person, has score $scores;  # Multi-valued attribute
let $first = $scores[0];             # First element (0-indexed)
let $second = $scores[1];            # Second element
fetch { "first_score": $first }
typeql
match
  $p isa person, has score $scores;  # 多值属性
let $first = $scores[0];             # 第一个元素(0索引)
let $second = $scores[1];            # 第二个元素
fetch { "first_score": $first }

List Slicing

列表切片

typeql
match
  $p isa person, has score $scores;
let $top_three = $scores[0..3];      # Elements 0, 1, 2
let $rest = $scores[3..10];          # Elements 3 through 9
fetch { "top_scores": $top_three }

typeql
match
  $p isa person, has score $scores;
let $top_three = $scores[0..3];      # 元素0、1、2
let $rest = $scores[3..10];          # 元素3到9
fetch { "top_scores": $top_three }

9. Structs

9. 结构体

Struct Definition

结构体定义

typeql
define
  # Define a struct type
  struct address:
    street value string,
    city value string,
    zip value string?,      # Optional field (nullable)
    country value string;
WARNING: structs are not yet implemented as of TypeDB 3.8.0, so should not be used.
typeql
define
  # 定义结构体类型
  struct address:
    street value string,
    city value string,
    zip value string?,      # 可选字段(可为null)
    country value string;
警告:截至TypeDB 3.8.0,结构体尚未实现,请勿使用。

Using Structs

使用结构体

typeql
undefined
typeql
undefined

Insert with struct value

插入带结构体值的实体

insert $p isa person, has name "Alice", has home_address { street: "123 Main St", city: "Boston", zip: "02101", country: "USA" };
insert $p isa person, has name "Alice", has home_address { street: "123 Main St", city: "Boston", zip: "02101", country: "USA" };

Match struct fields

匹配结构体字段

match $p isa person, has home_address $addr; $addr isa address { city: "Boston" }; fetch { "person": $p.name }
undefined
match $p isa person, has home_address $addr; $addr isa address { city: "Boston" }; fetch { "person": $p.name }
undefined

Struct Destructuring

结构体解构

typeql
undefined
typeql
undefined

Destructure struct in let

在let中解构结构体

match $p isa person, has home_address $addr; let { city: $city, zip: $zip } = $addr; fetch { "person": $p.name, "city": $city }

---
match $p isa person, has home_address $addr; let { city: $city, zip: $zip } = $addr; fetch { "person": $p.name, "city": $city }

---

10. Functions

10. 函数

Define reusable query logic in schema.
在模式中定义可复用的查询逻辑。

Function Definition

函数定义

typeql
define
typeql
define

Return stream of values

返回值流

fun get_active_users() -> { string }: match $u isa user, has status == "active", has email $e; return { $e };
fun get_active_users() -> { string }: match $u isa user, has status == "active", has email $e; return { $e };

Return single value with aggregation

带聚合的单值返回

fun count_users() -> integer: match $u isa user; return count;
fun count_users() -> integer: match $u isa user; return count;

Function with parameters

带参数的函数

fun get_user_projects($user_email: string) -> { string }: match $u isa user, has email == $user_email; membership (member: $u, project: $p); $p has name $name; return { $name };
fun get_user_projects($user_email: string) -> { string }: match $u isa user, has email == $user_email; membership (member: $u, project: $p); $p has name $name; return { $name };

Return multiple values in stream

返回流中的多值

fun get_user_details($email: string) -> { string, string }: match $u isa user, has email == $email, has name $n, has role $r; return { $n, $r };
fun get_user_details($email: string) -> { string, string }: match $u isa user, has email == $email, has name $n, has role $r; return { $n, $r };

Return first match only

仅返回第一个匹配结果

fun get_oldest_user() -> string: match $u isa user, has name $n, has age $a; sort $a desc; return first $n;
fun get_oldest_user() -> string: match $u isa user, has name $n, has age $a; sort $a desc; return first $n;

Return last match only

仅返回最后一个匹配结果

fun get_youngest_user() -> string: match $u isa user, has name $n, has age $a; sort $a desc; return last $n;
fun get_youngest_user() -> string: match $u isa user, has name $n, has age $a; sort $a desc; return last $n;

Return boolean (existence check)

返回布尔值(存在性检查)

fun user_exists($email: string) -> boolean: match $u isa user, has email == $email; return check; # Returns true if match found, false otherwise
undefined
fun user_exists($email: string) -> boolean: match $u isa user, has email == $email; return check; # 找到匹配返回true,否则返回false
undefined

Using Functions

使用函数

typeql
undefined
typeql
undefined

Call function in match with 'let ... in'

在match中通过'let ... in'调用函数

match let $emails in get_active_users(); fetch { "active_emails": $emails }
match let $emails in get_active_users(); fetch { "active_emails": $emails }

Call function with parameter

带参数调用函数

match let $projects in get_user_projects("alice@example.com"); fetch { "projects": $projects }
match let $projects in get_user_projects("alice@example.com"); fetch { "projects": $projects }

Call function returning single value

调用返回单值的函数

match let $count in count_users(); fetch { "total_users": $count }
match let $count in count_users(); fetch { "total_users": $count }

Use function in expression

在表达式中使用函数

match $u isa user; let $exists in user_exists($u.email); fetch { "user": $u.name, "verified": $exists }
undefined
match $u isa user; let $exists in user_exists($u.email); fetch { "user": $u.name, "verified": $exists }
undefined

Inline Functions with WITH

使用WITH定义内联函数

typeql
undefined
typeql
undefined

Define function inline for single query

为单个查询内联定义函数

with fun active_in_dept($dept: string) -> { user }: match $u isa user, has department == $dept, has status "active"; return { $u };
match let $user in active_in_dept("Engineering"); fetch { "engineer": $user.name }

---
with fun active_in_dept($dept: string) -> { user }: match $u isa user, has department == $dept, has status "active"; return { $u };
match let $user in active_in_dept("Engineering"); fetch { "engineer": $user.name }

---

11. IID (Internal Identifier) Operations

11. IID(内部标识符)操作

typeql
undefined
typeql
undefined

Match by IID (for direct lookups)

通过IID匹配(直接查找)

match $entity iid 0x1f0005000000000000012f; fetch { "data": { $entity.* } }
match $entity iid 0x1f0005000000000000012f; fetch { "data": { $entity.* } }

Get IID using iid() function (3.8+)

使用iid()函数获取IID(3.8+)

match $p isa person, has email "alice@example.com"; fetch { "person": $p.name, "iid": iid($p) }
match $p isa person, has email "alice@example.com"; fetch { "person": $p.name, "iid": iid($p) }

Get IID and exact type label together (3.8+)

同时获取IID和精确类型标签(3.8+)

NOTE: label() requires a TYPE variable, use isa! to bind it

注意:label()需要TYPE变量,使用isa!绑定

match $p isa! $t, has email "alice@example.com"; $t sub person; fetch { "iid": iid($p), "type": label($t) }

---
match $p isa! $t, has email "alice@example.com"; $t sub person; fetch { "iid": iid($p), "type": label($t) }

---

12. Rules (Inference)

12. 规则(推理)

TypeDB 3.0 and on no longer uses rules, and uses only functions instead.

TypeDB 3.0及以上版本不再使用规则,仅使用函数替代。

13. Common Patterns

13. 常见模式

Note: each clause is not itself terminated with a trailing semicolon, only each statement within a clause is.
注意:每个子句本身不需要以分号结尾,仅子句内的每个语句需要。

Upsert (Insert if not exists)

Upsert(不存在则插入)

typeql
undefined
typeql
undefined

Use 'put' for upsert behavior

使用'put'实现upsert行为

match $c isa company, has name "Acme Inc"; put $p isa person, has email "new@example.com", has name "New Person"; insert employment (employer: $c, employee: $p);
undefined
match $c isa company, has name "Acme Inc"; put $p isa person, has email "new@example.com", has name "New Person"; insert employment (employer: $c, employee: $p);
undefined

Polymorphic Queries

多态查询

typeql
undefined
typeql
undefined

Query abstract supertype to get all subtypes

查询抽象父类型以获取所有子类型实例

match $artifact isa artifact, has name $n; # Gets all subtypes fetch { "name": $n }
match $artifact isa artifact, has name $n; # 获取所有子类型实例 fetch { "name": $n }

Query exact type only (not subtypes)

仅查询精确类型(排除子类型)

match $artifact isa! artifact, has name $n; # Only direct instances fetch { "name": $n }
undefined
match $artifact isa! artifact, has name $n; # 仅获取直接实例 fetch { "name": $n }
undefined

Graph Traversal

图遍历

typeql
undefined
typeql
undefined

Find all connected nodes (1-hop)

查找所有相连节点(1跳)

match $center isa entity, has id == "target-id"; $rel links ($center), links ($neighbor); not { $neighbor is $center; }; fetch { "center": $center.id, "neighbor": $neighbor.id }
undefined
match $center isa entity, has id == "target-id"; $rel links ($center), links ($neighbor); not { $neighbor is $center; }; fetch { "center": $center.id, "neighbor": $neighbor.id }
undefined

Existence Check

存在性检查

typeql
undefined
typeql
undefined

Check if pattern exists

检查模式是否存在

match $u isa user, has email "alice@example.com"; not { (member: $u) isa team_membership; };
match $u isa user, has email "alice@example.com"; not { (member: $u) isa team_membership; };

Returns results only if user exists but has no team

仅当用户存在且未加入任何团队时返回结果


---

---

14. Critical Pitfalls

14. 关键陷阱

TypeDB 3 relation syntax

TypeDB 3 关系语法

Relations in TypeDB 3.x use the follow syntax only:
Anonyous relation syntax: always use this if you don't need a relation instance variable
<rel-type> (<role-type>: <player var>, <role-type-2>, <player var 2>, ...);
Variabilized relation syntax (with a variable for the relation instance): only use this if you need a variable for the relation instance
$rel-var isa <rel-type>,
  links (<role-type>: <player var>, <role-type-2>, <player var 2>, ...);
TypeDB 3.x中的关系仅使用以下语法:
匿名关系语法: 如果不需要关系实例变量,请始终使用此语法
<rel-type> (<role-type>: <player var>, <role-type-2>, <player var 2>, ...);
带变量的关系语法(为关系实例指定变量): 仅当需要关系实例变量时使用此语法
$rel-var isa <rel-type>,
  links (<role-type>: <player var>, <role-type-2>, <player var 2>, ...);

Reserved keywords

保留关键字

These are reserved identifiers. Never use them as user-defined identifier like type labels or variables, in any capitalization. If required, append _ instead:
with, match, fetch, update, define, undefine, redefine, insert, put, delete, end , entity, relation, attribute, role , asc, desc, struct, fun, return, alias, sub, owns, as, plays, relates, iid, isa, links, has, is, or, not, try, in, true, false, of, from, first, last
以下为保留标识符。请勿将其用作用户定义的标识符(如类型标签或变量),无论大小写。如果必须使用,请在末尾添加下划线
with, match, fetch, update, define, undefine, redefine, insert, put, delete, end , entity, relation, attribute, role , asc, desc, struct, fun, return, alias, sub, owns, as, plays, relates, iid, isa, links, has, is, or, not, try, in, true, false, of, from, first, last

Match Clauses are Simultaneous (AND)

Match子句为同时满足(AND)

All statements in
match
must be satisfied together. Not sequential.
typeql
undefined
match
中的所有语句必须同时满足,而非按顺序执行。
typeql
undefined

WRONG assumption: "get all books, then find promotions"

错误假设:"获取所有书籍,然后查找促销信息"

ACTUAL: Only returns books that ARE in promotions

实际结果:仅返回参与促销的书籍

match $b isa book; promotion (book: $b, promo: $p);
undefined
match $b isa book; promotion (book: $b, promo: $p);
undefined

Unconstrained Variables = Cross Join

无约束变量 = 笛卡尔积

typeql
undefined
typeql
undefined

PROBLEM: Returns every book x every promotion (Cartesian product)

问题:返回每本书与每个促销的组合(笛卡尔积)

match $b isa book; $p isa promotion; # Not linked to $b!
match $b isa book; $p isa promotion; # 未与$b关联!

FIX: Link variables through relations

修复:通过关系关联变量

match $b isa book; book_promotion (book: $b, promotion: $p);
undefined
match $b isa book; book_promotion (book: $b, promotion: $p);
undefined

Symmetric Relations Return Duplicates

对称关系返回重复结果

typeql
undefined
typeql
undefined

PROBLEM: Returns (A,B) and (B,A)

问题:返回(A,B)和(B,A)

match friendship (friend: $p1, friend: $p2);
match friendship (friend: $p1, friend: $p2);

FIX: Add asymmetric constraint

修复:添加非对称约束

match $p1 has email $e1; $p2 has email $e2; friendship (friend: $p1, friend: $p2); $e1 < $e2; # Each pair only once
undefined
match $p1 has email $e1; $p2 has email $e2; friendship (friend: $p1, friend: $p2); $e1 < $e2; # 每个配对仅返回一次
undefined

Cardinality Validated at Commit

基数约束在提交时验证

Insert violations don't fail immediately - only on commit.
插入违反约束的操作不会立即失败 - 仅在提交时触发错误。

Sorting Loads All Results

排序会加载所有结果

sort
requires loading all matching data into memory before pagination.
sort
需要将所有匹配数据加载到内存后再进行分页。

Variable Scoping in OR/NOT

OR/NOT中的变量作用域

Variables inside
or
blocks are not guaranteed bound outside:
typeql
undefined
or
块内的变量在块外不保证已绑定:
typeql
undefined

INVALID: $company might not be bound

无效:$company可能未绑定

match $p isa person; { employment (employee: $p, employer: $company); } or { $p has status "freelancer"; }; not { $company has name "BadCorp"; }; # $company may be unbound!
match $p isa person; { employment (employee: $p, employer: $company); } or { $p has status "freelancer"; }; not { $company has name "BadCorp"; }; # $company可能未绑定!

VALID: Bind variable in parent scope first

有效:先在父作用域绑定变量

match $p isa person; employment (employee: $p, employer: $company); not { $company has name "BadCorp"; };
undefined
match $p isa person; employment (employee: $p, employer: $company); not { $company has name "BadCorp"; };
undefined

Variable Reuse in OR Branches

OR分支中的变量复用

typeql
undefined
typeql
undefined

INVALID: $x means different things in each branch

无效:$x在每个分支中含义不同

match { editing (person: $p, document: $x); } or { messaging (person: $p, message: $x); };
match { editing (person: $p, document: $x); } or { messaging (person: $p, message: $x); };

VALID: Use different variable names

有效:使用不同的变量名

match { editing (person: $p, document: $doc); } or { messaging (person: $p, message: $msg) ; };

---
match { editing (person: $p, document: $doc); } or { messaging (person: $p, message: $msg) ; };

---

15. CLI Notes

15. CLI注意事项

Command Execution

命令执行

bash
undefined
bash
undefined

Server commands: NO semicolon

服务器命令:无需分号

typedb console --command "database list"
typedb console --command "database list"

TypeQL in transactions: WITH semicolons

事务中的TypeQL:需要分号

typedb console --command "transaction mydb schema" --command "define entity person;"
undefined
typedb console --command "transaction mydb schema" --command "define entity person;"
undefined

Script Files (.tqls)

脚本文件(.tqls)

text
undefined
text
undefined

Console commands without semicolons

控制台命令无需分号

transaction mydb schema define entity person; commit
undefined
transaction mydb schema define entity person; commit
undefined

Transaction Lifecycle

事务生命周期

  • schema
    ,
    write
    transactions: use
    commit
  • read
    transactions: use
    close

  • schema
    write
    事务:使用
    commit
    提交
  • read
    事务:使用
    close
    关闭

16. Value Types Reference

16. 值类型参考

TypeQL TypeDescriptionExample Literal
string
UTF-8 text
"hello"
boolean
true/false
true
,
false
integer
64-bit signed int
42
,
-17
double
Double-precision float
3.14159
decimal
Precise decimal
99.99dec
date
Date only
2024-01-15
datetime
Date and time
2024-01-15T10:30:00
datetime-tz
With timezone
2024-01-15T10:30:00 America/New_York
duration
Time duration
P1Y2M3D
,
PT4H30M
Note:
0dec
is not valid syntax in some versions of TypeDB. Always use
0.0dec
.
TypeQL类型描述示例字面量
string
UTF-8文本
"hello"
boolean
布尔值(真/假)
true
,
false
integer
64位有符号整数
42
,
-17
double
双精度浮点数
3.14159
decimal
高精度小数
99.99dec
date
仅日期
2024-01-15
datetime
日期和时间
2024-01-15T10:30:00
datetime-tz
带时区的日期时间
2024-01-15T10:30:00 America/New_York
duration
时间间隔
P1Y2M3D
,
PT4H30M
注意:在部分TypeDB版本中,
0dec
不是有效语法,请始终使用
0.0dec

Duration Format (ISO 8601)

时间间隔格式(ISO 8601)

text
P[n]Y[n]M[n]DT[n]H[n]M[n]S
P1Y2M3D     = 1 year, 2 months, 3 days
PT4H30M     = 4 hours, 30 minutes
P1W         = 1 week
PT1H30M45S  = 1 hour, 30 minutes, 45 seconds

text
P[n]Y[n]M[n]DT[n]H[n]M[n]S
P1Y2M3D     = 1年2个月3天
PT4H30M     = 4小时30分钟
P1W         = 1周
PT1H30M45S  = 1小时30分钟45秒

17. Debugging Queries

17. 调试查询

Test Match Before Write

在写入前测试Match

typeql
undefined
typeql
undefined

Before running delete:

执行删除前:

match $u isa user, has status "inactive"; fetch { "will_delete": $u.email }
match $u isa user, has status "inactive"; fetch { "will_delete": $u.email }

Then execute:

然后执行删除:

match $u isa user, has status "inactive"; delete $u;
undefined
match $u isa user, has status "inactive"; delete $u;
undefined

Check Schema

检查模式

typeql
undefined
typeql
undefined

In read transaction - list entity types

在read事务中 - 列出实体类型

match $type sub entity; fetch { "entity_types": $type }
match $type sub entity; fetch { "entity_types": $type }

List relation types

列出关系类型

match $rel sub relation; fetch { "relation_types": $rel }
match $rel sub relation; fetch { "relation_types": $rel }

List attribute types

列出属性类型

match $attr sub attribute; fetch { "attribute_types": $attr }
undefined
match $attr sub attribute; fetch { "attribute_types": $attr }
undefined

Verify Cardinality

验证基数

typeql
undefined
typeql
undefined

Count instances per type

统计每个类型的实例数量

match $type sub entity; $instance isa! $type; reduce $count = count groupby $type;

---
match $type sub entity; $instance isa! $type; reduce $count = count groupby $type;

---

18. Complete Operator Reference

18. 完整操作符参考

Comparison Operators

比较操作符

OperatorDescriptionExample
==
Equal
$age == 30
!=
Not equal
$status != "done"
<
Less than
$age < 18
<=
Less than or equal
$age <= 65
>
Greater than
$salary > 50000
>=
Greater than or equal
$score >= 90
like
Regex match
$name like "^A.*"
contains
Substring match
$bio contains "dev"
操作符描述示例
==
等于
$age == 30
!=
不等于
$status != "done"
<
小于
$age < 18
<=
小于等于
$age <= 65
>
大于
$salary > 50000
>=
大于等于
$score >= 90
like
正则匹配
$name like "^A.*"
contains
子串匹配
$bio contains "dev"

Math Operators

数学操作符

OperatorDescriptionExample
+
Addition
$a + $b
-
Subtraction
$a - $b
*
Multiplication
$a * $b
/
Division
$a / $b
%
Modulo
$a % $b
^
Power
$a ^ 2
操作符描述示例
+
加法
$a + $b
-
减法
$a - $b
*
乘法
$a * $b
/
除法
$a / $b
%
取模
$a % $b
^
幂运算
$a ^ 2

Expression Functions

表达式函数

FunctionDescriptionExample
abs($x)
Absolute value
abs($n - 10)
ceil($x)
Round up (double/decimal only)
ceil($price)
floor($x)
Round down (double/decimal only)
floor($price)
round($x)
Round nearest (double/decimal)
round($price)
len($s)
String length
len($name)
max($a,$b)
Maximum of two values
max($x, 0)
min($a,$b)
Minimum of two values
min($x, 100)
iid($var)
Get internal identifier (3.8+)
iid($p)
label($t)
Get type label (TYPE var only!)
label($t)
concat(…)
Concatenate strings
concat($a," ",$b)
函数名描述示例
abs($x)
绝对值
abs($n - 10)
ceil($x)
向上取整(仅double/decimal)
ceil($price)
floor($x)
向下取整(仅double/decimal)
floor($price)
round($x)
四舍五入(仅double/decimal)
round($price)
len($s)
字符串长度
len($name)
max($a,$b)
取两个值的最大值
max($x, 0)
min($a,$b)
取两个值的最小值
min($x, 100)
iid($var)
获取内部标识符(3.8+)
iid($p)
label($t)
获取类型标签(仅TYPE变量!)
label($t)
concat(…)
字符串拼接
concat($a," ",$b)

Pattern Keywords

模式关键字

KeywordDescription
isa
Type check (includes subtypes)
isa!
Exact type check (excludes subtypes)
has
Attribute ownership
links
Role player in relation
is
Identity comparison
or
Disjunction
not
Negation
try
Optional pattern
关键字描述
isa
类型检查(包含子类型)
isa!
精确类型检查(排除子类型)
has
属性拥有关系
links
关系中的角色参与者
is
身份比较
or
析取(或)
not
否定(非)
try
可选模式