MQL语法说明
数据类型
字符串类型
类型名称 | 类型描述 | 备注 |
---|---|---|
text | UTF-8编码的字符串 | 每个单词进行分词 |
varchar | UTF-8编码的字符串 | 不对单词进行分词 |
数值类型
类型名称 | 类型描述 | 备注 |
---|---|---|
int | 32位有符号整数 | - |
bigint | 64位有符号整数 | - |
double | 64位IEEE-754浮点 | - |
float | 32位IEEE-754浮点 | - |
时间类型
类型名称 | 类型描述 | 备注 |
---|---|---|
timestamp | 64位有符号整数,表示时间(1970年1月1日格林威治标准时间00:00:00)以来的日期和时间,以毫秒为单位 | 'yyyy-mm-dd [hh:MM:ss[.fff]][+/-NNNN]' => '2015-05-03 13:30:54.234-0800', '2015-05-03 13:30:54+0400', '2015-05-03' |
date | 编码的64位有符号整 数,表示自午夜以来的 毫微秒数,没有相应的 日期值 | 'yyyy-mm-dd ' => '2015-05-03' |
集合类型
类型名称 | 类型描述 | 备注 |
---|---|---|
map |
一组键值,其中键是唯一的,并且映射按键排序 | {key1:value1,key2:value2...} |
set< varchar ,float,double,int> | 逗号分隔的从零开始排序的唯一值列表 | [value1,value2...] |
list< varchar ,float,double,int> | 逗号分隔相 同数据类型 的非唯一值 列表, 元素 按列表中的 位置排 序; 第一个 位置是零 | [value1,value2...] |
Bucket{ type: tsdb} | json格式 | 用于存储时序数据 |
Bucket{ type: biglog} | json格式 | 用于存储日志数据 |
其他类型
类型名称 | 类型描述 | 备注 |
---|---|---|
blob | 一组键值对,其中键是唯一的,并且映射按键排序 | Blob 数据类型表示定义为0X(十六进制)开头的十六进制常数,适用于存储图像或其他二进制文件。例如,0xcafe。 |
enum | 枚举类型 | 是一个小的二维表,行数小于65536, 用于定义常量类型 。例如 enum { "0":["Unknown", "未知"], "1":["Ready", "就绪"], "2":["Waiting", "等待"], "3":["Running", "运行中"], "4":["Succeeded", "成功"], "5":["Failed", "失败"], "6":["Cancelled", "取消"], "7":["Skipped", "忽略"], "8":["Timeout", "超时"], "9":["Delete", "删除"] } |
boolean | 真或假。内部存储为 true 或 false1或者0 | - |
对象类型
类型名称 | 类型约束 | 类型描述 | 备注 |
---|---|---|---|
类的名称(Nickname或者全路径类名) | [$MinCount..$MaxCount] | 用户可以将通过create class创建创建的类型作为其他类的字段 | wheel[0..?]约束为0到多 wheel[2..4]约束为2到4 wheel[?]无约束 wheel[4..4]约束为4 wheel[2..?]约束为2到多 |
--定义轮子对象
create class if not exists wheel:/matrix/entity (
name varchar,
remark varchar,
indexes(name,remark)
) with key=manu;
--定义车,有轮子的属性
create class if not exists car:/matrix/entity (
name varchar,
wheel Wheel[4..4],
remark varchar,
indexes(remark)
) with key=manu;
面向对象建模
类型重定义
通过typedef关键字,可以将基础数据类型、集合类型、对象类型等进行重命名
--定义typedef定义
typedef MyInteger = int;
类的组合和聚合
支持通过对象类型方式,实现面向对象的组合和聚合关系
--定义轮子对象
create class if not exists wheel:/matrix/entity (
name varchar,
remark varchar,
indexes(name,remark)
) with key=manu ;
--定义车
create class if not exists car:/matrix/entity (
name varchar,
wheel Wheel[4..4],
remark varchar,
indexes(remark)
) with key=manu ;
--支持插入和查询:
--插入轮子
Insert into wheel (id,name) values ('wheel:id101','id101');
Insert into wheel (id,name) values ('wheel:id102','id102');
Insert into wheel (id,name) values ('wheel:id103','id103');
Insert into wheel (id,name) values ('wheel:id104','id104');
--插入车
Insert into Car (id,name) values ('Car:id10', ['wheel:id101','wheel:id102','wheel:id103','wheel:id104'])';
Select wheel.name,id from Car where id='Car:id10';
--返回结果
Wheel ID
[['id101'],['id102'],['id103'],['id104']] Car:id10
[!NOTE]
car:/matrix/entity ,父对象如果定义了NickName,可使用缩减形式car:entity
类的继承
通过继承方式创建类,实现父类属性的继承,以及实现从父类向子类的泛华查询
--定义Car
create class if not exists car:/matrix/entity (
name varchar,
wheel Wheel[4..4],
remark varchar,
indexes(remark)
) with key=manu ;
--创建继承Car的camry类
create class if not exists /matrix/entity/car/camry (
capacity list<double> "容量",
lightsize list<int> "灯大小",
speed MyInteger "速度",
index( capacity,lightsize,speed)
)with ttl=366 day , key=manu, alias='camry' , nickname='camry' ;
DDL数据定义
类创建
CREATE CLASS [IF NOT EXISTS] <classname>(
column type display_name,
...
INDEX(column,column),
KEYS(column,column)
)[WITH property=value,property=value];
[!NOTE]
- 类和字段名称不区分大小写
Property | 描述 | 举例 |
---|---|---|
autosearch | 是否进行自动搜索 | 0:false, 1:true,default:1(可以不写) |
ttl | 数据过期设置,只对版本数据有效 | 30 day、1 month、720 hour 单位:second , minute , day , month, year |
alias | 类的别名 | Alias='别名' |
nickname | 类的简单写法 | nickname='缩写',nickname区分大小写 |
ckeys | 集群键,系统将根据集群键在同一台服务器进行自动的排序 | ckeys=(field1 asc/desc ,field2 asc/desc) |
partition | 分布式分区设置,按照设置进行跨服务器的分区存储。 支持 int、 bigint、bool、timestamp、enum、 varchar 、text类型 |
partition=(field1,field2) |
key | 设置主键的产生方式的类型。 包括 sequence, hash,uuid;默认为 hash,建议使 用 hash 效率较高 |
key=sequence |
[!NOTE]
- Property:partition,ckeys不能同时使用,即column在partition中,就不能出现在ckeys中
- partition,ckeys当需要多个字段的时候,需要使用()括起来,如:ckeys=(field1 asc|desc,field2 asc|desc)
普通类创建举例
create class if not exists /matrix/entity/mydevice (
model varchar '型号',
type enum{
"1000":["computer", "服务器"],
"1001":["network", "网络设备"],
"1002":["software", "软件"]
} '类型',
company varchar '厂商',
ctel varchar '厂商联系电话',
sn varchar '序列号',
host varchar '主机名',
ip varchar 'IP地址',
dc varchar '数据中心',
room varchar '房间',
rack varchar '机柜',
unit varchar '机架',
location varchar '地点',
region varchar '所属地点',
biz varchar '所属业务',
department varchar '负责部门',
contact varchar '联系人',
tel varchar '联系人电话',
assetid varchar '资产编号',
period date '保修期',
config map<varchar,varchar> '详细配置',
files map<varchar,varchar> '配置文件列表',
element map<varchar,varchar> '组成实体的元素',
indexes(model,type,company,ctel,sn,host,ip,dc,room,rack,unit,location,region,biz,department,contact,tel,period),
keys(sn,model,type,company,dc,host,ip)
) with ttl=366 day, autosearch, Alias='实体',nickname='entity',ckeys=(dc,room);
create class if not exists /matrix/entity/ups () with alias='UPS电源';
包含bucket时序数据属性创类语句例子
create class if not exists /test/donghuan/A (
ip varchar "ip" ,
deviceoid varchar "OID" ,
devicename varchar "设备名称" ,
perfstructure varchar "性能结构描述",
desc varchar "设备描述",
disk_perf bucket {
"crc": [ "mount_point" ],
"desc": ["空闲磁盘", "空闲磁盘百分比", "已使用磁盘空间", "磁盘总空间", "已使用磁盘空间百分比", "文件系统" ],
"params": [
[ "mount_point", "string", "", "${desc[5]}" ],
[ "free", "int", "MB", "${desc[0]}" ],
[ "pfree", "float", "%", "${desc[1]}"],
[ "used", "int", "MB", "${desc[2]}"],
[ "total", "int", "MB", "${desc[3]}"],
[ "pused", "float", "%", "${desc[4]}"]
],
"ttl":365,
"type": "tsdb"
} "磁盘1",
keys(ip,devicename,deviceoid),
indexes(ip,devicename,deviceoid)
) with alias='A', nickname='A';
如果bucket字段的属性太多,且具备一定的规律,可采用以下矩阵模式创建bucket字段
create class if not exists /test/donghuan/A (
ip varchar "ip" ,
devicename varchar "设备名称" ,
deviceoid varchar "OID" ,
perfstructure varchar "性能结构描述",
desc varchar "设备描述",
values bucket {
"type" : "tsdb",
"params": [
["${1-5}","int","","${desc[0-4]}","1-5"],
["${6-9,11-12,15-16,19-20}","int","MB","${desc[5-8,10-11,14-15,18-19]}","6-9,11-12,15-16,19-20"],
["10","int","%","${desc[9]}","10"],
["${13-14,17-18}","int","KB/s","${desc[12-13,16-17]}","13-14,17-18"]
],
"desc": ["在线点","及早期火警","及早期预警","DO1","DO2","系统分区总容量","系统分区剩余量","数据分区总容量","数据分区剩余量","CUP使用率","内存总容量","内存剩余量","网卡1上行速度","网卡1下行速度","网卡1上行总量","网卡1下行总量","网卡2上行速度","网卡2下行速度","网卡2上行总量","网卡2下行总量"],
"ttl" :365
} 'full',
keys(ip,devicename,deviceoid),
indexes(ip,devicename,deviceoid)
) with alias='A', nickname='A';
[!NOTE]
- ${1-5,8,10,12}是指多个列,包含1,2,3,4,5,8,10,12
- ${'str1','str2','str3'}是指多个列,包含str1,str2,str3
- "desc${1-3}str"是指多个列,包含desc1str,desc2str,desc3str
- "desc${10;1;2}"是指多个列,包含desc1,desc3,desc5,desc7,desc9
- 支持数组变量定义和使用,例如上例中desc数组变量声明后,在定义里可以对该数组引用
包含bucket日志流数据属性创建类语句示例
[!NOTE]
- files 用于定义允许的文件名,支持*和?作为通配符号
- pattern 和上面允许的文件的pattern对应,定义每类文件的时间戳格式
- sample 和上面允许的文件的pattern对应,用样例形式定义每类文件的时间戳,pattern和sample只需定义一种即可,数组大小必须和files的个数匹配
create class if not exists /matrix/entity (
host varchar "host",
ip varchar "ip",
location varchar "地点",
logs bucket {
"files":["*.log","*ncolog"],
"pattern":["MMM DD HH:mm:ss","MMM DD HH:mm:ss"],
"ttl":90,
"type":"bitlog"
} "simple",
model varchar "型号",
type enum {
"1000":["computer", "服务器"],
"1001":["network", "网络设备"],
"1002":["software", "软件"]
}"类型",
keys(host,ip,model,type) ,
index(host,ip,location,model,type)
)with ttl=90 day , autosearch=true , alias='entity' ;
时间Pattern定义说明
{"YYYY","2006","[1-2]\\d{3}"},
{"YY","06", "\\d{2}"},
{"MMMM", "January","[A-Z][a-z]{2,8}"},
{"MMM", "Jan", "[A-Z][a-z]{2}"},
{"MM", "01", "[0-3]\\d"},
{"M","1","\\d{1,2}"},
{"DDDD", "Monday","[A-Z][a-z]{5,7}"},
{"DDD","Mon","[A-Z][a-z]{2}"},
{"DD","02", "\\d{2}"},
{"_D", "_2","(?:\\d{1}|\\d{2})"},
{"D","2", "\\d{1,2}"},
{"HH", "15","\\d{2}"},
{"hh", "03","\\d{2}"},
{"h", "3","\\d{1,2}"},
{"mm", "04","\\d{2}"},
{"m", "4","\\d{1,2}"},
{"ss", "05","\\d{2}"},
{"s", "5", "\\d{1,2}"},
{".SSS",".999999999",".\\d{3,}"},
{",SSS",".999999999", ",\\d{3,}"},
{"P","PM","(?:am|AM|pm|PM)"},
{"ZZZZZ","-07:00", "[+-][0-9]{2}:[0-9]{2}"},
{"ZZZZ","-0700", "[+-][0-9]{4}"},
{"ZZZ", "MST", "[A-Z]{3}"},
{"ZZ", "Z07:00", "Z[0-9]{2}:[0-9]{2}"},
更改类定义
ALTER CLASS<Class Name> Add[Index] Column
column mql_type display_name,
column mql_type display_name;
ALTER CLASS<ClassName> Delete|Drop Column column,column;
ALTER CLASS<ClassName> With|Setproperty=value,property=value;
ALTER CLASS<ClassName> renameOld_Column New_Column display_name;
Property说明
Property | 描述 | 举例 |
---|---|---|
autosearch | 是否进行自动搜索0:no,1:yes | default:1(可以不写 |
ttl | 数据过期设置 | 30 day 或者1 month 或者720 hour 单位:second , minute , day , month, year |
Alias | 类的别名 | - |
举例
alter class /matrix/entity/ups add index column test varchar '测试', test2 int '';
alter class /matrix/entity/ups delete Column test,test2;
alter class /matrix/entity/ups set autosearch=true;
Bucket字段类型更改定义
ALTER CLASS<Class Name> Add Column bucket{
bucket attribute
} display_name;
ALTER CLASS<ClassName> Delete|Drop Column column,column;
#日志类型bucket支持增加文件名和时间格式pattern
ALTER CLASS<Class Name> MODIFY Column ADD PATTERN{"files":["filepattern"],"pattern":["timepattern"]};
举例
#增加一个日志的bucket字段
alter calss /matrix/entity add column logs bucket {
"type":"bitlog",
"files":["*.log","*ncolog"],
"pattern":["MMM DD HH:mm:ss","MMM DD HH:mm:ss"],
"ttl":90
} "simple";
#为一个日志bucket字段增加一个filepattern和timepattern
alter class /matrix/entity modify logs add pattern{"files":["*ncolog"],"pattern":["MMM DD HH:mm:ss"]};
DML数据操纵语言
SELECT语句
SELECT [DISTINCT] (field,field...|'*' |FUNCTION)
FROM ClassName,ClassName
[JOIN ()
[WHERE LuceneConditions]
[GROUP BYGroupExp]
[ORDER BYOrderExp]
[LIMIT(integer) ]
[WITH Version]
[HAVING Condition]
LuceneConditions 说明
Lucene 表达式 | 描述 | 举例 |
---|---|---|
MatchOP | 相等与恒等判断 | field = value => 当value中包含?自动转换为like查询 field == value => 忽略value中的 ? |
IsOP | 是否为空判断 | field is 'nil' |
IsNotOP | 是否不为空判断 | field isnot 'nil' |
FuzzyOP | 模糊匹配 | field ~ 'StringValue' ,近似查询 |
LikeOP | 精确匹配 | field like 'StringValue',支持 * ?通配符号 |
PrefixOP | 开始匹配 | field =^ 'StringValue' |
RangeOP | 区间判断 | >=,>,< ,<= |
ContainOP | 包含判断 | filed in (String List) |
LogicOP | 逻辑运算 | &&,||,and,or |
Function说明
Function名称 | 描述 | 举例 |
---|---|---|
min | 最小 | min(field) |
max | 最大 | max(field) |
avg | 平均 | avg(field) |
count | 统计记录数量 | count(field) |
sum | 计算和 | sum(field) |
writetime | 更新时间 | writetime(field) |
举例
带版本的数据查询
#order by举例
select type from /matrix/filesystem where parent like '/home*' orderby typelimit 10 with version;
#group by举例:
select type,count(*) from /matrix/filesystem where parent like '/home*' group by type order by type limit 10 with version;
#having举例:
select type,count(*) from /matrix/filesystem where parent like '/home*' group by type order by type with version having count(*) >3;
不带版本的对象数据查询
#order by举例
select type from /matrix/filesystem where parent like '/home*' order by type limit 10;
#group by 举例
select type,count(*) from/matrix/filesystem where parent like '/home*' group by type order by type limit 10;
INSERT语句
INSERT INTO ClassName field=value,field= value,field=value;
举例
insert into /matrix/test (day,id,name,vtime) values (1123443223,'test', ' 测试',1123443223);
UPDATE语句
UPDATE ClassName SET field=value,field= value,field=value WHERE LuceneConditions;
LuceneConditions说明
|Lucene表达式 |描述 |举例|
|-|-|-|
|MatchOP |相等判断 |field = value => 当value中包含?自动转换为like查询
field == value => 忽略value中的 ?|
|IsOP |是否为空判断 |field is 'nil'|
|IsNotOP |是否不为空判断 |field isnot'nil'|
|FuzzyOP |模糊匹配 |field ~'StringValue'|
|LikeOP |精确匹配 |field like'StringValue'|
|PrefixOP |开始匹配 |field =^ 'StringValue'|
|RangeOP |区间判断| >=, >, <, <= |
|ContainOP |包含判断 |filed in(StringList)|
|LogicOP |逻辑运算 |&&,and,||,or|
举例
update /matrix/test set day=1123443223, id = 'test', name="测试2",vtime=1123443223 WHERE id='test';
DELETE语句
DELETE FROM ClassName,ClassName [WHERE LuceneConditions] [WITHVersion];
Lucene Conditions说明
Lucene表达式 | 描述 | 举例 | ||
---|---|---|---|---|
MatchOP | 相等判断 | field=value | ||
IsOP | 是否为空判断 | field is 'nil' | ||
IsNotOP | 是否不为空判断 | field isnot'nil' | ||
FuzzyOP | 模糊匹配 | field ~'StringValue' | ||
LikeOP | 精确匹配 | field like'StringValue' | ||
PrefixOP | 开始匹配 | field =^ 'StringValue' | ||
RangeOP | 区间判断 | >=, >, <, <= | ||
ContainOP | 包含判断 | filed in(StringList) | ||
LogicOP | 逻辑运算 | &&,and,\ | \ | ,or |
举例
不带版本的删除
delete from /matrix/test where id='test';
带版本的删除
delete from /matrix/test where id='test' with version;
集合类型操作
测试样例
creat eclass if not exists /matrix/test(
field1 date "field1",
field2 timestamp "field2",
field3 bigint "field3",
field8 map<varchar,varchar> "field8",
field10 list<varchar> "field10",
keys(field1) ,
index(field1,field2,field3, field8,field10)
)with alias="test" ,nickname="test";
Map操作
#插入
insert into test(name,field1,field2,field3,field8) values('11','2019-12-12',1341123451231,11,{"k1":"v1","k2":"v2","k3":"v3"});
#更新
update test setfield8=field8+{"k4":"v4"} where name='11';
update test setfield8=field8- "k4"where name='11';
Set和List操作
#插入
insert into test(name,field1,field2,field3,field10) values ('11','2019-12-12',1341123451231,11,["str1","str2","str3"]);
#更新
update ckeys test set field10=field10+"str4" where name='11';
update ckeys test set field10=field10- "str4" where name='11';
#查询
select id,config["field1","field2"],email[0,2] from /matrix/entity/people where id="people:张三";
[!NOTE] config为map类型,email为set或list类型
支持函数
字母转小写函数
lower ( str text)
例如:lower(Abc) -- abc
字母转大写函数
upper ( str text)
例如:upper (Abc) -- ABC
字符串左侧去空函数
ltrim ( str text)
例如:ltrim(' Abc') -- Abc
字符串右侧去空函数
rtrim ( str text)
例如:rtrim('Abc ') --Abc
左右侧同时去空函数
trim ( str text)
例如:trim(' Abc ') --Abc
截取子字符串函数
substring ( str text, st int, len int) 例如:substring('Abcd', 2, 2) --cd
转化为时间戳函数
timestamp ( input text, pattern text )
例如:timestamp('2021/11/01 12:23:21', 'YYYY/MM/DD HH:mm:ss')
格式化时间函数
dateformat ( input timestamp, pattern text )
例如:dateformat('1335644345000','YYYY/MM/DD HH:mm:ss')
Bucket数据类型操作
Bucket时序数据类型数据操作
#指定采集时间插入
insert into /matrix/testbucket(id, buck) values ('id12342345',[2,nil,3.5,6.6,'1234567890']) at'2020-05-1212:12:12';
#利用插入时间作为采集时间
insert into /matrix/testbucket(id,buck) values('id12342345',[2,nil,3.5,6.6,'1234567890']) at'';
#指定bucket字段插入
insert into /matrix/testbucket(id,buck['field1','field2','field3','field4','field5'])values('id12342345',[2,nil,3.5,6.6,'1234567890']) at'2020-05-1212:12:12';
#bucket查询
select id,buck["field1",field2"].time('2020-05-2012:12:12","2020-05-2220:20:20").find("field1">10).find("field2"<20).limit(101,100).titile() from/matrix/entity/switch where id='switch:switch1'
[!NOTE]
- buck是一个定义的bucket类型字段(见类创建)
- field1和field2是bucket这个字段类型里包含的列
- time(起始时间,终止时间)是针对于bucket提供的时间过滤函数,可以是字符串形式'2020-05-2012:12:12"或"2020-05-20",也可以是时间戳方式
- find(index|fieldRangeOPvalue)是针对于bucket提供的数据过滤函数,例如find(1>10)或find("field1">10),每个find只能写一组条件,如需多个条件,可使用多个find limit([offset],limit)是限制返回数量,例如:limit(100,10)或者limit(10)
- title()是返回field1,field2的字段
- distinct()是对bcket指定字段的返回值进行相同合并操作
Bucket日志流数据类型数据操作
单条日志插入
insert into /matrix/testbucket(id,logs['a.log']) values('itm:node3',["May1512:23:21192.168.190.175 Error This is a log message"])
多条日志同时插入
insert into /matrix/entity/itm (id,logs['a.log']) values('itm:node3',['
May 15 12:23:21 192.168.190.175 Error This is a log message
May 15 12:23:21 192.168.190.175 Error This is a log message
May 15 12:23:21 192.168.190.175 Error This is a log message']);
bucket查询
SELECT id,logs["ncolog.log",'aaa.log'].time('2020-06-11','').find("ssl_req").limit(10,10) FROM /matrix/entity/it/it_aix where id='it_aix:192.168.190.175';
[!NOTE]
- logs是一个定义的bucketbiglog类型字段(见类创建)
- ncolog.log,aaa.log是指定查询日志文件
- time(起始时间,终止时间)是针对于bucket提供的时间过滤函数,可以是字符串形式'2020-05-2012:12:12"或"2020-05-20",也可以是时间戳方式
- find(keystring)是针对于bucket提供的数据过滤函数,例如find("key1 key2") 含义为包含key1和key2的日志,find("fkey1" "key2")含义为包含key1或者包含key2的日志
- limit([offset],limit)是限制返回数量,例如:limit(100,10)或者limit(10)
- file()是返回查询到的日志的文件,不能与limit同时使用
轻量Transaction
通过关键字BEGAIN BATCH......END实现轻量级Transaction功能。
BEGIN BATCH
insert into /matrix/test/batch(v_varchar,v_text,v_int,v_bigint,v_float,v_double,v_smalldouble,v_bool)values('500','helloword2003',-400,400,1.1,1.1234567890123456,1.123456,false );
insert into /matrix/test/batch(v_varchar,v_text,v_int,v_bigint,v_float,v_double,v_smalldouble,v_bool)values('600','helloword2003',370,370,1.1,1.1234567890123456,1.123456,true );
insert into /matrix/test/batch(v_varchar,v_text,v_int,v_bigint,v_float,v_double,v_smalldouble,v_bool)values('700','helloword2003',580,580,1.1,1.1234567890123456,1.123456,true );
insert into /matrix/test/batch(v_varchar,v_text,v_int,v_bigint,v_float,v_double,v_smalldouble,v_bool)values('602','helloword2003',-370,-370,1.1,1.1234567890123456,1.123456,true );
insert into /matrix/test/batch(v_varchar,v_text,v_int,v_bigint,v_float,v_double,v_smalldouble,v_bool)values('708','helloword2003',-580,-580,1.1,1.1234567890123456,1.123456,true );
END
分页功能支持
通过limit关键字支持分页查询功能
#类似于MySQL的offset功能,3为offset,4为limit
SELECT id,name from/matrix/devops/event limit 3,4;
关系类型操作
创建关系类型
create edge type <关系类型> <关系名称>
举例
create edge type refer '引用' --创建关系
更新关系类型描述
alter edge type <关系类型> <关系名称>
举例
alter edge type refer '指引'
[!NOTE] 只能更新关系名称,不能更新关系类型
删除关系类型
drop edge type <关系类型>
drop edge type refer --删除关系
关系数据更新与查询
关系数据创建
#插入数据时,插入关系信息,使用mql insert语句
create("biz:数字国网")-[:contain{"intp":1,"floatp":3.4}]->("app:test2"),("biz:数字国网")-[:contain]->("app:test1");
#删除某对象的某个关系或者节点,使用mql update语句
match("biz:数字国网")-[r1:contain]->(n1:"app:test1") remove r1,n1 ;
关系数据查询
Node语法
在MQL cypher里面通过用一对小括号()表示一个节点,它在cypher里面查询形式如下:
() 代表匹配任意一个节点
("CLASS:Node") 代表匹配任意一个节点,并给它起了一个别名,例如:
("swtich:switch01")
(:CLASS) 代表查询一个类型的数据,例如:(:swtich)
(Variable:CLASS) 代表查询一个类型的数据,并给它起了一个别名,例如:(s:switch)
(Variable:CLASSwhereConditions) 查询某个类型下,节点属性满足某个值的数据
例如 match(:switch where name='*switch2' or id='switch:switch2')-[*1]->("esx:*")
关系语法
关系用一对
-
和<
或者>
组成,关系有方向分进和出,不带<
或者>
的节点为出方,带的节点为进方,如果两个节点都无方向箭头,则为同时为进和出。
1、节点-[*]->节点或 节点<-[*]-节点 从一个节点任意关系指向另一个节点,
例如:match ("biz:查账系统")-[*]->("linux:*")
2、节点-[:relation]->节点 或者 节点<-[:relation]-节点 从一个节点指定关系指向另一个节点,
例如:match("biz:查账系统")-[:contain]->("linux:*")
3、节点-[:relation*stepNum]->节点 或者 节点<-[:relation*stepNum]-节点 从一个节点指定关系,且指定中间跳数指向另一个节点,
例如:match("biz:查账系统")-[:contain*3]->("linux:*")
4、节点-[:relation where conditions*]->节点 或者节点<-[:relation where conditions*]-节点 从一个节点指定关系,且指定中间跳数指向另一个节点,
例如:match("biz:查账系统")-[:contain where intp=1 and floatp>3*]->()
模式语法
模式语法是节点和关系查询语法的结合,通过模式语法我们可以进行我们想要的任意复杂的查询
#模式1
(节点)-[关系]->(节点)-[关系]->(节点)......
或者
(节点)<-[关系]-(节点)<-[关系]-(节点)......
#模式2
......(节点)-[关系]->(节点)<-[关系]-(节点)......
#模式3
......(节点)<-[关系]-(节点)-[关系]->(节点)......
#模式4
(节点)-[关系]->(p:节点)<-[关系]-(节点),(p)<-[关系]-()
控制关键字
为了对增强用户对查询的结果控制,MQL cypher提供了一些查询结果控制的关键字
1、attr 控制返回节点的属性和关系的属性,节点属性,使用属性名称,关系属性,使用.
属性名称(.*为所有关系属性),
例如:match("biz:数字国网","biz:开发测试")-[*]->() with attr=(name, status, .*)
2、until设置返回节点挡板,当查询到until后节点时,停止继续向下查询,例如:
match("biz:查账系统")-[:contain]->("cluster:查账系统web集群")-[*]->() until "switch:*"
3、[short|long|all] path控制返回最短路径或者最长路径,例如:
match(b:"biz:B*")-[*]->(e:"esx:B*")-[*1]->(s:"switch:Bswitch1") short path b,e,s;
4、back设置查询历史某时刻的配置关系,例如:
match("biz:B查账系统")-[:contain]->("cluster:B查账系统web集群")-[*]->() back '2019-06-1913:04:00';
5、diff比对当前时刻配置关系和历史某时刻的配置关系,例如:
match("biz:B查账系统")-[:contain]->("cluster:B查账系统web集群")-[*]->() diff '2019-06-1913:04:00';
6、level控制查询最大跳数,默认为10
match("biz:数字国网","biz:开发测试")-[*]->() with level=20;
7、tag子图功能
match(a:"biz:查账系统")-[*]->("linux:*")-[*1]->("esx:esx4") add "tag5" in a;
match(a:"biz:查账系统")-[*1]->("biz:认证系统") in "tag5";
match(a:"biz:查账系统")-[*]->("linux:*")-[*1]->("esx:esx4") remove tag("tag5",...) in a;
8、with inline部件查询功能,实现跨部件的查询和组件的自动收缩
match(a:"node:node1")-[*1]->() with inline
[!NOTE]
- 部件查询,因为部件是一种特殊的实体,需要数据规范
- 实体id:
- 类名:实体唯一标识 例如:node:node1
- 部件id:
- 部件类名:部件唯一标识#所属实体类名:所属实体唯一标识
- 部件的所属关系指向实体
关系查询举例
#例如查询和查账系统相关,与esx具有连接关系,且在发生5级告警的交换机,列出他们的主机名和IP地址。
select host,ip from /matrix/devops/event/omnibus o join ("biz: 查 账 系 统")-[*]->("esx:*")-[:connect*]->(h:switch) on o.entity=h.id where o.severity=5;
#以下举例的测试数据为以下内容:
match("biz:数字国网","biz:开发测试")-[*]->() with attr=( name, status , .* )
match("biz:查账系统")-[*]->("esx:esx1") with attr=( name, status )
match('linux:wecise')-[*]->()-[*]->("etcd:etcd1")
match("biz:查账系统")-[*]->("linux:linux[1-5]")-[*1]->("esx:esx1")
match("biz:查账系统")-[*]->("linux:*")-[*1]->("esx:esx4")
match(b:"biz:*")-[*]->(e:"esx:*")-[*1]->(s:"switch:*")pathb,e,sshort[longall]
match("linux:*")-[*1]->("esx:*")
match("biz:查账系统")-[:contain]-("cluster:查账系统web集群")-[*]-()
match(m:"biz:查账系统")-[*]->(p:"linux:linux[1-5]")-[*]->(q:"esx:esx4") path m,p,q
match ("biz:B查账系统")-[:contain]->("cluster:B查账系统 web集群")-[*]->() until "switch:*" back '2019-06-1913:04:00'
match ("biz:B查账系统")-[:contain]->("cluster:B查账系统 web集群")-[*]->() until "switch:*" diff '2019-06-1913:04:00'
关系查询优化
关系查询执行策略,可以通过逗号隔开,并严格按照逗号隔开顺序执行,用户可以使用这一特性,优化查询效率。原则为: 1.尽量为一跳查询的组合 2.尽量为确定的查询放在最前面,以缩小查询结果的数量
例如:
match ("perbasisinfo:320911197112273412")<-[:belong:yongy*2]-(p:phonenumber)<-[:callto:bycall*1]
- (h:/matrix/action/calllog where starttimestr >='2020-03-01' and starttimestr<='2020-03-30' limit 50)-[:callto:bycall*1]->(:phonenumber)
可优化成为:
match ("perbasisinfo:320911197112273412")<-[:belong:yongy*2]-(p:phonenumber),
(p)<-[:callto:bycall*1]-(h:/matrix/action/calllog where starttimestr>='2020-03-01' and starttimestr<='2020-03-30' limit 50),
(h)-[:callto:bycall*1]->(:phonenumber)
JOIN查询
[!NOTE] 目前只支持inner join,建议以大表join小表
SELECT field(s)
FROM ClassName alias1
JOIN (alias2:ClassName [where LuceneConditions]) or (graph query block)
ON alias1.field=alias2.field
[ WHERE LuceneConditions]
[ORDER BY OrderExp]
[LIMIT(integer)]
图表联查
为了能够在具有复杂关系逻辑条件的情况下,实现动态知识的查询表达,平台支持图表联查功能。
JOIN查询举例
select host,ip from /matrix/devops/event/omnibus o join ("biz: 查账系统")-[*]->("esx:*")-[:connect*]->(h:switch) on o.entity=h.id whereo.severity=5;
select entity,msg,host,i.id,i.name from /matrix/devops/event/ e join (i:/matrix/entity/switch) on e.entity=i.id and e.entity=i.name limit -1 where entity like 'switch:*' ;
select count(*) from /matrix/devops/event/ e join (i:/matrix/entity/switch where id='switch:switch1' or name='switch:switch2') on e.entity=i.id and e.entity=i.name limit -1 where entity like 'switch:*';
select entity,msg,host,i.id,i.name,p.param,p.value from /matrix/devops/event/ e join (i:/matrix/entity/switch where id='switch:switch1' or name='switch:switch2') on e.entity=i.id
and e.entity=i.name join (p:/matrix/devops/performance/ where entity like 'switch:*' and value>30) on e.entity=p.entity limit-1 where entity like 'switch:*';
select entity,msg,host,i.id,i.name,p.entity,p.param,p.value,l.host,l.msg from /matrix/devops/event/ e join (i:/matrix/entity/switch where id='switch:switch1' or name='switch:switch2') on e.entity=i.id and e.entity=i.name join
(p:/matrix/devops/performance/whereentitylike'switch:*'andvalue>30) on e.entity=p.entity join (l:/matrix/devops/log where entity like 'switch:*' and msg like '*error*') on e.entity=l.entity limit -1;