typeql
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeQL 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
事务类型
| Type | Use For | Commit |
|---|---|---|
| Define/undefine types, functions | Yes |
| Insert, update, delete data | Yes |
| Match, fetch, select queries | No (use |
| 类型 | 适用场景 | 提交方式 |
|---|---|---|
| 定义/取消定义类型、函数 | 是(需Commit) |
| 插入、更新、删除数据 | 是(需Commit) |
| 匹配、获取、选择查询 | 否(使用 |
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 semicolontext
[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 transactions.
schema模式定义用于创建类型和约束,需在事务中运行。
schemaRoot Types (TypeDB 3.x)
根类型(TypeDB 3.x)
In TypeDB 3.x, is no longer a valid root. The three roots are:
thingentityrelationattribute
在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 nametypeql
define
# 为现有类型创建别名
attribute username alias name; # username是name的别名Annotations Reference
注解参考
| Annotation | Usage | Description |
|---|---|---|
| | Unique identifier for type |
| | Unique but not primary key |
| | Cardinality constraint |
| | Pattern validation |
| | Value range |
| | Enum-like constraint |
| | Cannot be instantiated |
| | Cascade delete when owner deleted |
| | Attribute exists independently of owner |
| | Each value can only be owned once |
| | Composite key with another attribute |
Note: and can only be put on , not directly on an attribute value definition.
@key@uniqueowns| 注解 | 使用方式 | 描述 |
|---|---|---|
| | 类型的唯一标识符 |
| | 唯一但非主键 |
| | 基数约束 |
| | 模式验证 |
| | 值范围约束 |
| | 枚举式约束 |
| | 无法实例化 |
| | 所有者删除时级联删除属性 |
| | 属性可独立于所有者存在 |
| | 每个值只能被拥有一次 |
| | 与其他属性组成复合主键 |
注意:和只能用于声明,不能直接用于属性值定义。
@key@uniqueowns2. 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
undefinedtypeql
undefinedInsert 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;
undefinedmatch
$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;
undefinedPut (Upsert)
新增/更新(Upsert)
typeql
undefinedtypeql
undefinedPut 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
然后插入关系
undefinedundefinedUpdate
更新
typeql
undefinedtypeql
undefinedUpdate 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";
undefinedmatch
$p isa person, has name "Alice";
$p has nickname $old;
delete
$p has $old;
insert
$p has nickname "Ally";
undefinedDelete
删除
typeql
undefinedtypeql
undefinedDelete 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
undefinedtypeql
undefinedFetch 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;
)
}
undefinedmatch
$c isa company;
fetch {
"company": $c.name,
"employee_count": (
match
(employer: $c, employee: $e) isa employment;
reduce $count = count;
)
}
undefinedFiltering Patterns
过滤模式
typeql
undefinedtypeql
undefinedFilter 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
undefinedmatch
$p isa person, has name $n;
$n like "^A.*"; # 正则匹配
match
$p isa person, has bio $b;
$b contains "engineer"; # 子串匹配
undefinedIdentity Check (is)
身份检查(is)
typeql
undefinedtypeql
undefinedCheck 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 }
undefinedmatch
$p1 isa person;
$p2 isa person;
friendship (friend: $p1, friend: $p2);
not { $p1 is $p2; }; # 排除自交友
fetch { "person": $p1.name }
undefinedConjunction (Grouping with AND)
合取(AND分组)
typeql
undefinedtypeql
undefinedExplicit grouping with curly braces
使用大括号显式分组
match
$p isa person;
{
$p has age > 18;
$p has status "active";
}; # Both conditions must be true
undefinedmatch
$p isa person;
{
$p has age > 18;
$p has status "active";
}; # 两个条件必须同时满足
undefinedDisjunction (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
undefinedtypeql
undefinedFind 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 }
undefinedmatch
$p isa person;
not {
$c isa company, has name "Acme Inc";
employment (employer: $c, employee: $p);
};
fetch { "unemployed": $p.name }
undefinedOptional Patterns (TRY)
可选模式(TRY)
typeql
undefinedtypeql
undefinedMatch 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: , ,
sortoffsetlimittypeql
undefined顺序必须为:, ,
sortoffsetlimittypeql
undefinedSort 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
undefinedtypeql
undefinedCount
计数
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;
undefinedmatch
$c isa company, has industry $ind;
employment (employer: $c, employee: $e);
$e has department $dept;
reduce
$count = count groupby $ind, $dept;
undefinedAvailable Reducers
可用聚合函数
| Reducer | Usage | Description |
|---|---|---|
| | Count results |
| | Sum numeric values |
| | Minimum value |
| | Maximum value |
| | Average |
| | Median |
| | Standard deviation |
| | Collect into list |
| 聚合函数 | 使用方式 | 描述 |
|---|---|---|
| | 计数结果数量 |
| | 数值求和 |
| | 最小值 |
| | 最大值 |
| | 平均值 |
| | 中位数 |
| | 标准差 |
| | 收集为列表 |
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
undefinedtypeql
undefinedInsert 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 }
undefinedmatch
$p isa person, has home_address $addr;
$addr isa address { city: "Boston" };
fetch { "person": $p.name }
undefinedStruct Destructuring
结构体解构
typeql
undefinedtypeql
undefinedDestructure 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
definetypeql
defineReturn 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
undefinedfun user_exists($email: string) -> boolean:
match $u isa user, has email == $email;
return check; # 找到匹配返回true,否则返回false
undefinedUsing Functions
使用函数
typeql
undefinedtypeql
undefinedCall 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 }
undefinedmatch
$u isa user;
let $exists in user_exists($u.email);
fetch { "user": $u.name, "verified": $exists }
undefinedInline Functions with WITH
使用WITH定义内联函数
typeql
undefinedtypeql
undefinedDefine 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
undefinedtypeql
undefinedMatch 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
undefinedtypeql
undefinedUse '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);
undefinedmatch
$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);
undefinedPolymorphic Queries
多态查询
typeql
undefinedtypeql
undefinedQuery 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 }
undefinedmatch
$artifact isa! artifact, has name $n; # 仅获取直接实例
fetch { "name": $n }
undefinedGraph Traversal
图遍历
typeql
undefinedtypeql
undefinedFind 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
}
undefinedmatch
$center isa entity, has id == "target-id";
$rel links ($center), links ($neighbor);
not { $neighbor is $center; };
fetch {
"center": $center.id,
"neighbor": $neighbor.id
}
undefinedExistence Check
存在性检查
typeql
undefinedtypeql
undefinedCheck 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 must be satisfied together. Not sequential.
matchtypeql
undefinedmatchtypeql
undefinedWRONG assumption: "get all books, then find promotions"
错误假设:"获取所有书籍,然后查找促销信息"
ACTUAL: Only returns books that ARE in promotions
实际结果:仅返回参与促销的书籍
match
$b isa book;
promotion (book: $b, promo: $p);
undefinedmatch
$b isa book;
promotion (book: $b, promo: $p);
undefinedUnconstrained Variables = Cross Join
无约束变量 = 笛卡尔积
typeql
undefinedtypeql
undefinedPROBLEM: 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);
undefinedmatch
$b isa book;
book_promotion (book: $b, promotion: $p);
undefinedSymmetric Relations Return Duplicates
对称关系返回重复结果
typeql
undefinedtypeql
undefinedPROBLEM: 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
undefinedmatch
$p1 has email $e1;
$p2 has email $e2;
friendship (friend: $p1, friend: $p2);
$e1 < $e2; # 每个配对仅返回一次
undefinedCardinality Validated at Commit
基数约束在提交时验证
Insert violations don't fail immediately - only on commit.
插入违反约束的操作不会立即失败 - 仅在提交时触发错误。
Sorting Loads All Results
排序会加载所有结果
sortsortVariable Scoping in OR/NOT
OR/NOT中的变量作用域
Variables inside blocks are not guaranteed bound outside:
ortypeql
undefinedortypeql
undefinedINVALID: $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"; };
undefinedmatch
$p isa person;
employment (employee: $p, employer: $company);
not { $company has name "BadCorp"; };
undefinedVariable Reuse in OR Branches
OR分支中的变量复用
typeql
undefinedtypeql
undefinedINVALID: $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
undefinedbash
undefinedServer 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;"
undefinedtypedb console --command "transaction mydb schema" --command "define entity person;"
undefinedScript Files (.tqls)
脚本文件(.tqls)
text
undefinedtext
undefinedConsole commands without semicolons
控制台命令无需分号
transaction mydb schema
define
entity person;
commit
undefinedtransaction mydb schema
define
entity person;
commit
undefinedTransaction Lifecycle
事务生命周期
- ,
schematransactions: usewritecommit - transactions: use
readclose
- 、
schema事务:使用write提交commit - 事务:使用
read关闭close
16. Value Types Reference
16. 值类型参考
| TypeQL Type | Description | Example Literal |
|---|---|---|
| UTF-8 text | |
| true/false | |
| 64-bit signed int | |
| Double-precision float | |
| Precise decimal | |
| Date only | |
| Date and time | |
| With timezone | |
| Time duration | |
Note: is not valid syntax in some versions of TypeDB. Always use .
0dec0.0dec| TypeQL类型 | 描述 | 示例字面量 |
|---|---|---|
| UTF-8文本 | |
| 布尔值(真/假) | |
| 64位有符号整数 | |
| 双精度浮点数 | |
| 高精度小数 | |
| 仅日期 | |
| 日期和时间 | |
| 带时区的日期时间 | |
| 时间间隔 | |
注意:在部分TypeDB版本中,不是有效语法,请始终使用。
0dec0.0decDuration 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 secondstext
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
undefinedtypeql
undefinedBefore 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;
undefinedmatch
$u isa user, has status "inactive";
delete $u;
undefinedCheck Schema
检查模式
typeql
undefinedtypeql
undefinedIn 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 }
undefinedmatch
$attr sub attribute;
fetch { "attribute_types": $attr }
undefinedVerify Cardinality
验证基数
typeql
undefinedtypeql
undefinedCount 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
比较操作符
| Operator | Description | Example |
|---|---|---|
| Equal | |
| Not equal | |
| Less than | |
| Less than or equal | |
| Greater than | |
| Greater than or equal | |
| Regex match | |
| Substring match | |
| 操作符 | 描述 | 示例 |
|---|---|---|
| 等于 | |
| 不等于 | |
| 小于 | |
| 小于等于 | |
| 大于 | |
| 大于等于 | |
| 正则匹配 | |
| 子串匹配 | |
Math Operators
数学操作符
| Operator | Description | Example |
|---|---|---|
| Addition | |
| Subtraction | |
| Multiplication | |
| Division | |
| Modulo | |
| Power | |
| 操作符 | 描述 | 示例 |
|---|---|---|
| 加法 | |
| 减法 | |
| 乘法 | |
| 除法 | |
| 取模 | |
| 幂运算 | |
Expression Functions
表达式函数
| Function | Description | Example |
|---|---|---|
| Absolute value | |
| Round up (double/decimal only) | |
| Round down (double/decimal only) | |
| Round nearest (double/decimal) | |
| String length | |
| Maximum of two values | |
| Minimum of two values | |
| Get internal identifier (3.8+) | |
| Get type label (TYPE var only!) | |
| Concatenate strings | |
| 函数名 | 描述 | 示例 |
|---|---|---|
| 绝对值 | |
| 向上取整(仅double/decimal) | |
| 向下取整(仅double/decimal) | |
| 四舍五入(仅double/decimal) | |
| 字符串长度 | |
| 取两个值的最大值 | |
| 取两个值的最小值 | |
| 获取内部标识符(3.8+) | |
| 获取类型标签(仅TYPE变量!) | |
| 字符串拼接 | |
Pattern Keywords
模式关键字
| Keyword | Description |
|---|---|
| Type check (includes subtypes) |
| Exact type check (excludes subtypes) |
| Attribute ownership |
| Role player in relation |
| Identity comparison |
| Disjunction |
| Negation |
| Optional pattern |
| 关键字 | 描述 |
|---|---|
| 类型检查(包含子类型) |
| 精确类型检查(排除子类型) |
| 属性拥有关系 |
| 关系中的角色参与者 |
| 身份比较 |
| 析取(或) |
| 否定(非) |
| 可选模式 |