from:https://rednum.cn/ViewListAction?method=detail&dataid=315&classfyid=1

接触Titan数据库是去年的事情了,今年公司要开发一个新的的关系发现系统,所以把自己掌握的关于Titan的知识记录一下。这篇文章一共有三章,由我和同事合著完成。

1.Titan数据的安装

下载地址:http://s3.thinkaurelius.com/downloads/titan/titan-1.0.0-hadoop1.zip

从titan的官网上我们会看到titan数据是一种非常灵活的数据,可以有一些很多的组合方式:



小编使用的是 Hbase + ElasticSearch + db-cache 方式使用Titan

Hbase,ES,和配置的时候都可以是集群的方式,考虑到时入门这里使用Hbase是集群的方式,其它都是单节点的方式

  1. 启动Titan数据库

    在home目录,解压缩titan-1.0.0-hadoop1.zip并cd这个目录,执行

    bin/titan.sh start.

    看到类似这样的结果就说明titan数据服务启动成功了:

    
    
    1. $ bin/titan.sh start
    2. Forking Cassandra...
    3. Running `nodetool statusthrift`.. OK (returned exit status 0 and printed string "running").
    4. Forking Elasticsearch...
    5. Connecting to Elasticsearch (127.0.0.1:9300)... OK (connected to 127.0.0.1:9300).
    6. Forking Gremlin-Server...
    7. Connecting to Gremlin-Server (127.0.0.1:8182)... OK (connected to 127.0.0.1:8182).
    8. Run gremlin.sh to connect.

    3.启动Titan客户端 gremlin

    gremlin是一种图形数据查询语言标准,好比关系数据库中SQL语法,使用 bin/gremlin.sh 启动客户端。

    看到类似的输出说明gremlin启动成功了:

    
    
    1. $ bin/gremlin.sh
    2. \,,,/
    3. (o o)
    4. -----oOOo-(3)-oOOo-----
    5. plugin activated: tinkerpop.server
    6. plugin activated: tinkerpop.hadoop
    7. plugin activated: tinkerpop.utilities
    8. plugin activated: aurelius.titan
    9. plugin activated: tinkerpop.tinkergraph
    10. gremlin> :remote connect tinkerpop.server conf/remote.yaml

    4.配置Titan的工作方式,进入目录conf我们看到有很多预配置的文件



    小编使用的是titan-hbase-es.properties这个配置文件,编辑文件,小编根据自己的方式配置如下:



  1. # Titan configuration sample: HBase and Elasticsearch
  2. #
  3. # This file connects to HBase using a Zookeeper quorum
  4. # (storage.hostname) consisting solely of localhost. It also connects
  5. # to Elasticsearch running on localhost over Elasticsearch's native "Transport"
  6. # protocol. Zookeeper, the HBase services, and Elasticsearch must already
  7. # be running and available before starting Titan with this file.
  8. # The primary persistence provider used by Titan. This is required. It
  9. # should be set one of Titan's built-in shorthand names for its standard
  10. # storage backends (shorthands: berkeleyje, cassandrathrift, cassandra,
  11. # astyanax, embeddedcassandra, hbase, inmemory) or to the full package and
  12. # classname of a custom/third-party StoreManager implementation.
  13. #
  14. # Default: (no default value)
  15. # Data Type: String
  16. # Mutability: LOCAL
  17. storage.backend=hbase
  18. # The hostname or comma-separated list of hostnames of storage backend
  19. # servers. This is only applicable to some storage backends, such as
  20. # cassandra and hbase.
  21. #
  22. # Default: 127.0.0.1
  23. # Data Type: class java.lang.String[]
  24. # Mutability: LOCAL
  25. storage.hostname=192.168.1.252
  26. # Whether to enable Titan's database-level cache, which is shared across
  27. # all transactions. Enabling this option speeds up traversals by holding
  28. # hot graph elements in memory, but also increases the likelihood of
  29. # reading stale data. Disabling it forces each transaction to
  30. # independently fetch graph elements from storage before reading/writing
  31. # them.
  32. #
  33. # Default: false
  34. # Data Type: Boolean
  35. # Mutability: MASKABLE
  36. cache.db-cache = true
  37. # How long, in milliseconds, database-level cache will keep entries after
  38. # flushing them. This option is only useful on distributed storage
  39. # backends that are capable of acknowledging writes without necessarily
  40. # making them immediately visible.
  41. #
  42. # Default: 50
  43. # Data Type: Integer
  44. # Mutability: GLOBAL_OFFLINE
  45. #
  46. # Settings with mutability GLOBAL_OFFLINE are centrally managed in Titan's
  47. # storage backend. After starting the database for the first time, this
  48. # file's copy of this setting is ignored. Use Titan's Management System
  49. # to read or modify this value after bootstrapping.
  50. cache.db-cache-clean-wait = 20
  51. # Default expiration time, in milliseconds, for entries in the
  52. # database-level cache. Entries are evicted when they reach this age even
  53. # if the cache has room to spare. Set to 0 to disable expiration (cache
  54. # entries live forever or until memory pressure triggers eviction when set
  55. # to 0).
  56. #
  57. # Default: 10000
  58. # Data Type: Long
  59. # Mutability: GLOBAL_OFFLINE
  60. #
  61. # Settings with mutability GLOBAL_OFFLINE are centrally managed in Titan's
  62. # storage backend. After starting the database for the first time, this
  63. # file's copy of this setting is ignored. Use Titan's Management System
  64. # to read or modify this value after bootstrapping.
  65. cache.db-cache-time = 180000
  66. # Size of Titan's database level cache. Values between 0 and 1 are
  67. # interpreted as a percentage of VM heap, while larger values are
  68. # interpreted as an absolute size in bytes.
  69. #
  70. # Default: 0.3
  71. # Data Type: Double
  72. # Mutability: MASKABLE
  73. cache.db-cache-size = 0.5
  74. # The indexing backend used to extend and optimize Titan's query
  75. # functionality. This setting is optional. Titan can use multiple
  76. # heterogeneous index backends. Hence, this option can appear more than
  77. # once, so long as the user-defined name between "index" and "backend" is
  78. # unique among appearances.Similar to the storage backend, this should be
  79. # set to one of Titan's built-in shorthand names for its standard index
  80. # backends (shorthands: lucene, elasticsearch, es, solr) or to the full
  81. # package and classname of a custom/third-party IndexProvider
  82. # implementation.
  83. #
  84. # Default: elasticsearch
  85. # Data Type: String
  86. # Mutability: GLOBAL_OFFLINE
  87. #
  88. # Settings with mutability GLOBAL_OFFLINE are centrally managed in Titan's
  89. # storage backend. After starting the database for the first time, this
  90. # file's copy of this setting is ignored. Use Titan's Management System
  91. # to read or modify this value after bootstrapping.
  92. index.search.backend=elasticsearch
  93. # The hostname or comma-separated list of hostnames of index backend
  94. # servers. This is only applicable to some index backends, such as
  95. # elasticsearch and solr.
  96. #
  97. # Default: 127.0.0.1
  98. # Data Type: class java.lang.String[]
  99. # Mutability: MASKABLE
  100. index.search.hostname=127.0.0.1
  101. # The Elasticsearch node.client option is set to this boolean value, and
  102. # the Elasticsearch node.data option is set to the negation of this value.
  103. # True creates a thin client which holds no data. False creates a regular
  104. # Elasticsearch cluster node that may store data.
  105. #
  106. # Default: true
  107. # Data Type: Boolean
  108. # Mutability: GLOBAL_OFFLINE
  109. #
  110. # Settings with mutability GLOBAL_OFFLINE are centrally managed in Titan's
  111. # storage backend. After starting the database for the first time, this
  112. # file's copy of this setting is ignored. Use Titan's Management System
  113. # to read or modify this value after bootstrapping.
  114. index.search.elasticsearch.client-only=true

