Titan数据库快速入门之神的光芒

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. 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. 4.0.0
  4. com.rednum.graph
  5. redtitan
  6. 1.0-SNAPSHOT
  7. jar
  8. UTF-8
  9. 1.7
  10. 1.7
  11. org.slf4j
  12. slf4j-api
  13. 1.7.2
  14. org.slf4j
  15. slf4j-log4j12
  16. 1.7.2
  17. log4j
  18. log4j
  19. 1.2.16
  20. javax.jms
  21. jms
  22. com.sun.jdmk
  23. jmxtools
  24. com.sun.jmx
  25. jmxri
  26. org.apache.hadoop
  27. hadoop-hdfs
  28. 2.6.4
  29. org.apache.hadoop
  30. hadoop-client
  31. 2.6.4
  32. org.apache.hbase
  33. hbase-client
  34. 1.2.1
  35. org.apache.hbase
  36. hbase
  37. 1.2.1
  38. pom
  39. com.google.guava
  40. guava
  41. 16.0.1
  42. com.thinkaurelius.titan
  43. titan-core
  44. 1.0.0
  45. com.thinkaurelius.titan
  46. titan-hbase
  47. 1.0.0
  48. com.thinkaurelius.titan
  49. titan-es
  50. 1.0.0
  51. org.elasticsearch
  52. elasticsearch
  53. 1.5.2
  54. com.google.guava
  55. guava
  56. prohadoop
  57. prohadoop
  58. 0.0.1-SNAPSHOT
  59. jar
  60. org.apache.maven.plugins
  61. maven-compiler-plugin
  62. 1.7
  63. 1.8
  64. org.apache.maven.plugins
  65. maven-assembly-plugin
  66. 2.4
  67. jar-with-dependencies
  68. assemble-all
  69. package
  70. single
  71. redtitan

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

你可能感兴趣的:(图形数据库,titan)