本节为您介绍如何在GQL语句中使用Connection
对象的gql()
方法和gqlStream()
方法查询数据库。
每个示例主要展示如何使用所列方法。点击完整示例查看完整代码示例。
GQL(图查询语言)是符合ISO标准的图数据库查询语言。更多GQL的详细信息,请参阅本文档。
gql()
在当前图集或数据库上执行UQL查询语句并返回查询结果。
参数:
String
:待执行的GQL查询语句。RequestConfig
(可选):请求配置,设置为null
时忽略该设置。
返回值:
Response
:请求的结果。
// 获取图集miniCircle中movie下的5个点并打印其名称
RequestConfig requestConfig = new RequestConfig();
requestConfig.setGraphName("miniCircle");
Response response = client.gql("MATCH (n:movie) RETURN n LIMIT 5", requestConfig);
List<Node> nodeList = response.alias("n").asNodes();
for (Node node : nodeList) {
System.out.println(node.get("name"));
}
The Shawshank Redemption
Farewell My Concubine
Léon: The Professional
Titanic
Life is Beautiful
更多示例,请参阅嬴图数据与Java类型映射。
gqlStream()
在当前图集或数据库上执行GQL查询语句并以增量形式返回查询结果。在处理大型数据集时,无需立刻加载所有数据至内存中。
参数:
String
:待执行的GQL查询语句。UqlListener
:流处理监听器。RequestConfig
(可选):请求配置;设置为null
时忽略该设置。
返回值:
void
// 获取图集miniCircle的1步路径
RequestConfig requestConfig = new RequestConfig();
requestConfig.setGraphName("miniCircle");
client.gqlStream("MATCH p = ()-[]-() RETURN p", new UqlListener() {
int count = 0;
public void onReady() {
System.out.println("Start downloading");
}
public void next(Response response) {
if (response.getStatus().getErrorCode() != Ultipa.ErrorCode.SUCCESS){
System.out.println(response.getStatus().getMsg());
}
Graph graph = response.get(0).asGraph();
List<Path> paths = graph.getPaths();
count += paths.size();
System.out.println("count = " + count);
}
public void onComplete() {
System.out.println("Done");
System.out.println("count = " + count);
}
public void onError(Throwable throwable) {
System.out.println("Error");
}
}, requestConfig);
count = 1250
count = 1392
Done
count = 1392
完整示例
package com.ultipa.www.sdk.api;
import com.ultipa.sdk.UltipaDriver;
import com.ultipa.sdk.connect.conf.RequestConfig;
import com.ultipa.sdk.connect.conf.UltipaConfiguration;
import com.ultipa.sdk.operate.entity.Node;
import com.ultipa.sdk.operate.response.Response;
import java.util.*;
public class Main {
public static void main(String[] args) {
// 设置连接
UltipaConfiguration myConfig = UltipaConfiguration.config()
// URI示例: .hosts("mqj4zouys.us-east-1.cloud.ultipa.com:60010")
.hosts("192.168.1.85:60061,192.168.1.86:60061,192.168.1.87:60061")
.username("<username>")
.password("<password>");
UltipaDriver client = null;
try {
// 建立与数据库的连接
client = new UltipaDriver(myConfig);
// 配置请求
RequestConfig config = new RequestConfig();
config.setGraphName("amz");
// 获取10个点并打印返回的第一个点的 _id和storeName属性值
Response response = client.gql("MATCH (n) RETURN n LIMIT 10", config);
List<Node> nodeList = response.alias("n").asNodes();
System.out.println("ID of the 1st node: " + nodeList.get(0).getID());
System.out.println("Store name of the 1st node: " + nodeList.get(0).get("storeName"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (client != null) {
client.close();
}
}
}
}