[========]

好回到gremlin.sh,在提示符下输入以下命令,看到类似的结果


  1. gremlin> graph = TitanFactory.open('conf/titan-berkeleyje-es.properties')
  2. ==>standardtitangraph[berkeleyje:../db/berkeley]
  3. gremlin> GraphOfTheGodsFactory.load(graph)
  4. ==>null
  5. gremlin> g = graph.traversal()
  6. ==>graphtraversalsource[standardtitangraph[berkeleyje:../db/berkeley], standard]

那么恭喜您,你的第一个Titan数据建立好了,事实上titan已经在Hbase中建立了一个叫做titan的表,和在ES中建立一个叫Search的索引,运行以下的查询语句进一步验证:


  1. gremlin> g
  2. ==>graphtraversalsource[titangraph[cassandrathrift:127.0.0.1], standard]
  3. gremlin> g.V().has('name', 'hercules')
  4. ==>v[24]
  5. gremlin> g.V().has('name', 'hercules').out('father')
  6. ==>v[16]
  7. gremlin> g.V().has('name', 'hercules').out('father').out('father')
  8. ==>v[20]
  9. gremlin> g.V().has('name', 'hercules').out('father').out('father').values('name')
  10. ==>saturn

在titan这个表中实际存储的是这样一个结构:



这个图对于初学者可能有点蒙逼,请大家不要在意这些细节,这个图讲的主要是希腊神话中神与神自己一些关系,比如谁和谁是兄弟,谁和谁是母女父子兄弟,谁在那里居住,谁在那里战斗过等等等…..

大家可以把这个图上的关系和上面的查询语句对照起来看就一目了然了,我举个例子:

g.V().has(‘name’, ‘hercules’).out(‘father’)

表示找一个顶点 V,它有一个属性 name = hercules,然后谁是他的的父亲关系的节点。

6 titan db数据规范

6.1 边的类型下面几种

MULTI:表示点和点之间没有约束,可以有任意多个边相连;

SIMPLE:表示点和点只有一个单向进入或出去的边;

MANY2ONE:表示一个点可以有多个进入边;

ONE2MANY:表示一个点可以有多个出去边;

ONE2ONE:表示两个点可以有一对边

