你好,DolphinDB Java API的使用中除了运行脚本之外,可以通过run方法直接在远程DolphinDB服务器上执行DolphinDB内置(比如问题中的columnNames函数)或用户自定义函数。这里涉及到run方法的使用方式,若run方法有两个参数,则第一个参数为DolphinDB中的函数名,第二个参数是该函数的参数。
当我们想使用run方法调用DolphinDB的函数时,可按以下步骤展开:
1.首先需要明确函数的参数列表(可在用户手册直接查询https://www.dolphindb.cn/cn/help/130/index.html);
2.其次在Java中构建对应的参数列表,命名规则如下表所示(例如table,在Java API中对应的是BasicTable)
scalar | Basic<DataType> | BasicInt, BasicDouble, BasicDate, etc. |
vector, matrix | Basic<DataType><DataForm> | BasicIntVector, BasicDoubleMatrix, BasicAnyVector, etc. |
set, dictionary, table | Basic<DataForm> | BasicSet, BasicDictionary, BasicTable. |
chart | BasicChart |
3.最后执行run方法。
下面以columnNames函数调用为例
1.首先明确columnNames语法:
columnNames(X)
参数:X可以是矩阵或表
具体可见https://www.dolphindb.cn/cn/help/130/FunctionsandCommands/FunctionReferences/c/columnNames.html
2.接下来构建参数列表
List<Entity> arguments1 = new ArrayList<Entity>(1);
BasicTable table1 = createBasicTable(5);
arguments1.add(table1);
3.执行run方法
BasicStringVector o1 = (BasicStringVector)conn.run("columnNames",arguments1);
System.out.println(o1.getString());
完整示例代码如下:
import com.xxdb.*;
import com.xxdb.data.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static String HOST = "localhost";
public static Integer PORT = 8848;
private static BasicTable createBasicTable(int n) throws Exception {
List<String> colNames = new ArrayList<String>();
colNames.add("time");
colNames.add("areaId");
colNames.add("deviceId");
colNames.add("value");
List<Vector> cols = new ArrayList<Vector>() {
};
BasicTimestampVector timestamp = new BasicTimestampVector(n);
BasicUuidVector areaId = new BasicUuidVector(n);
BasicUuidVector deviceId = new BasicUuidVector(n);
BasicDoubleVector value = new BasicDoubleVector(n);
cols.add(timestamp);
cols.add(areaId);
cols.add(deviceId);
cols.add(value);
return new BasicTable(colNames, cols);
}
public static void main(String[] args) throws Exception {
// DolphinDB 连接登录
DBConnection conn = new DBConnection();
conn.connect("localhost", 8848, "admin", "123456");
// 构建参数
// 方式一:表,BasicTable
List<Entity> arguments1 = new ArrayList<Entity>(1);
BasicTable table1 = createBasicTable(5);
arguments1.add(table1);
BasicStringVector o1 = (BasicStringVector)conn.run("columnNames",arguments1);
System.out.println(o1.getString());
// 方式二:矩阵,以BasicIntMatrix为例
BasicIntMatrix basicIntMatrix = new BasicIntMatrix(3, 3);
// rename,赋予列标签
List<String> list = new ArrayList<>(Arrays.asList("col1","col2","col3"));
BasicStringVector basicStringVector = new BasicStringVector(list);
List<Entity> renameArguments = new ArrayList<Entity>(2);
renameArguments.add(basicIntMatrix);
renameArguments.add(basicStringVector);
basicIntMatrix = (BasicIntMatrix) conn.run("rename!",renameArguments);
// 获取columnNames
List<Entity> arguments2 = new ArrayList<Entity>(1);
arguments2.add(basicIntMatrix);
BasicStringVector o2 = (BasicStringVector)conn.run("columnNames",arguments2);
System.out.println(o2.getString());
}
}
注意:本例代码中使用rename!函数增加矩阵列标签。