OrientDB 结合Java的使用

maven配置

        <dependency>
            <groupId>com.orientechnologies</groupId>
            <artifactId>orientdb-client</artifactId>
            <version>3.2.21</version>
        </dependency>
        <dependency>
            <groupId>com.orientechnologies</groupId>
            <artifactId>orientdb-graphdb</artifactId>
            <version>3.2.8</version>
        </dependency>

添加vertex 类

    public static void addVertexClass() {
        OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/haha", "root", "root");
        OrientGraph graph = factory.getTx();
        graph.createVertexType("abcd");
        graph.commit();
        factory.close();
    }

其中 new OrientGraphFactory("remote:localhost/haha", "root", "root");

中的第一个参数可以是remote表示远程连接,也可以是

plocal:/path/to/your/databases

表示连接的是本地(orientdb创建一个新的库时,会在磁盘上创建这个文件夹,windows环境下可查找自己的安装路径下有一个databases目录)

创建vertex

    public static void addVertex() {
        // 在vertex 类abcd下创建一个vertex
        OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/haha", "root", "root");
        OrientGraph graph = factory.getTx();
        OrientVertex vertex = graph.addVertex("class:abcd");
        vertex.setProperty("name", "haha");
        vertex.setProperty("age", 12);

        // 在V下创建一个vertex
        OrientVertex vertex2 = graph.addVertex(null);
        vertex2.setProperty("name", "ha");
        vertex2.setProperty("age", 123);
        graph.commit();
        factory.close();
    }

若想要在某个vertex类下创建一个vertex,则需要使用

OrientVertex vertex = graph.addVertex("class:abcd");

查看源码可看到

  public OrientVertex addVertex(Object id, final Object... prop) {
    makeActive();

    String className = null;
    String clusterName = null;
    Object[] fields = null;

    if (id != null) {
      if (id instanceof String) {
        // PARSE ARGUMENTS
        final String[] args = ((String) id).split(",");
        for (String s : args) {
          // CLASS_PREFIX = "class:" 若使用此前缀,则使用的是vertex的类
          if (s.startsWith(CLASS_PREFIX))
            // GET THE CLASS NAME
            className = s.substring(CLASS_PREFIX.length());
          else if (s.startsWith(CLUSTER_PREFIX))
            // GET THE CLASS NAME
            clusterName = s.substring(CLUSTER_PREFIX.length());
          else id = s;
        }
      }

      // 若在factory设置了saveOriginalIds=true,则会使用这个id值作为originalId
      if (isSaveOriginalIds())
        // SAVE THE ID TOO
        fields = new Object[] {OrientElement.DEF_ORIGINAL_ID_FIELDNAME, id};
    }

     。。。。。。。。
    return vertex;
  }

查询特定类的vertex

    public static void queryVertex() {
        OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/haha", "root", "root");
        OrientGraph graph = factory.getTx();
        OrientGraphQuery graphQuery = (OrientGraphQuery) graph.query().has("name", "haha");
        // 加标签,找固定的vertex的class
        graphQuery.labels("abcd");
       
        Iterable<Vertex> vertices = graphQuery.vertices();
        for (Vertex vertex : vertices) {
            for (String key : vertex.getPropertyKeys()) {
                Object value = vertex.getProperty(key);
                System.out.print(key + ":  " + value + "     ");
            }
        }
        graph.commit();
        factory.close();
    }

真正执行查询的入口在 graphQuery.vertices();这个方法中,查看源码可以看到

isUseClassForVertexLabel()方法为true时,且label值为1个时,使用的具体指定的vertex类,默认情况下这个方法是为true的,因此需要我们设置这个label值,否则便是查询所有的vertex,若要查询所有,则不需要设置这个label值。

以上便是orientdb 图数据库API的简单使用,Edge的创建以及查询应该与上述操作差不多,有需要的可自行尝试一下。

遇到的问题:

1、若要设置的字段有空值,默认情况下会直接报错,是因为在设置值时有元素非空约束,通过设置   

 factory.setStandardElementConstraints(false); 

即可对所需字段设置空值。

2、使用分页

graphQuery.skip(1).limit(10);

skip相当于平时使用的offset

3、根据条件查询总条数

如果没有任何条件,只需要知道vertex 类中的条数,则使用 graph.countVertices()方法即可

        OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/haha", "root", "root");
        OrientGraph graph = factory.getTx();
        long totalCount = graph.countVertices("classname");

如果有查询条件(暂时未发现其他方法),可重写OrientGraphQuery,添加新的方法即可

此处是复制OrientGraphQuery类中的vertices方法加以修改,是为了能够和数据查询的语句保持一致

public class CustomGraphQuery extends OrientGraphQuery {

    protected static final String QUERY_SELECT_COUNT_FROM = "select count(*) as num from ";

    public CustomGraphQuery(Graph graph) {
        super(graph);
    }

    public long countVertices() {

        OTransaction transaction = ((OrientBaseGraph) graph).getRawGraph().getTransaction();
        final StringBuilder text = new StringBuilder(512);

        // GO DIRECTLY AGAINST E CLASS AND SUB-CLASSES
        text.append(QUERY_SELECT_COUNT_FROM);

        if (((OrientBaseGraph) graph).isUseClassForVertexLabel()
                && labels != null
                && labels.length > 0) {
            // FILTER PER CLASS SAVING CHECKING OF LABEL PROPERTY
            if (labels.length == 1)
                // USE THE CLASS NAME
                text.append(OrientBaseGraph.encodeClassName(labels[0]));

        } else text.append(OrientVertexType.CLASS_NAME);

        final List<Object> queryParams = manageFilters(text);
        if (!((OrientBaseGraph) graph).isUseClassForVertexLabel())
            manageLabels(queryParams.size() > 0, text);

        if (orderBy.length() > 1) {
            text.append(ORDERBY);
            text.append(orderBy);
            text.append(" ").append(orderByDir).append(" ");
        }

        OrientBaseGraph baseGraph = (OrientBaseGraph) this.graph;
        OResultSet command = baseGraph.getRawGraph().command(text.toString(), queryParams);
        OResult next = command.next();
        return next.getProperty("num");
    }

}

使用如下

    public static void queryVertexCount() {
        OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/haha", "root", "root");
        OrientGraph graph = factory.getTx();

        CustomGraphQuery graphQuery = new CustomGraphQuery(graph);
        graphQuery.has("name", "haha");

        // 加标签,找固定的vertex的class
        graphQuery.labels("classname");
        long totalCount = graphQuery.countVertices();
        graph.commit();
        factory.close();
    }

以上代码亲测可用!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值