示例代码:


  1. mgmt = graph.openManagement()
  2. follow = mgmt.makeEdgeLabel('follow').multiplicity(MULTI).make()
  3. mother = mgmt.makeEdgeLabel('mother').multiplicity(MANY2ONE).make()
  4. mgmt.commit()

6.2 titan数据支持类型



表示我们给点或边定义属性,而这些属性可以是以上的数据类型

6.3 属性的基数

SINGLE: 严格的key->value一对一

LIST:key->values一对多values可以重复

SET:key->values一对多values不可以重复

7.titan主要索引的使用

7.1 Composite Index

示例代码:


  1. graph.tx().rollback() //Never create new indexes while a transaction is active
  2. mgmt = graph.openManagement()
  3. name = mgmt.getPropertyKey('name')
  4. age = mgmt.getPropertyKey('age')
  5. mgmt.buildIndex('byNameComposite', Vertex.class).addKey(name).buildCompositeIndex()
  6. mgmt.buildIndex('byNameAndAgeComposite', Vertex.class).addKey(name).addKey(age).buildCompositeIndex()
  7. mgmt.commit()
  8. //Wait for the index to become available
  9. mgmt.awaitGraphIndexStatus(graph, 'byNameComposite').call()
  10. mgmt.awaitGraphIndexStatus(graph, 'byNameAndAgeComposite').call()
  11. //Reindex the existing data
  12. mgmt = graph.openManagement()
  13. mgmt.updateIndex(mgmt.getGraphIndex("byNameComposite"), SchemaAction.REINDEX).get()
  14. mgmt.updateIndex(mgmt.getGraphIndex("byNameAndAgeComposite"), SchemaAction.REINDEX).get()
  15. mgmt.commit()

这种只能用索引的值严格查找等于的方式查找;

7.2 Mixed Index

示例代码


  1. graph.tx().rollback() //Never create new indexes while a transaction is active
  2. mgmt = graph.openManagement()
  3. name = mgmt.getPropertyKey('name')
  4. age = mgmt.getPropertyKey('age')
  5. mgmt.buildIndex('nameAndAge', Vertex.class).addKey(name).addKey(age).buildMixedIndex("search")
  6. mgmt.commit()
  7. //Wait for the index to become available
  8. mgmt.awaitGraphIndexStatus(graph, 'nameAndAge').call()
  9. //Reindex the existing data
  10. mgmt = graph.openManagement()
  11. mgmt.updateIndex(mgmt.getGraphIndex("nameAndAge"), SchemaAction.REINDEX).get()
  12. mgmt.commit()

这种Index必须使用ES作为后备,可以模糊查询或值范围查询

8.pom.xml 配置


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.rednum.graph</groupId>
  5. <artifactId>redtitan</artifactId>
  6. <version>1.0-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <properties>
  9. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  10. <maven.compiler.source>1.7</maven.compiler.source>
  11. <maven.compiler.target>1.7</maven.compiler.target>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.slf4j</groupId>
  16. <artifactId>slf4j-api</artifactId>
  17. <version>1.7.2</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.slf4j</groupId>
  21. <artifactId>slf4j-log4j12</artifactId>
  22. <version>1.7.2</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>log4j</groupId>
  26. <artifactId>log4j</artifactId>
  27. <version>1.2.16</version>
  28. <exclusions>
  29. <exclusion>
  30. <groupId>javax.jms</groupId>
  31. <artifactId>jms</artifactId>
  32. </exclusion>
  33. <exclusion>
  34. <groupId>com.sun.jdmk</groupId>
  35. <artifactId>jmxtools</artifactId>
  36. </exclusion>
  37. <exclusion>
  38. <groupId>com.sun.jmx</groupId>
  39. <artifactId>jmxri</artifactId>
  40. </exclusion>
  41. </exclusions>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.apache.hadoop</groupId>
  45. <artifactId>hadoop-hdfs</artifactId>
  46. <version>2.6.4</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.apache.hadoop</groupId>
  50. <artifactId>hadoop-client</artifactId>
  51. <version>2.6.4</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.apache.hbase</groupId>
  55. <artifactId>hbase-client</artifactId>
  56. <version>1.2.1</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.apache.hbase</groupId>
  60. <artifactId>hbase</artifactId>
  61. <version>1.2.1</version>
  62. <type>pom</type>
  63. </dependency>
  64. <dependency>
  65. <groupId>com.google.guava</groupId>
  66. <artifactId>guava</artifactId>
  67. <version>16.0.1</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>com.thinkaurelius.titan</groupId>
  71. <artifactId>titan-core</artifactId>
  72. <version>1.0.0</version>
  73. </dependency>
  74. <dependency>
  75. <groupId>com.thinkaurelius.titan</groupId>
  76. <artifactId>titan-hbase</artifactId>
  77. <version>1.0.0</version>
  78. </dependency>
  79. <dependency>
  80. <groupId>com.thinkaurelius.titan</groupId>
  81. <artifactId>titan-es</artifactId>
  82. <version>1.0.0</version>
  83. </dependency>
  84. <dependency>
  85. <groupId>org.elasticsearch</groupId>
  86. <artifactId>elasticsearch</artifactId>
  87. <version>1.5.2</version>
  88. <exclusions>
  89. <exclusion>
  90. <groupId>com.google.guava</groupId>
  91. <artifactId>guava</artifactId>
  92. </exclusion>
  93. </exclusions>
  94. </dependency>
  95. <dependency>
  96. <groupId>prohadoop</groupId>
  97. <artifactId>prohadoop</artifactId>
  98. <version>0.0.1-SNAPSHOT</version>
  99. <type>jar</type>
  100. </dependency>
  101. </dependencies>
  102. <build>
  103. <plugins>
  104. <plugin>
  105. <groupId>org.apache.maven.plugins</groupId>
  106. <artifactId>maven-compiler-plugin</artifactId>
  107. <configuration>
  108. <source>1.7</source>
  109. <targe>1.8</targe>
  110. </configuration>
  111. </plugin>
  112. <plugin>
  113. <groupId>org.apache.maven.plugins</groupId>
  114. <artifactId>maven-assembly-plugin</artifactId>
  115. <version>2.4</version>
  116. <configuration>
  117. <descriptorRefs>
  118. <descriptorRef>jar-with-dependencies</descriptorRef>
  119. </descriptorRefs>
  120. </configuration>
  121. <executions>
  122. <execution>
  123. <id>assemble-all</id>
  124. <phase>package</phase>
  125. <goals>
  126. <goal>single</goal>
  127. </goals>
  128. </execution>
  129. </executions>
  130. </plugin>
  131. </plugins>
  132. </build>
  133. <name>redtitan</name>
  134. </project>

9.titan java客户端


  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package com.rednum.graph;
  7. import com.google.gson.Gson;
  8. import com.google.gson.internal.LinkedTreeMap;
  9. import static com.rednum.graph.TiTanDB.INDEX_NAME;
  10. import static com.rednum.graph.TiTanDB.load;
  11. import static com.rednum.graph.TiTanDB.query;
  12. import com.thinkaurelius.titan.core.EdgeLabel;
  13. import com.thinkaurelius.titan.core.Multiplicity;
  14. import com.thinkaurelius.titan.core.PropertyKey;
  15. import com.thinkaurelius.titan.core.TitanFactory;
  16. import com.thinkaurelius.titan.core.TitanGraph;
  17. import com.thinkaurelius.titan.core.TitanTransaction;
  18. import com.thinkaurelius.titan.core.attribute.Geoshape;
  19. import com.thinkaurelius.titan.core.attribute.Text;
  20. import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
  21. import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
  22. import com.thinkaurelius.titan.core.schema.TitanManagement;
  23. import com.thinkaurelius.titan.core.util.TitanCleanup;
  24. import java.io.BufferedReader;
  25. import java.io.FileReader;
  26. import java.util.HashMap;
  27. import java.util.Iterator;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Set;
  31. import org.apache.commons.configuration.BaseConfiguration;
  32. import org.apache.commons.configuration.Configuration;
  33. import org.apache.tinkerpop.gremlin.process.traversal.Order;
  34. import org.apache.tinkerpop.gremlin.process.traversal.P;
  35. import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
  36. import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
  37. import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
  38. import org.apache.tinkerpop.gremlin.structure.Direction;
  39. import org.apache.tinkerpop.gremlin.structure.Edge;
  40. import org.apache.tinkerpop.gremlin.structure.T;
  41. import org.apache.tinkerpop.gremlin.structure.Vertex;
  42. import org.codehaus.jettison.json.JSONArray;
  43. import org.codehaus.jettison.json.JSONObject;
  44. /**
  45. *
  46. * @author X.H.Yang
  47. */
  48. public class TitanNewGraph {
  49. // private final Gson gson = new Gson();
  50. public static TitanGraph create() {
  51. try {
  52. //创建名为temptest的表。
  53. TitanGraph graph = TitanFactory.build()
  54. .set("storage.backend", "hbase")
  55. .set("storage.hostname", "192.168.1.252")
  56. .set("storage.hbase.table", "newgraph")
  57. .set("cache.db-cache", "true")
  58. .set("cache.db-cache-clean-wait", "20")
  59. .set("cache.db-cache-time", "180000")
  60. .set("cache.db-cache-size", "0.5")
  61. .set("index.newgraph.backend", "elasticsearch")
  62. .set("index.newgraph.hostname", "192.168.1.212")
  63. .set("index.newgraph.port", 9300)
  64. .set("index.newgraph.elasticsearch.client-only", true)
  65. .open();
  66. return graph;
  67. } catch (Exception e) {
  68. System.out.println(e);
  69. return null;
  70. }
  71. }
  72. public static void loadWithoutMixedIndex(final TitanGraph graph,
  73. boolean uniqueNameCompositeIndex) {
  74. load(graph, null, uniqueNameCompositeIndex);
  75. }
  76. public static void load(final TitanGraph graph) {
  77. load(graph, "newgraph", true);
  78. }
  79. public static void load(final TitanGraph graph, String mixedIndexName,
  80. boolean uniqueNameCompositeIndex) {
  81. // Create Schema
  82. try {
  83. TitanManagement mgmt = graph.openManagement();
  84. final PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
  85. TitanManagement.IndexBuilder nameIndexBuilder = mgmt.buildIndex("name", Vertex.class).addKey(name);
  86. if (uniqueNameCompositeIndex) {
  87. nameIndexBuilder.unique();
  88. }
  89. TitanGraphIndex namei = nameIndexBuilder.buildCompositeIndex();
  90. mgmt.setConsistency(namei, ConsistencyModifier.LOCK);
  91. final PropertyKey age = mgmt.makePropertyKey("age").dataType(Integer.class).make();
  92. if (null != mixedIndexName) {
  93. mgmt.buildIndex("vertices", Vertex.class).addKey(age).buildMixedIndex(mixedIndexName);
  94. }
  95. final PropertyKey time = mgmt.makePropertyKey("time").dataType(Integer.class).make();
  96. final PropertyKey reason = mgmt.makePropertyKey("reason").dataType(String.class).make();
  97. final PropertyKey place = mgmt.makePropertyKey("place").dataType(Geoshape.class).make();
  98. if (null != mixedIndexName) {
  99. mgmt.buildIndex("edges", Edge.class).addKey(reason).addKey(place).buildMixedIndex(mixedIndexName);
  100. }
  101. mgmt.makeEdgeLabel("father").multiplicity(Multiplicity.MANY2ONE).make();
  102. mgmt.makeEdgeLabel("mother").multiplicity(Multiplicity.MANY2ONE).make();
  103. EdgeLabel battled = mgmt.makeEdgeLabel("battled").signature(time).make();
  104. mgmt.buildEdgeIndex(battled, "battlesByTime", Direction.BOTH, Order.decr, time);
  105. mgmt.makeEdgeLabel("lives").signature(reason).make();
  106. mgmt.makeEdgeLabel("pet").make();
  107. mgmt.makeEdgeLabel("brother").make();
  108. mgmt.makeVertexLabel("titan").make();
  109. mgmt.makeVertexLabel("location").make();
  110. mgmt.makeVertexLabel("god").make();
  111. mgmt.makeVertexLabel("demigod").make();
  112. mgmt.makeVertexLabel("human").make();
  113. mgmt.makeVertexLabel("monster").make();
  114. mgmt.commit();
  115. TitanTransaction tx = graph.newTransaction();
  116. // vertices
  117. Vertex saturn = tx.addVertex(T.label, "titan", "name", "saturn", "age", 34);
  118. Vertex sky = tx.addVertex(T.label, "location", "name", "sky");
  119. Vertex sea = tx.addVertex(T.label, "location", "name", "sea");
  120. Vertex jupiter = tx.addVertex(T.label, "god", "name", "jupiter", "age", 5000);
  121. Vertex neptune = tx.addVertex(T.label, "god", "name", "neptune", "age", 4500);
  122. Vertex hercules = tx.addVertex(T.label, "demigod", "name", "hercules", "age", 30);
  123. Vertex alcmene = tx.addVertex(T.label, "human", "name", "alcmene", "age", 45);
  124. Vertex pluto = tx.addVertex(T.label, "god", "name", "pluto", "age", 4000);
  125. Vertex nemean = tx.addVertex(T.label, "monster", "name", "nemean");
  126. Vertex hydra = tx.addVertex(T.label, "monster", "name", "hydra");
  127. Vertex cerberus = tx.addVertex(T.label, "monster", "name", "cerberus");
  128. Vertex tartarus = tx.addVertex(T.label, "location", "name", "tartarus");
  129. // edges
  130. jupiter.addEdge("father", saturn);
  131. jupiter.addEdge("lives", sky, "reason", "loves fresh breezes");
  132. jupiter.addEdge("brother", neptune);
  133. jupiter.addEdge("brother", pluto);
  134. neptune.addEdge("lives", sea).property("reason", "loves waves");
  135. neptune.addEdge("brother", jupiter);
  136. neptune.addEdge("brother", pluto);
  137. hercules.addEdge("father", jupiter);
  138. hercules.addEdge("mother", alcmene);
  139. hercules.addEdge("battled", nemean, "time", 1, "place", Geoshape.point(38.1f, 23.7f));
  140. hercules.addEdge("battled", hydra, "time", 2, "place", Geoshape.point(37.7f, 23.9f));
  141. hercules.addEdge("battled", cerberus, "time", 12, "place", Geoshape.point(39f, 22f));
  142. pluto.addEdge("brother", jupiter);
  143. pluto.addEdge("brother", neptune);
  144. pluto.addEdge("lives", tartarus, "reason", "no fear of death");
  145. pluto.addEdge("pet", cerberus);
  146. cerberus.addEdge("lives", tartarus);
  147. //commit the transaction to disk
  148. tx.commit();
  149. } catch (Exception e) {
  150. System.out.println(e);
  151. e.printStackTrace();
  152. }
  153. }
  154. public static void query(TitanGraph graph) {
  155. GraphTraversalSource g = graph.traversal();
  156. GraphTraversal<Vertex, Long> count = g.V().count();
  157. System.out.println("共有结点" + count.next());
  158. GraphTraversal<Vertex, Vertex> iterators = g.V();
  159. try {
  160. while (iterators.hasNext()) {
  161. Vertex ver = iterators.next();
  162. System.out.println(ver);
  163. System.out.println(ver.label());
  164. System.out.println(ver.keys());
  165. Set<String> set = ver.keys();
  166. for (String ss : set) {
  167. System.out.println(ver.value(ss));
  168. }
  169. }
  170. } catch (Exception e) {
  171. e.toString();
  172. }
  173. GraphTraversal<Edge, Edge> edgeAll = g.E();
  174. System.out.println("共有边" + g.E().count().next());
  175. try {
  176. while (edgeAll.hasNext()) {
  177. Edge ee = edgeAll.next();
  178. Set<String> set = ee.keys();
  179. for (String ss : set) {
  180. System.out.println(ss+":"+ee.value(ss));
  181. }
  182. System.out.println(ee.label());
  183. System.out.println(ee.outVertex().value("name"));
  184. System.out.println(ee.inVertex().value("name"));
  185. System.out.println("-----");
  186. }
  187. } catch (Exception e) {
  188. e.toString();
  189. }
  190. System.out.println(g.V().has("name", "hercules").next().value("name"));
  191. System.out.println(g.V().has("name", "hercules").next().values("name", "age"));
  192. Iterator<Object> iterator = g.V().has("name", "hercules").next().values("name", "age");
  193. while (iterator.hasNext()) {
  194. Object object = iterator.next();
  195. System.out.println(object);
  196. }
  197. Vertex saturn = g.V().has("name", "tanzhuo").next();
  198. System.out.println(saturn);
  199. //得到 saturn的孙子节点
  200. System.out.println(g.V(saturn).in("father").in("father").next().value("age"));
  201. GraphTraversal<Edge, Edge> a = g.E().has("place", P.eq(Geoshape.point(38.1f, 23.7f)));
  202. System.out.println(a);
  203. while (a.hasNext()) {
  204. Edge e = a.next();
  205. System.out.println(e.keys());
  206. System.out.println(e.label());
  207. System.out.println(e.outVertex().value("name"));
  208. System.out.println(e.inVertex().value("name"));
  209. System.out.println(e.value("time") + " : " + e.value("place"));
  210. }
  211. Vertex hercules = g.V().has("name", "hercules").next();
  212. System.out.println(g.V(hercules).out("mother", "father").values("name"));
  213. GraphTraversal<Vertex, Vertex> mF = g.V(hercules).out("mother", "father");
  214. while (mF.hasNext()) {
  215. Vertex v = mF.next();
  216. System.out.println(v.label() + " : " + v.value("name"));
  217. }
  218. //repeat(__.in("father")).times(2)表示父亲的父亲,times(2)表示重复两次
  219. System.out.println(g.V(saturn).repeat(__.in("father")).times(2).next().value("name"));
  220. GraphTraversal<Vertex, Vertex> monsters = g.V(hercules).out("battled");
  221. while (monsters.hasNext()) {
  222. Vertex monster = monsters.next();
  223. System.out.println(monster.label() + " : " + monster.value("name"));
  224. }
  225. //P.eq(1)表示time,次数为1次
  226. monsters = g.V(hercules).outE("battled").has("time", P.eq(1)).inV();
  227. while (monsters.hasNext()) {
  228. Vertex monster = monsters.next();
  229. System.out.println(monster.label() + " : " + monster.value("name"));
  230. }
  231. Vertex pluto = g.V().has("name", "pluto").next();
  232. GraphTraversal<Vertex, Vertex> liveInTartarusVertex = g.V(pluto).out("lives").in("lives");
  233. while (liveInTartarusVertex.hasNext()) {
  234. Vertex vertex = liveInTartarusVertex.next();
  235. System.out.println(vertex.value("name"));
  236. }
  237. GraphTraversal<Vertex, Vertex> liveInTartarusVertexNo = g.V(pluto).out("lives").in("lives").where(__.is(P.neq(pluto)));
  238. while (liveInTartarusVertexNo.hasNext()) {
  239. Vertex vertex = liveInTartarusVertexNo.next();
  240. System.out.println(vertex.value("name"));
  241. }
  242. //P.neq("x")不等于
  243. GraphTraversal<Vertex, Vertex> liveInTartarusVertexNot = g.V(pluto).as("x").out("lives").in("lives").where(P.neq("x"));
  244. while (liveInTartarusVertexNot.hasNext()) {
  245. Vertex vertex = liveInTartarusVertexNot.next();
  246. System.out.println("======" + vertex.value("name"));
  247. }
  248. GraphTraversal<Vertex, Map<String, Vertex>> brothers
  249. = g.V(pluto).out("brother").as("god").out("lives").as("place").select("god", "place");
  250. while (brothers.hasNext()) {
  251. Map<String, Vertex> map = brothers.next();
  252. System.out.println(map);
  253. for (Map.Entry<String, Vertex> entry : map.entrySet()) {
  254. System.out.println(entry.getKey() + " : " + entry.getValue().value("name"));
  255. }
  256. }
  257. System.out.println(g.V(pluto).outE("lives").next().value("reason"));
  258. GraphTraversal<Edge, Edge> reasons = g.E().has("reason").as("r").values("reason").is(Text.textContains("loves")).select("r");
  259. System.out.println(reasons);
  260. while (reasons.hasNext()) {
  261. Edge e = reasons.next();
  262. System.out.println(e.keys());
  263. System.out.println(e.label());
  264. System.out.println(e.value("reason"));
  265. }
  266. GraphTraversal<Edge, Map<String, Object>> reasons2
  267. = g.E().has("reason").as("source").values("reason").is(Text.textContains("loves")).as("reason").select("source")
  268. .outV().values("name").as("god").select("source").inV().values("name").as("thing").select("god", "reason", "thing");
  269. while (reasons2.hasNext()) {
  270. Map<String, Object> map = reasons2.next();
  271. System.out.println(map);
  272. for (Map.Entry<String, Object> entry : map.entrySet()) {
  273. System.out.println(entry.getKey() + " : " + entry.getValue());
  274. }
  275. }
  276. }
  277. public static void main(String[] args) throws Exception {
  278. try {
  279. TitanGraph graph = TitanNewGraph.create();
  280. //load(graph);
  281. query(graph);
  282. graph.close();
  283. } catch (Exception e) {
  284. e.toString();
  285. }
  286. }
  287. }

10.程序输出


  1. 共有结点12
  2. v[4120]
  3. location
  4. [name]
  5. sky
  6. v[8216]
  7. location
  8. [name]
  9. sea
  10. v[4160]
  11. human
  12. [name, age]
  13. alcmene
  14. 45
  15. v[8256]
  16. god
  17. [name, age]
  18. pluto
  19. 4000
  20. v[12352]
  21. location
  22. [name]
  23. tartarus
  24. v[4200]
  25. god
  26. [name, age]
  27. jupiter
  28. 5000
  29. v[8296]
  30. monster
  31. [name]
  32. nemean
  33. v[4208]
  34. monster
  35. [name]
  36. hydra
  37. v[4224]
  38. titan
  39. [name, age]
  40. tanzhuo
  41. 34
  42. v[8320]
  43. monster
  44. [name]
  45. cerberus
  46. v[4304]
  47. god
  48. [name, age]
  49. neptune
  50. 4500
  51. v[4336]
  52. demigod
  53. [name, age]
  54. hercules
  55. 30
  56. 共有边17
  57. reason:no fear of death
  58. lives
  59. pluto
  60. tartarus
  61. -----
  62. pet
  63. pluto
  64. cerberus
  65. -----
  66. brother
  67. pluto
  68. jupiter
  69. -----
  70. brother
  71. pluto
  72. neptune
  73. -----
  74. father
  75. jupiter
  76. tanzhuo
  77. -----
  78. reason:loves fresh breezes
  79. lives
  80. jupiter
  81. sky
  82. -----
  83. brother
  84. jupiter
  85. neptune
  86. -----
  87. brother
  88. jupiter
  89. pluto
  90. -----
  91. lives
  92. cerberus
  93. tartarus
  94. -----
  95. reason:loves waves
  96. lives
  97. neptune
  98. sea
  99. -----
  100. brother
  101. neptune
  102. jupiter
  103. -----
  104. brother
  105. neptune
  106. pluto
  107. -----
  108. father
  109. hercules
  110. jupiter
  111. -----
  112. mother
  113. hercules
  114. alcmene
  115. -----
  116. place:point[37.7,23.9]
  117. time:2
  118. battled
  119. hercules
  120. hydra
  121. -----
  122. time:1
  123. place:point[38.1,23.7]
  124. battled
  125. hercules
  126. nemean
  127. -----
  128. place:point[39.0,22.0]
  129. time:12
  130. battled
  131. hercules
  132. cerberus
  133. -----
  134. hercules
  135. org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils$3@b1534d3
  136. hercules
  137. 30
  138. v[4224]
  139. 30
  140. [GraphStep([],edge), HasStep([place.eq(point[38.1,23.7])])]
  141. [time, place]
  142. battled
  143. hercules
  144. nemean
  145. 1 : point[38.1,23.7]
  146. [GraphStep([v[4336]],vertex), VertexStep(OUT,[mother, father],vertex), PropertiesStep([name],value)]
  147. god : jupiter
  148. human : alcmene
  149. hercules
  150. monster : hydra
  151. monster : nemean
  152. monster : cerberus
  153. monster : nemean
  154. pluto
  155. cerberus
  156. cerberus
  157. ======cerberus
  158. {god=v[4200], place=v[4120]}
  159. god : jupiter
  160. place : sky
  161. {god=v[4304], place=v[8216]}
  162. god : neptune
  163. place : sea
  164. no fear of death
  165. [GraphStep([],edge), TraversalFilterStep([PropertiesStep([reason],value)])@[r], PropertiesStep([reason],value), IsStep(CONTAINS(loves)), SelectOneStep(r)]
  166. [reason]
  167. lives
  168. loves fresh breezes
  169. [reason]
  170. lives
  171. loves waves
  172. {god=jupiter, reason=loves fresh breezes, thing=sky}
  173. god : jupiter
  174. reason : loves fresh breezes
  175. thing : sky
  176. {god=neptune, reason=loves waves, thing=sea}
  177. god : neptune
  178. reason : loves waves
  179. thing : sea

最后请大家把输出结果和对应的语句对照的看相信会对Titan数据库有一个初步的了解,谢谢观赏,本课程完

Titan数据库快速入门之神的光芒相关推荐

  1. 超经典两万字,MySQL数据库快速入门。

    「作者主页」:士别三日wyx 「作者简介」:CSDN top100.阿里云博客专家.华为云享专家.网络安全领域优质创作者 「专栏简介」:此文章已录入专栏<MySQL数据库快速入门> MyS ...

  2. 视频教程-oracle数据库快速入门-Oracle

    oracle数据库快速入门 十年项目开发经验,主要从事java相关的开发,熟悉各种mvc开发框架. 王振伟 ¥21.00 立即订阅 扫码下载「CSDN程序员学院APP」,1000+技术好课免费看 AP ...

  3. 猿创征文 | 国产数据库实战之TiDB 数据库快速入门

    猿创征文 | 国产数据库实战之TiDB 数据库快速入门 一.系统检查 1.检查系统版本 2.查看本地IP地址 3.TiDB集群介绍 二.快速部署本地测试集群 1.安装 TiUP工具 2.声明全局环境变 ...

  4. 数据库快速入门教程--视频

    数据库快速入门教程--视频 下载地址:http://v.51work6.com/courseInfoRedirect.do?action=courseInfo&courseId=240579 ...

  5. MySQL数据库快速入门到精通(超详细保姆级,建议收藏)这可能是目前最适合你的教程,从基础语法到实例演示。

    前言 此文章旨在为需要掌握快速开发和复习MySQL的同学所准备,您完全可以把此文章当作参考文档来使用,本文将尽量精简,使您快速的理解和掌握语法. 关于MySQL MySQL是一个关系型数据库管理系统, ...

  6. 如何系统的学习数据库、形成自己的数据库体系、数据库快速入门

    1,适合对象:在日常工作过程中,频繁使用数据库的技术人员.研发人员 适合管理数据库的技术人员. 2,开始学习 第一部分:快速的熟悉数据库信息 2.1,熟悉业务系统的基本功能:所有的数据库设计都是依赖于 ...

  7. mysql外键约束视频教学_外键约束案例_MySQL数据库 快速入门 基础+实战 视频教程_MySQL视频-51CTO学院...

    MySQL是开源免费和功能多面的小型数据库,MySQL也是目前流行通用的关系型数据库,已经被 Oracle 收购了.随着版本更新升级,加入一些高级功能,MySQL6.x 版本也开始收费.不过本教程将使 ...

  8. mysql快捷创建数据库_mysql数据库快速入门(1)

    1.数据库操作 1.1.连接mysql服务器 mysql -u root( 用户名 ) -p 1.2.退出mysql命令提示窗 exit 1.3.查看版本 SELECT VERSION(); 1.4. ...

  9. h2 mysql mode_H2 数据库快速入门

    目录: 关键词:H2 Database, 关系数据库, SQL, 内存数据库. H2 Database 是一个 Java 实现的关系型数据库,也是一个嵌入式数据库. 引入依赖 在 gradle 文件中 ...

最新文章

  1. python调用cmd命令
  2. Python-OS平台编程
  3. SpringBoot加itext实现PDF导出
  4. URI概念的简单介绍
  5. java plt_matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
  6. 实验7-3-2 查找指定字符 (15分)
  7. Mysql的my.cnf配置文件详情
  8. 力扣113. 路径总和 II(JavaScript)
  9. .NET中方法的注意事项 明细
  10. VC下sql+ado数据库v_strTemp.vt == VT_NULL判断的问题
  11. Htmlunit 使用记录
  12. 苹果Mac时间日程管理工具:Things 备注支持 Markdown
  13. mysql 加锁 索引_把MySQL中的各种锁及其原理都画出来
  14. Memcacher win7 安装测试
  15. SEO之关键词选择原则
  16. 亿图图示:分享你的流程图给你的小伙伴
  17. android studio ADT+SDK \appium下载与安装
  18. 程序员如何提一个好问题?
  19. 你坐飞机时可能意识不到,AI已经全流程为你保驾护航
  20. V型测试,W型测试和H型测试

热门文章

  1. OAuth2授权码模式
  2. 织梦CMS5.7版自动给图片添加alt属性的方法
  3. 国盛源app投资放心有多少积储才能够理财?理财门槛高吗?
  4. 全球可用的NTP服务器列表与解析服务
  5. android 高性能手机排行榜,安兔兔发布了2018年12月份的Android手机性能排行榜
  6. Linux 使用scp命令远程传输文件夹
  7. 如果我使用maya建模软件,就业前景如何?
  8. springboot+vue汽车4S店维修管理系统
  9. 长期熬夜——真的不好
  10. µC/OS-II 示例 ucos任务的挂起与删除