Giter Club home page Giter Club logo

gremlin-scala's Introduction

logo

Build Status Join the chat at https://gitter.im/mpollmeier/gremlin-scala Maven Central scaladoc

Gremlin-Scala for Apache Tinkerpop 3

A wrapper to use Apache Tinkerpop3 - a JVM graph traversal library - from Scala.

  • Beautiful DSL to create vertices and edges
  • Type safe traversals
  • Scala friendly function signatures
  • Minimal runtime overhead - only allocates additional instances if absolutely necessary
  • Nothing is hidden away, you can always easily access the underlying Gremlin-Java objects if needed, e.g. to access graph db specifics things like indexes

TOC

Getting started

The examples project comes with working examples for different graph databases. Typically you just need to add a dependency on "com.michaelpollmeier" %% "gremlin-scala" % "SOME_VERSION" and one for the graph db of your choice to your build.sbt (this readme assumes tinkergraph). The latest version is displayed at the top of this readme in the maven badge.

Using the sbt console

  • sbt gremlin-scala/Test/console
import gremlin.scala._
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory
implicit val graph = TinkerFactory.createModern.asScala

val name = Key[String]("name")

val g = graph.traversal
g.V.hasLabel("person").value(name).toList
// List(marko, vadas, josh, peter)

Simple traversals

The below create traversals, which are lazy computations. To run a traversal, you can use e.g. toSet, toList, head, headOption etc.

import gremlin.scala._
import org.apache.tinkerpop.gremlin.process.traversal.{Order, P}
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory

implicit val graph = TinkerFactory.createModern.asScala
val g = graph.traversal

g.V //all vertices
g.E //all edges

g.V(1).outE("knows") //follow outgoing edges
g.V(1).out("knows") //follow outgoing edges to incoming vertex

val weight = Key[Double]("weight")
for {
  person <- g.V.hasLabel("person")
  favorite <- person.outE("likes").order(By(weight, Order.decr)).limit(1).inV
} yield (person, favorite.label)

// remove all people over 30 from the g - also removes corresponding edges
val Age = Key[Int]("age")
g.V.hasLabel("person").has(Age, P.gte(30)).drop.iterate

Warning: GremlinScala is not a monad, because the underlying Tinkerpop GraphTraversal is not. I.e. while GremlinScala offers map, flatMap etc. and you can use it in a for comprehension for syntactic sugar, it does not fulfil all monad laws.

More working examples in TraversalSpec.

Vertices and edges with type safe properties

import gremlin.scala._
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
import scala.language.postfixOps
implicit val graph = TinkerGraph.open.asScala

// Keys for properties which can later be used for type safe traversals
val Founded = Key[String]("founded")
val Distance = Key[Int]("distance")

// create labelled vertex
val paris = graph + "Paris"

// create vertex with typed properties
val london = graph + ("London", Founded -> "43 AD")

// create labelled edges 
paris --- "OneWayRoad" --> london
paris <-- "OtherWayAround" --- london
paris <-- "Eurostar" --> london

// create edge with typed properties
paris --- ("Eurostar", Distance -> 495) --> london

// type safe access to properties
paris.out("Eurostar").value(Founded).head //43 AD
paris.outE("Eurostar").value(Distance).head //495
london.valueOption(Founded) //Some(43 AD)
london.valueOption(Distance) //None
paris.setProperty(Founded, "300 BC")

val Name = Key[String]("name")
val Age = Key[Int]("age")

val v1 = graph + ("person", Name -> "marko", Age -> 29) asScala

v1.keys // Set(Key("name"), Key("age"))
v1.property(Name) // "marko"
v1.valueMap // Map("name" -> "marko", "age" -> 29)
v1.valueMap("name", "age") // Map("name" -> "marko", "age" -> 29)

More working examples in SchemaSpec, ArrowSyntaxSpec and ElementSpec.

Compiler helps to eliminate invalid traversals

Gremlin-Scala aims to helps you at compile time as much as possible. Take this simple example:

import gremlin.scala._
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
implicit val graph = TinkerGraph.open.asScala
val g = graph.traversal
g.V.outE.inV  //compiles
g.V.outE.outE //does _not_ compile

In Gremlin-Groovy there's nothing stopping you to create the second traversal - it will explode at runtime, as outgoing edges do not have outgoing edges. In Gremlin-Scala this simply doesn't compile.

Type safe traversals

You can label any step using as(StepLabel) and the compiler will infer the correct types for you in the select step using an HList (a type safe list, i.e. the compiler knows the types of the elements of the list). In Gremlin-Java and Gremlin-Groovy you get a Map[String, Any], so you have to cast to the type you think it will be, which is ugly and error prone. For example:

import gremlin.scala._
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
def graph = TinkerFactory.createModern.asScala
val g = graph.traversal

// select all labelled steps
g.V(1).as("a").outE.as("b").select.toList
// returns a `(Vertex, Edge)` for each path

// select subset of labelled steps
val a = StepLabel[Vertex]()
val b = StepLabel[Edge]()
val c = StepLabel[Double]()

val traversal = g.V(1).as(a).outE("created").as(b).value("weight").as(c)
    
traversal.select((b, c)).head
// returns a `(Edge, Double)`

More working examples in SelectSpec. Kudos to shapeless and Scala's sophisticated type system that made this possible.

As of 3.3.3.2 there is a typesafe union step that supports heterogeneous queries:

val traversal =
  g.V(1).union(
    _.join(_.outE)
     .join(_.out)
  )
// derived type: GremlinScala[(List[Edge], List[Vertex])] 
val (outEdges, outVertices) = traversal.head

A note on predicates

tl;dr: use gremlin.scala.P to create predicates of type P.

Many steps in take a tinkerpop3 predicate of type org.apache.tinkerpop.gremlin.process.traversal.P. Creating Ps that take collection types is dangerous though, because you need to ensure you're creating the correct P. For example P.within(Set("a", "b")) would be calling the wrong overload (which checks if the value IS the given set). In that instance you actually wanted to create P.within(Set("a", "b").asJava: java.util.Collection[String]). To avoid that confusion, it's best to just import gremlin.scala._ and create it as P.within(Set("a", "b")).

Build a custom DSL on top of Gremlin-Scala

You can now build your own domain specific language, which is super helpful if you don't want to expose your users to the world of graphs and tinkerpop, but merely build an API for them. All you need to do is setup your ADT as case classes, define your DSL as Steps and create one implicit constructor (the only boilerplate code). The magic in gremlin.scala.dsl._ allows you to even write for comprehensions like this (DSL for tinkerpop testgraph):

case class Person  (name: String, age: Integer) extends DomainRoot
case class Software(name: String, lang: String) extends DomainRoot

val traversal = for {
  person   <- PersonSteps(graph)
  software <- person.created
} yield (person.name, software)

// note: `traversal` is inferred by the compiler as `gremlin.scala.dsl.Steps[(String, Software)]`

traversal.toSet // returns: 
Set(
  ("marko", Software("lop", "java")),
  ("josh", Software("lop", "java")),
  ("peter", Software("lop", "java")),
  ("josh", Software("ripple", "java"))
)

// DSL also supports typesafe as/select:
PersonSteps(graph)
  .as("person")
  .created
  .as("software")
  .select
  .toList
// inferred return type is `List[(Person, Software)]`

See the full setup and more tests in DslSpec.

Common and useful steps

// get a vertex by id
g.V(1).headOption

// get all vertices
g.V.toList

// group all vertices by their label
g.V.group(By.label)

// group vertices by a property
val age = Key[Int]("age")
g.V.has(age).group(By(age))

// order by property decreasing
val age = Key[Int]("age")
g.V.has(age).order(By(age, Order.decr))

More working examples in TraversalSpec.

Mapping vertices from/to case classes

You can save and load case classes as a vertex - implemented with a blackbox macro.

  • You can optionally specify the label of your class using @label
  • Option members will be automatically unwrapped, i.e. a Some[A] will be stored as the value of type A in the database, or null if it's None. If we wouldn't unwrap it, the database would have to understand Scala's Option type itself.
  • The same goes for value classes, i.e. a case class ShoeSize(value: Int) extends AnyVal will be stored as an Integer.
  • List members will be stored as multi-properties, i.e. Cardinality.list
  • Annotating members with @id and @underlying will instruct the marshaller to set the element id and/or the underlying element in the class. Note: you cannot specify the id when adding a vertex like this. Using @id only works when retrieving the vertex back from the graph and it therefor must be an Option.
  • Your classes must be defined outside the scope where they are being used (e.g. in the code below the class Example cannot be inside object Main).

Warning: this may not work with your particular remote graph, depending on the implementation/configuration. That's because the graph may choose to only return referenced elements which doesn't contain it's properties.

// this does _not_ work in a REPL
import gremlin.scala._
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph

@label("my_custom_label")
case class Example(longValue: Long, stringValue: Option[String], @underlying vertex: Option[Vertex] = None)

object Main extends App {
  implicit val graph = TinkerGraph.open.asScala
  val example = Example(Long.MaxValue, Some("optional value"))
  val v = graph + example
  v.toCC[Example] // equal to `example`, but with `vertex` set

  // find all vertices with the label of the case class `Example`
  graph.V.hasLabel[Example]

  // modify the vertex like a case class
  v.updateAs[Example](_.copy(longValue = 0L))
}

You can also define your own marshaller, if the macro generated one doesn't quite cut it. For that and more examples check out the MarshallableSpec.

More advanced traversals

Here are some examples of more complex traversals from the examples repo. If you want to run them yourself, check out the tinkergraph examples in there.

What's the property distribution of all vertices?

graph.V.groupCount(By(__.properties().count)).head

What is Die Hard's average rating?

graph.V.has("movie", "name", "Die Hard")
  .inE("rated")
  .values("stars")
  .mean
  .head

Get the maximum number of movies a single user rated

g.V.hasLabel("person")
  .flatMap(_.outE("rated").count)
  .max
  .head

What 80's action movies do 30-something programmers like? Group count the movies by their name and sort the group count map in decreasing order by value.

g.V
  .`match`(
    __.as("a").hasLabel("movie"),
    __.as("a").out("hasGenre").has("name", "Action"),
    __.as("a").has("year", P.between(1980, 1990)),
    __.as("a").inE("rated").as("b"),
    __.as("b").has("stars", 5),
    __.as("b").outV().as("c"),
    __.as("c").out("hasOccupation").has("name", "programmer"),
    __.as("c").has("age", P.between(30, 40))
  )
  .select[Vertex]("a")
  .map(_.value[String]("name"))
  .groupCount()
  .order(Scope.local).by(Order.valueDecr)
  .limit(Scope.local, 10)
  .head

What is the most liked movie in each decade?

g.V()
  .hasLabel(Movie)
  .where(_.inE(Rated).count().is(P.gt(10)))
  .groupBy { movie =>
    val year = movie.value2(Year)
    val decade = (year / 10)
    (decade * 10): Integer
  }
  .map { moviesByDecade =>
    val highestRatedByDecade = moviesByDecade.mapValues { movies =>
      movies.toList
        .sortBy { _.inE(Rated).value(Stars).mean().head }
        .reverse.head //get the movie with the highest mean rating
    }
    highestRatedByDecade.mapValues(_.value2(Name))
  }
  .order(Scope.local).by(Order.keyIncr)
  .head

Serialise to and from files

Currently graphML, graphson and gryo/kryo are supported file formats, it is very easy to serialise and deserialise into those: see GraphSerialisationSpec. An easy way to visualise your graph is to export it into graphML and import it into gephi.

Help - it's open source!

If you would like to help, here's a list of things that needs to be addressed:

Why such a long version number?

The first three digits is the TP3 version number, only the last digit is automatically incremented on every release of gremlin-scala.

Talks

ScalaDays Berlin 2018

Further reading

For more information about Gremlin see the Gremlin docs and the Gremlin users mailinglist. Please note that while Gremlin-Scala is very close to the original Gremlin, there are differences to Gremlin-Groovy - don't be afraid, they hopefully all make sense to a Scala developer ;)

Random links:

Random things worth knowing

  • org.apache.tinkerpop.gremlin.structure.Transaction is not thread-safe. It's implemented with Apache's ThreadLocal class, see #196 (comment)

Releases

... happen automatically for every commit on master from travis.ci thanks to sbt-ci-release-early

YourKit endorsement

YourKit supports open source projects with innovative and intelligent tools for monitoring and profiling Java and .NET applications. YourKit is the creator of YourKit Java Profiler, YourKit .NET Profiler, and YourKit YouMonitor.

Breaking changes

3.4.7.2

Marshallable now treats Sets as multi-properties, i.e. one property for each element in the set. This is similar to how List properties are handled and allows for a natural representation of vertex properties whose cardinality is set in case classes. This change breaks compatibility with Marshallable's previous behaviour in which Sets were effectively treated as single cardinality properties, i.e. a single property whose value is the entire set.

3.4.1.13

The implementation for @label with non literal values (e.g. @label(SomeClass.LABEL)) was dropped due to it's bad performance. Please use String literals instead, e.g. @label("MyLabel").

3.3.3.2

We now have a fully typed union step which supports heterogeneous queries. The old version is still available as unionFlat, since it may still be relevant in some situations where the union traversals are homogeneous.

3.3.2.0

The by modulator is now called By. E.g. order(by(Order.decr)) becomes order(By(Order.decr)). Background: case insensitive platforms like OSX (default) and Windows fail to compile object by and trait By because they lead to two separate .class files. I decided for this option because it conforms to Scala's naming best practices. See #237 (comment).

3.3.1.2

To fix problems with remote graphs and the arrow syntax (e.g. vertex1 --- "label" --> vertex2) there now needs to be an implicit ScalaGraph in scope. Background: the configuration for remote is unfortunately not stored in the Tinkerpop Graph instance, but in the TraversalSource. Since a vertex only holds a reference to the graph instance, this configuration must be passed somehow. ScalaGraph does contain the configuration, e.g. for remote connections, so we now pass it implicitly.

3.3.1.1

The type signature of GremlinScala changed: the former type parameter Labels is now a type member, which shortens the type if you don't care about Labels. The Labels were only used in a small percentage of steps, but had to be written out by users all the time even if they didn't care. Rewrite rules (old -> new), using Vertex as an example: GremlinScala[Vertex, _] -> GremlinScala[Vertex] (existential type: most common, i.e the user doesn't use or care about the Labels) GremlinScala[Vertex, HNil] -> GremlinScala.Aux[Vertex, HNil] (equivalent: GremlinScala[Vertex] {type Labels = HNil}) GremlinScala[Vertex, Vertex :: HNil] -> GremlinScala.Aux[Vertex, Vertex :: HNil] (equivalent: GremlinScala[Vertex] {type Labels = Vertex :: HNil}) Notice: GremlinScala isn't a case class any more - it shouldn't have been in the first place.

3.2.4.8

The filter step changed it's signature and now takes a traversal: filter(predicate: GremlinScala[End, _] => GremlinScala[_, _]). The old filter(predicate: End => Boolean) is now called filterOnEnd, in case you still need it. This change might affect your for comprehensions.

The reasoning for the change is that it's discouraged to use lambdas (see http://tinkerpop.apache.org/docs/current/reference/#a-note-on-lambdas). Instead we are now creating anonymous traversals, which can be optimised by the driver, sent over the wire as gremlin binary for remote execution etc.

gremlin-scala's People

Contributors

0xroch avatar bowofolaf avatar ddrozdov avatar dkrieg avatar epost avatar fppt avatar gitter-badger avatar hubertp avatar ikeyan avatar ithinkicancode avatar jeffwilde avatar jeremysears avatar joan38 avatar jordanpenard avatar jtarvydas avatar l15k4 avatar lionelfleury avatar mikolak-net avatar mpollmeier avatar nikelin avatar omidb avatar petrjanda avatar satendrakumar avatar schrepfler avatar spmallette avatar thijsbroersen avatar to-om avatar tolbertam avatar vantonio avatar varju avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gremlin-scala's Issues

IntelliJ rebuild

Hi,
When I'm using the library in my code, for changes to be applied on my gremlin-scala codes I have to rebuild the whole project (which for a bug projects take time). Is there an specific thing that I have to set in my SBT file? any idea?

Thanks for the awesome wrapper.

Unresolved dependencies -- org.apache.tinkerpop

More of an sbt matter, but is there some build prerequisite that allows org.apache.tinkerpop to resolve? My sbt setup can only find com.tinkerpop. I am hoping to not have to resort to Gremlin-Java.

[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: org.apache.tinkerpop#gremlin-core;3.0.0-SNAPSHOT: not found
[warn] :: org.apache.tinkerpop#tinkergraph-gremlin;3.0.0-SNAPSHOT: not found
[warn] :: org.apache.tinkerpop#gremlin-test;3.0.0-SNAPSHOT: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn] Note: Unresolved dependencies path:
[warn] org.apache.tinkerpop:gremlin-core:3.0.0-SNAPSHOT (/Users/fpatton/third-party/gremlin-scala/build.sbt#L7-24)
[warn] +- com.michaelpollmeier:gremlin-scala_2.11:3.0.0-SNAPSHOT
[warn] org.apache.tinkerpop:tinkergraph-gremlin:3.0.0-SNAPSHOT (/Users/fpatton/third-party/gremlin-scala/build.sbt#L7-24)
[warn] +- com.michaelpollmeier:gremlin-scala_2.11:3.0.0-SNAPSHOT
[warn] org.apache.tinkerpop:gremlin-test:3.0.0-SNAPSHOT (/Users/fpatton/third-party/gremlin-scala/build.sbt#L7-24)
[warn] +- com.michaelpollmeier:gremlin-scala_2.11:3.0.0-SNAPSHOT

ScalaVertex has no properties

hello,

maybe I'm doing something wrong but I can use:

  vertex.property[Integer]("age")

with my graph.
Here is my configuration:

  "com.michaelpollmeier" % "gremlin-scala" % "2.3.0"


  val g = TitanFactory.open(conf)
  val gs = new ScalaGraph(g)
  def vertices = gs.V

so if I iterate over vertices I have blueprints Vertex:

            scala> vertices.next()
            res10: com.tinkerpop.blueprints.Vertex = v[32560]

not if I specify the type:

            scala> val vertex: ScalaVertex = vertices.next()
            vertex: com.tinkerpop.gremlin.scala.ScalaVertex = com.tinkerpop.gremlin.scala.ScalaVertex@266964d7

but anyways I can't access properties:

            scala> vertex.property
            <console>:20: error: value property is not a member of com.tinkerpop.gremlin.scala.ScalaVertex
                          vertex.property
                                    ^

Doesn't filter multi-valued property keys

Just started using this library(using version 2.4.2), really like it so far. I see an issue when querying multi valued property, it returns empty result. Here's my simplified test case

Just started using this library(using version 2.4.2), so far looks awesome. I'm filtering vertices with multiple 'has' conditions, and it's working just fine, except when the property is multivalued, in which case it returns blank/empty results.

gremlin> v = g.addVertex(["name":"John","alias":"J"])
gremlin> g.V
WARN com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx - Query requires iterating over all vertices [()]. For better performance, use indexes
==>v[40004]
gremlin> g.v(40004).map
==>{name=John}
gremlin> g.v(40004).addProperty("alias","j")
==>e[1G3J-ape-1k][40004-alias->j]
gremlin> g.v(40004).addProperty("alias","J")
==>e[1G3L-ape-1k][40004-alias->J]
gremlin> g.v(40004).map
==>{alias=[J, j], name=John}
gremlin> g.commit()
==>null

object MultiValueTest extends App {
val g: ScalaGraph = TitanFactory.open("/tmp/del")
val works_pipeline = g.V.has("name", "John")
val shouldwork_pipeline = g.V.has("alias", "j")
println(works_pipeline.toList) //prints List(v[40004])
println(shouldwork_pipeline.toList) //prints List() -- it should return the same node
g.shutdown()
}

traversalIsLocked

Hi, I have this problem:
what's wrong ?

this works:
val theList = gs.V.has("x","y")
// theList.out().toList().foreach(e => println(e.valueString))
theList.outE().map(e => e.label()).toList().foreach(println)


this works:
val theList = gs.V.has("x","y")
theList.out().toList().foreach(e => println(e.valueString))
// theList.outE().map(e => e.label()).toList().foreach(println)


this one NOT:
val theList = gs.V.has("x","y")
theList.out().toList().foreach(e => println(e.valueString))
theList.outE().map(e => e.label()).toList().foreach(println)

error stack:
at com.tinkerpop.gremlin.process.Traversal$Exceptions.traversalIsLocked(Traversal.java:232)
at com.tinkerpop.gremlin.neo4j.process.graph.util.Neo4jGraphTraversal.addStep(Neo4jGraphTraversal.java:35)
at com.tinkerpop.gremlin.neo4j.process.graph.util.Neo4jGraphTraversal.addStep(Neo4jGraphTraversal.java:16)
at com.tinkerpop.gremlin.process.graph.GraphTraversal.toE(GraphTraversal.java:162)
at com.tinkerpop.gremlin.neo4j.process.graph.Neo4jTraversal.toE(Neo4jTraversal.java:478)
at com.tinkerpop.gremlin.neo4j.process.graph.Neo4jTraversal.toE(Neo4jTraversal.java:24)
at com.tinkerpop.gremlin.process.graph.GraphTraversal.outE(GraphTraversal.java:166)
at com.tinkerpop.gremlin.neo4j.process.graph.Neo4jTraversal.outE(Neo4jTraversal.java:362)
at com.tinkerpop.gremlin.neo4j.process.graph.Neo4jTraversal.outE(Neo4jTraversal.java:24)
at com.tinkerpop.gremlin.scala.GremlinScala$GremlinVertexSteps.outE(GremlinScala.scala:313)
at rocnlp.Neo4j3$delayedInit$body.apply(Neo4j3.scala:18)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at rocnlp.Neo4j3$.main(Neo4j3.scala:9)
at rocnlp.Neo4j3.main(Neo4j3.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

V() function

Hi,

In TP3 why V is now V() ?
Since it has a set of parentheses it doesn't call the implicit conversion so I need to wrap manually with ScalaGraph() the implementation.

Cheers

Investigate Rexster Script-Engine performance issue.

_This will NOT hit you if you are not using https://github.com/tinkerpop/rexster!_

I'm getting 200-2000ms to eval a single "g.addV" command, which is a nightmare comparing to Groovy's ~10ms.

A few things tried:
a) manually getting the binding script, combined it with the user script and interpret the whole in one interpret() call. This should have speed things up a lot but there's hardly a way to know since the interpreting time is so unstable and unpredictable;
b) tried to use the more light-weighted scala.tools.reflect.ToolBox, it should be faster but due a bug* in the toolbox compiler, we can't even import the tinkperpop libs properly :-(

Any thoughts?

*https://issues.scala-lang.org/browse/SI-7378?page=com.atlassian.jira.plugin.system.issuetabpanels:changehistory-tabpanel

how to Commit graph data

How do you do a graph.Commit() of the graph data? There is no commit method on the ScalaGraph, just shutdown. Thanks in advance, and thanks for this library :)

Question: running gremlin-scala along side gremlin-groovy in Rexster

My current understanding is that one can configure rexster to run multiple script engines. I'd like to run both groovy and scala gremlin scripts through rexster. It is not clear in the documentation how to configure and reference each script engine. Can you please provide additional documentation to cover this use case or point me in the right direction?

count function vs count.head

Hi,
I'm using tinkerpop3, I'm trying to make a full example of what is in tinkerpop3 documentation for tinkepop3-scala.
Here what I got from 'count()'
assert(gs.V.count() == 50) //failed
assert(gs.V.count().head() == 50) //passed
in tinkerpop3 documentations: assert(gs.V.count() == 50) will pass

thanks,
Omid

NoClassDefFoundError: : com/tinkerpop/gremlin/structure/Graph$System

A problem occurs in version 3.0.0.M7. Works fine with M.0.0.6c

name := "test-gremlin-scala"

version := "1.0"

scalaVersion := "2.11.5"

libraryDependencies ++= Seq(
  "com.michaelpollmeier"       %% "gremlin-scala"   % "3.0.0.M7",
  "com.thinkaurelius.titan"    %  "titan-core"      % "0.9.0-M1",
  "com.thinkaurelius.titan"    %  "titan-cassandra" % "0.9.0-M1",
  "com.thinkaurelius.titan"    %  "titan-es"        % "0.9.0-M1"
)

Test file:

import com.thinkaurelius.titan.core.{TitanFactory, TitanGraph}
import com.tinkerpop.gremlin.scala.GremlinScala
import org.apache.commons.configuration.BaseConfiguration

object App {
  def main(args: Array[String]) = {
    val g = createSimpleTestGraphWithGremlinScala()
    println(g)
  }

  def createSimpleTestGraphWithGremlinScala(): TitanGraph = {
    val newGraph = createEmptyInMemoryGraph()

    val gs = GremlinScala(newGraph)

    val v1 = gs.addVertex("v1")
    val v2 = gs.addVertex("v2")
    v1.addEdge("uses", v2, Map())

    newGraph
  }

  def createEmptyInMemoryGraph(): TitanGraph = {
    val conf = new BaseConfiguration()
    conf.addProperty("storage.backend", "inmemory")
    val newGraph = TitanFactory.open(conf)
    newGraph
  }
}

An attempt to add a vertex (val v1 = gs.addVertex("v1")) results in
NoClassDefFoundError: : com/tinkerpop/gremlin/structure/Graph$System (Token.java:35)

Performance issues with Indices

Hi,

I tried the 2 following query in Titan and Neo4j and it seems that it's not using the indices optimisation ~O(1) and staying in O(n):
graph.V.has("dmdid", id).has("type", type).toStream()
graph.query().has("dmdid", id).has("type", type).vertices().toStream

This is a major issue since we can't use gremlin-scala once we start to put some data in the graph, queries takes ages.

Cheers

AddE throwing IllegalArgumentException: null (Preconditions.java:76)

Hi Michael,

I am using Scala 2.10.2 with "com.michaelpollmeier" % "gremlin-scala" % "2.4.1" and Titan 0.4.0.

The following code

println(fromV.getClass) // prints Class com.tinkerpop.gremlin.scala.ScalaVertex
println(targetV.getClass) // prints Class com.tinkerpop.gremlin.scala.ScalaVertex
println(label) // prints "mylbl"
graph.addE(fromV,targetV,label)

produces

 IllegalArgumentException: null (Preconditions.java:76)

[error] com.google.common.base.Preconditions.checkArgument(Preconditions.java:76)
[error] com.thinkaurelius.titan.graphdb.blueprints.TitanBlueprintsTransaction.addEdge(TitanBlueprintsTransaction.java:94)

I used breakpoints and checked line 94 of TitanBlueprintsTransaction.java, here is the issue (code below is from the TitanBlueprintsTransaction file):

public Edge addEdge(Object id, Vertex outVertex, Vertex inVertex, String label) {
    Preconditions.checkArgument(outVertex instanceof TitanVertex); // <-- This line fails, outVertex is instance of ScalaVertex thus the expression returns false.
    Preconditions.checkArgument(inVertex instanceof TitanVertex);
    return addEdge((TitanVertex) outVertex, (TitanVertex) inVertex, label);
}

Cheers,
Ali

Please add a match step example

Hello, could you add an example on how to perform the match-select pattern with gremilin scala?

This is an example from the Tinkerpop documentation:

gremlin> g.V().match('a',
            __.as('a').out('created').as('b'),
            __.as('b').has('name', 'lop'),
            __.as('b').in('created').as('c'),
            __.as('c').has('age', 29)).
          select('a', 'c').by('name')

Being a total newcomer I tried to invoke the match step on a GremlinScala class, but seems to me it's not implemented yet.
Then I tried to invoke it directly on the graph object. This is the code I have right now:

    val graph = TinkerGraph.open()
    var gs = GremlinScala(graph)
    val vertex = gs.addVertex("hello")
    var vertex2 = gs.addVertex("world")
    vertex.addEdge("followed_by", vertex2, Map())

    val result = graph.V.outE().`match`(
      "a",
      __.as("a").inV().as("b") // what to put here ?
    ) // .....

Which does not seem to work. What should I substitute to __ to have the code compile?

Perhaps a little example in the readme would help many others :)

Getting value in an Option

Hi,

I saw those 2 functions in GremlinElementSteps:

def value[A](key: String): A = element.value[A](key)

def valueWithDefault[A](key: String, default: A): A = property[A](key).orElse(default)

And I was wondering:

  • if we can add a method to get an Option instead of the value and avoid the IllegaleStateException.
  • if we can rename the WithDefault to OrElse for consistency with the rest of the Scala library.

Something like that:

def getValue[A](key: String): A = element.value[A](key)

def value[A](key: String): Option[A] = {
  val property = property[A](key)
  if (property.isPresent) Some(property.value)
  else None
}

def valueOrElse[A](key: String, default: A): A = property[A](key).orElse(default)

Cheers

Investigate engine loading problem.

I tried to deploy the jars into a rexster server but it doesn't load:

add the following line into rexster config xml file:

<script-engines>gremlin-scala</script-engines>

start the server, rexster found the GremlinScalaScriptEngineFactory, but it doesn't load the engine:

13/06/03 17:12:04 INFO server.RexProRexsterServer: Rexster configured with no security.
13/06/03 17:12:06 INFO auth.Auth: Created default superuser 'cassandra'
13/06/03 17:12:06 INFO protocol.EngineController: ScriptEngineManager has factory for: gremlin-groovy
13/06/03 17:12:06 INFO protocol.EngineController: Registered ScriptEngine for: gremlin-groovy
13/06/03 17:12:07 INFO protocol.EngineController: ScriptEngineManager has factory for: gremlin-scala
13/06/03 17:12:07 INFO protocol.EngineController: ScriptEngineManager has factory for: ECMAScript
13/06/03 17:12:07 INFO protocol.EngineController: ScriptEngineManager has factory for: Groovy
13/06/03 17:12:07 INFO server.RexProRexsterServer: Using org.glassfish.grizzly.strategies.LeaderFollowerNIOStrategy IOStrategy for RexPro.
13/06/03 17:12:07 INFO server.RexProRexsterServer: RexPro serving on port: [8184]

we need this line for an engine to be loaded:
protocol.EngineController: Registered ScriptEngine for: gremlin-groovy

sending a rexpro script also confirms that the engine is not properly loaded.

Upgrade to tinkerpop 2.3.0

Tinkerpop 2.3.0 has been released! When will gremlin-scala be upgraded to fit in with the new refactoring of the codebase?

Indexing

How can enable indexing in gremlin-scala?
Apparently in Java gremlin there is a feature like this:
gremlin> g.createKeyIndex("my_key",Vertex.class)

Add back with int

It's not real an issue but it can be great to have the full gremlin spec so just add somting like
def back(numberStep: Int): GremlinScalaPipeline[S, Any] = addPipe(new BackFilterPipe(new Pipeline(FluentUtility.removePreviousPipes(this, numberStep))))
in GremlinScalaPipe.scala

List all vertices along specific edges without target vertex.

I want to get a Set (in a directed, acyclic graph) of all vertices starting by the vertex with property "label" == "A". Edges are always labeled with "edge".

Example Graph:
example

So the result should be:
["A", "B", "C", "F", "D", "E"] or ["A", "B", "D", "E", "C", "F"]
Ordering does not matter. Its not a question about the shortest path. All vertices along all possible paths should be included in the resulting Set.

How would an appropriate traverser look like?

sbt dependency: error while loading <root>, error in opening zip file

hello
I have a problem while trying to use 2.4 :
"com.michaelpollmeier" % "gremlin-scala" % "2.4.0",

with sbt 12.4 and scala 2.10.2:

[info] Resolving com.thoughtworks.paranamer#paranamer;2.3 ...
[info] downloading https://oss.sonatype.org/content/groups/public/com/michaelpollmeier/gremlin-scala/2.4.0/gremlin-scala-2.4.0.jar ...
[info] [SUCCESSFUL ] com.michaelpollmeier#gremlin-scala;2.4.0!gremlin-scala.jar (261012ms)
[info] downloading https://oss.sonatype.org/content/groups/public/com/tinkerpop/gremlin/gremlin-groovy/2.4.0/gremlin-groovy-2.4.0.jar ...
[info] [SUCCESSFUL ] com.tinkerpop.gremlin#gremlin-groovy;2.4.0!gremlin-groovy.jar (3400ms)
[info] downloading https://oss.sonatype.org/content/groups/public/com/tinkerpop/gremlin/gremlin-java/2.4.0/gremlin-java-2.4.0.jar ...
[info] [SUCCESSFUL ] com.tinkerpop.gremlin#gremlin-java;2.4.0!gremlin-java.jar (2577ms)
[info] downloading https://oss.sonatype.org/content/groups/public/com/tinkerpop/pipes/2.4.0/pipes-2.4.0.jar ...
[info] [SUCCESSFUL ] com.tinkerpop#pipes;2.4.0!pipes.jar (3261ms)
[info] downloading https://oss.sonatype.org/content/groups/public/org/scala-lang/scala-reflect/2.10.2/scala-reflect-2.10.2.jar ...
[info] [SUCCESSFUL ] org.scala-lang#scala-reflect;2.10.2!scala-reflect.jar (18911ms)
[info] downloading https://oss.sonatype.org/content/groups/public/org/scala-lang/jline/2.10.2/jline-2.10.2.jar ...
[info] [SUCCESSFUL ] org.scala-lang#jline;2.10.2!jline.jar (3704ms)
[info] downloading http://repo1.maven.org/maven2/org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar ...
[info] [SUCCESSFUL ] org.apache.ivy#ivy;2.3.0!ivy.jar (3078ms)
[info] downloading http://repo1.maven.org/maven2/org/apache/ant/ant/1.8.3/ant-1.8.3.jar ...
[info] [SUCCESSFUL ] org.apache.ant#ant;1.8.3!ant.jar (1419ms)
[info] downloading https://oss.sonatype.org/content/groups/public/com/tinkerpop/blueprints/blueprints-core/2.4.0/blueprints-core-2.4.0.jar ...
[info] [SUCCESSFUL ] com.tinkerpop.blueprints#blueprints-core;2.4.0!blueprints-core.jar (3487ms)
[info] downloading http://repo1.maven.org/maven2/org/apache/ant/ant-launcher/1.8.3/ant-launcher-1.8.3.jar ...
[info] [SUCCESSFUL ] org.apache.ant#ant-launcher;1.8.3!ant-launcher.jar (287ms)
[info] Done updating.
[info] Compiling 21 Scala sources to /home/vagrant/alexandre/pogistan/target/scala-2.10/classes...
[error] error while loading , error in opening zip file
scala.reflect.internal.MissingRequirementError: object scala.runtime in compiler mirror not found.
at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
at scala.reflect.internal.Mirrors$RootsBase.getPackage(Mirrors.scala:172)
at scala.reflect.internal.Mirrors$RootsBase.getRequiredPackage(Mirrors.scala:175)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage$lzycompute(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass$lzycompute(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr$lzycompute(Definitions.scala:1015)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr(Definitions.scala:1014)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses$lzycompute(Definitions.scala:1144)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses(Definitions.scala:1143)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode$lzycompute(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1252)
at scala.tools.nsc.Global$Run.(Global.scala:1289)
at xsbt.CachedCompiler0.run(CompilerInterface.scala:86)
at xsbt.CachedCompiler0.run(CompilerInterface.scala:72)
at xsbt.CompilerInterface.run(CompilerInterface.scala:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sbt.compiler.AnalyzingCompiler.call(AnalyzingCompiler.scala:73)
at sbt.compiler.AnalyzingCompiler.compile(AnalyzingCompiler.scala:35)
at sbt.compiler.AnalyzingCompiler.compile(AnalyzingCompiler.scala:29)
at sbt.compiler.AggressiveCompile$$anonfun$4$$anonfun$compileScala$1$1.apply$mcV$sp(AggressiveCompile.scala:71)
at sbt.compiler.AggressiveCompile$$anonfun$4$$anonfun$compileScala$1$1.apply(AggressiveCompile.scala:71)
at sbt.compiler.AggressiveCompile$$anonfun$4$$anonfun$compileScala$1$1.apply(AggressiveCompile.scala:71)
at sbt.compiler.AggressiveCompile.sbt$compiler$AggressiveCompile$$timed(AggressiveCompile.scala:101)
at sbt.compiler.AggressiveCompile$$anonfun$4.compileScala$1(AggressiveCompile.scala:70)
at sbt.compiler.AggressiveCompile$$anonfun$4.apply(AggressiveCompile.scala:88)
at sbt.compiler.AggressiveCompile$$anonfun$4.apply(AggressiveCompile.scala:60)
at sbt.inc.IncrementalCompile$$anonfun$doCompile$1.apply(Compile.scala:24)
at sbt.inc.IncrementalCompile$$anonfun$doCompile$1.apply(Compile.scala:22)
at sbt.inc.Incremental$.cycle(Incremental.scala:52)
at sbt.inc.Incremental$.compile(Incremental.scala:29)
at sbt.inc.IncrementalCompile$.apply(Compile.scala:20)
at sbt.compiler.AggressiveCompile.compile2(AggressiveCompile.scala:96)
at sbt.compiler.AggressiveCompile.compile1(AggressiveCompile.scala:44)
at sbt.compiler.AggressiveCompile.apply(AggressiveCompile.scala:31)
at sbt.Compiler$.apply(Compiler.scala:79)
at sbt.Defaults$$anonfun$compileTask$1.apply(Defaults.scala:574)
at sbt.Defaults$$anonfun$compileTask$1.apply(Defaults.scala:574)
at sbt.Scoped$$anonfun$hf2$1.apply(Structure.scala:578)
at sbt.Scoped$$anonfun$hf2$1.apply(Structure.scala:578)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:49)
at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:41)
at sbt.std.Transform$$anon$5.work(System.scala:71)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
at sbt.Execute.work(Execute.scala:238)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:160)
at sbt.CompletionService$$anon$2.call(CompletionService.scala:30)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
error scala.reflect.internal.MissingRequirementError: object scala.runtime in compiler mirror not found.

java convertion

Hi,
This works:
val one:java.lang.Integer = 1
val marko = gs.v(one)

This not:
val marko = gs.v(1)
error:
Error:(40, 23) type mismatch;
found : Int(1)
required: AnyRef
Note: an implicit exists from scala.Int => java.lang.Integer, but
methods inherited from Object are rendered ambiguous. This is to avoid
a blanket implicit which would convert any scala.Int to any AnyRef.
You may wish to use a type ascription: x: java.lang.Integer.
val marko = gs.v(1)
^

noob here: Using Neo4jGraph instance for access to embedded db

Hi..sorry but I'm pretty newbie with neo4j and I wish access to my local db...I'm following this article

http://bleibinha.us/blog/2013/10/scala-and-graph-databases-with-gremlin-scala

basically I did this
val neo4jDirectory = "home/yo/Downloads/proj/neo4j-community-2.1.2/neo4j-community-1.9.8/data/graph.db"

val g = new Neo4jGraph(neo4jDirectory)

now..this works...but my g object only has a small subset of methods (neither V or E)
scala> g.
addEdge addVertex
asInstanceOf commit
createIndex createKeyIndex
dropIndex dropKeyIndex
getEdge getEdges
getFeatures getIndex
getIndexedKeys getIndices
getInternalIndexKeys getRawGraph
getVertex getVertices
isInstanceOf query
removeEdge removeVertex
rollback setCheckElementsInTransaction
shutdown stopTransaction
toString

yes..I know..this is the most noob question than you've ever heard...but I can't get the mistake..I try with TinkerGraph but neither works...

thanks and sorry for the so noob question...

What up about except(step:String) ?

Hello,

I just seen there is an un implemented exception for this function in GremlinScalaPipeline with this comment : "not currently supported because ExceptFilterPipe uses ElementHelper.areEqual to compare two elements, which compares if the classes are equal.

  • I'll open a pull request to fix that in blueprints shortly..."

Did you receve any update?

Indexing for the edges

Hi,

I know how to do indexing on the vertices, is there any solution for doing it for the edges?

--Omid

Tinkerpop3 branch compilation errors

Hey Michael,

I was just checking out what's new in tinkerpop3 and gremlin-scala that I'm unable to compile due to a several weird compilation errors. I tried a few version combinations of scala and java, but none of them made it. Would you please let me know what you know :-) ? I haven't had a chance to look at shapeless yet. And those compilation errors vary depending on version of scala and java I use, so I'm not gonna paste it here

outE.toList is java List

I was playing with the wrapper, here something that happens in some places, for example here

gs.v(1).outE("friend").toList

the code returns a Java List, I found also sometime some function returns Java objects instead of scala object like ScalaVertex.

function toMap

It's a minor improvement but usefull.
there is somme usefull methode like toList and toSet but when i use the function "cap" after a pipe "groupby" i should do something ugly like this :

sucessPipe.toList.get(0).asInstanceOf[JHashMap[List[List[String]], JArrayList[T]]].toMap.map{case (a,b) => (a,b.toList)}

I don't know how to generalize the key and values but a function toMap could do
the first part.

LoopBundle.getLoops starts at 2

As in the description, the value returned from getLoops is 2 the first time you enter the whileFunction.

This appears to be a bug in the main pipes project, but it's hard to tell - it looks like it might be an issue with the tinkerpop3 code as well.

Check out this branch with a repro case, and notes on where I think the existing unit tests are incorrect.

Simple path finding

It's not a Gremlin Scala specific question, I want to know what would be the simplest way to recursively find all path from node v1 that has out edge labeled of "friend". Basically exploring the whole graph from v1.

thanks

plugin gremlin scala to Titan

hello,
thanks a lot for this awesome work.

I interfere with a titan graph in a scala code a bit like this:

val g = TitanFactory.open(conf)

hasNot is not a member of ...

Hi again,
I'm trying to test every aspect of Tinkerprop3, here is one other place that don't match with Groovy version:

gs.V.as("a").properties("location").hasNot("endTime").as("b")

Error:(44, 41) value hasNot is not a member of com.tinkerpop.gremlin.scala.GremlinScala[com.tinkerpop.gremlin.structure.Property[Any],shapeless.::[com.tinkerpop.gremlin.scala.Vertex,shapeless.HNil]]
gs.V.as("a").properties("location").hasNot("endTime").as("b")

and also this one:
gs.V.has("name","gremlin").inE("uses").orderBy("skill")
Error:(44, 44) value orderBy is not a member of com.tinkerpop.gremlin.scala.GremlinScala[com.tinkerpop.gremlin.scala.Edge,shapeless.HNil]
gs.V.has("name","gremlin").inE("uses").orderBy("skill")
^

--Omid

Question: how to use Titan CONTAINS and Geo.WITHIN

Original question by @vallettea: https://github.com/tinkerpop/gremlin/issues/360

Overview:

my question is about elastic search: the CONTAINS is not the scala function but

import com.thinkaurelius.titan.core.attribute.Text.CONTAINS
I would also like to use:

import com.thinkaurelius.titan.core.attribute.Geo.WITHIN
like so:

g.query().has("coords", WITHIN, Geoshape.circle(43.7323099, 7.420435, 0.05)).vertices()
These are the kind of queries I perform on gremlin-groovy repl and I would like to do them inside my scala code.

Implicit class instead of implicit wrappers in companion object

Say I have test like this:

 "gremlin scala" should "have type problem" ignore {
    import com.tinkerpop.gremlin.scala.ScalaGraph._
    import com.tinkerpop.gremlin.scala.ScalaVertex._
    val neo4jDirectory = "/tmp/neo4j3"
    val neo4j: ScalaGraph = new Neo4jGraph(neo4jDirectory)
    val vertex = neo4j.addV()
    neo4j.v(vertex.getId).out("whatever")
    neo4j.shutdown()
}

that won't compile, because neo4j.v() returns Vertex and scala can't wrap it automatically to ScalaVertex...

but If I use implicit class feature like that:

 object ScalaVertexImplicits {
    implicit class ScalaVertexImplicit(v: Vertex) {
      def out(labels: String*): GremlinScalaPipeline[Vertex, Vertex] = {
        new ScalaVertex(v).out(labels: _*)
      }
    }
  }

  "gremlin scala" should "works fine" in {
    import com.tinkerpop.gremlin.scala.ScalaGraph._
    import com.tinkerpop.gremlin.scala.ScalaVertex._
    import ScalaVertexImplicits._
    val neo4jDirectory = "/tmp/neo4j3"
    val neo4j: ScalaGraph = new Neo4jGraph(neo4jDirectory)
    val vertex = neo4j.addV()
    neo4j.v(vertex.getId).out("whatever")
    neo4j.shutdown()
  }

everything seems fine.

Implicit class also should allow delete that ugly "manual type inference" val neo4j: ScalaGraph

Am I right or am I missing something?

Another noob here, titan config?

Hey, I'm really trying to get this working with Titan. However, Titan needs quite a bit of config to start up, and I can't figure it out in gremlin scala. My basic startup script right now is:

object IcebergGraph {
var g: TitanGraph = null

def getTitanConf = {
val conf = new BaseConfiguration();

conf.setProperty("storage.backend","berkeleyje");
conf.setProperty("storage.directory","../titandb/local");
conf.setProperty("storage.index.search.backend", "elasticsearch");
conf.setProperty("storage.index.search.hostname", "../titandb/searchindex");
conf.setProperty("storage.index.search.client-only", "true");
conf.setProperty("storage.index.search.local-mode", "true");

conf

}

def getTitanConnection = {
if (g == null || !g.isOpen()) {
g = TitanFactory.open(getTitanConf);
}
g
}
}

But I can't use this connection with gremlin scala, I take it, that it must create a different type of instance with the graph. I've tried digging into the source, but I'm just not that good yet. Any help would be great, I'd love to write a blog post about this to help others get started with it. Thanks

When might the Tinkerpop 3 branch be ready for use in a production application?

Hi,
apologies if it's not usually good form to ask about ETA's, however, I'd really like to code my Tinkerpop (TP) interactions against Scala (mainly for its brevity), and it has been suggested to me by the TP team that I start directly with TP3:

(16th Sept 2014)

Here are my thoughts.

  1. TinkerPop3 M2 is days away so start coding to that when it comes out.
  2. If you are using Neo4j, you will be a in great position for TinkerPop3 usage -- as TinkerPop3 GA is then maybe 1 month away and
    Neo4j is a reference implementation of TP3.
  3. If you are using any other backend, you will most likely see their TP3 implementations coming by years end. ?? (up to the vendors)
  4. If you are using Titan, then Titan 0.9 will come out within 1-2 months with TP3 support.

In short, avoid using TP2 if you can.

HTH, Marko.

http://markorodriguez.com

So, realistically, when might we use your TP3 solution without too many hiccups.

Thanks

Rich

How can I use the snapshot project within my own project?

So, this is more of a question than a bug/issue. How can I use this gremlin-scala snapshot in my own project? I tried to use it was follows.

I built this so that it would place the snapshot into the .m2 directory on my computer:
https://github.com/tinkerpop/tinkerpop3

Then in my sbt project:
lazy val tinkerPop3 = RootProject(uri("git://github.com/mpollmeier/gremlin-scala.git#%s".format("tinkerpop3-snapshot")))

Which I then add a a dependsOn
.dependsOn(tinkerPop3)

Then I go to compile my program and I get lots of errors about SFunction and SPredicate. Any suggestion? Thanks!

[info] Compiling 4 Scala sources to /home/home/.sbt/0.13/staging/cf2b138b3216f8c286ba/gremlin-scala/target/scala-2.11/classes...
[error] /home/home/.sbt/0.13/staging/cf2b138b3216f8c286ba/gremlin-scala/src/main/scala/com/tinkerpop/gremlin/package.scala:7: object SFunction is not a member of package com.tinkerpop.gremlin.util.function
[error] import com.tinkerpop.gremlin.util.function.SFunction
[error] ^
[error] /home/home/.sbt/0.13/staging/cf2b138b3216f8c286ba/gremlin-scala/src/main/scala/com/tinkerpop/gremlin/package.scala:8: object SPredicate is not a member of package com.tinkerpop.gremlin.util.function
[error] import com.tinkerpop.gremlin.util.function.SPredicate
[error]

Vertex to case class and vice versa in TP3

Hi,

Is there any plan to have a method converting Vertex to case class and the other way around or this is out of the project scope?

Do you see any cons to do something like that? I'm worried about the multivalue per property in TP3 but I don't see other limitations for now.
Because if not I'm gone a do an implementation and will be happy to discus about that.

Cheers

Implement GroupByReducePipe

Hello,

there is a extention of GroupByPipe with a third argument the "reduceFunction" : GroupByReducePipe.

This function add a reduce function to group by, the reduce function can be count an average ...
This function is apply on each List of each groups to 'reduce' this list to a single element. exemple List[Double] => Double.

I tried to implement that like that

def mapReduce[K, V, V2](map: JMap[K,V2] = new JHashMap[K,V2])( keyFunction: E ⇒ K, valueFunction: E ⇒ V , reduceFunction :java.util.List[V] ⇒ V2  ): GremlinScalaPipeline[S, E] =
    addPipe(
      new GroupByReducePipe(
        map,
        new ScalaPipeFunction(keyFunction),
        new ScalaPipeFunction(valueFunction),
        new ScalaPipeFunction(reduceFunction).asInstanceOf[ScalaPipeFunction[java.util.Collection[V], V2]]
      )
    )

def key(v :Vertex) = v

def groupValue( v : Vertex ) = v.name  //for exemple

/* exemple of reduce function
*/
def reduce(l :List[Vertex]) = {
   l.size
}

My implementation go wrong because the reduceFunction is never call, i don't know if it's because there in a problem in scala => java or if there is a problem in Pipe.

This function can be done on each list of the result of ScalaGremlin groupby (+cap) witch is a Map[K,List[V]] so Map[K,List[V]] => Map[K,V2]
But i don't know if the performance are better.

value V is not a member of com.tinkerpop.blueprints.impls.tg.TinkerGraph

scala> import com.tinkerpop.gremlin.Tokens
import com.tinkerpop.gremlin.Tokens

scala> import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory
import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory

scala>   val graph = TinkerGraphFactory.createTinkerGraph
graph: com.tinkerpop.blueprints.impls.tg.TinkerGraph = tinkergraph[vertices:6 edges:6]

scala>   def vertices = graph.V
<console>:10: error: value V is not a member of com.tinkerpop.blueprints.impls.tg.TinkerGraph

Am I using this wrong? I grabbed this code straight from GremlinTest.scala

Neo4j version

Hi,

How can I specify my Neo4j version, when I'm running my code I get following error, and when I enable "allow_store_upgrade=true" in neo4j property file, I will get the same error.is there any way to specify Neo4j version?
My Gremlin Version: 3.0.0.M5 (tested 2.6 same thing happened)

My code:
import com.tinkerpop.gremlin.neo4j.structure.Neo4jGraph
val graph: Neo4jGraph = Neo4jGraph.open("E:/scratch/test47/")
graph.close()

error:

Exception in thread "main" java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, E:\scratch\test47
at com.tinkerpop.gremlin.neo4j.structure.Neo4jGraph.(Neo4jGraph.java:123)
at com.tinkerpop.gremlin.neo4j.structure.Neo4jGraph.open(Neo4jGraph.java:139)
at com.tinkerpop.gremlin.neo4j.structure.Neo4jGraph.open(Neo4jGraph.java:148)
at rocnlp.wordnetNeo4j2$delayedInit$body.apply(wordnetNeo4j2.scala:6)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at rocnlp.wordnetNeo4j2$.main(wordnetNeo4j2.scala:3)
at rocnlp.wordnetNeo4j2.main(wordnetNeo4j2.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, E:\scratch\test47
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:366)
at org.neo4j.kernel.EmbeddedGraphDatabase.(EmbeddedGraphDatabase.java:59)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:91)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:181)
at com.tinkerpop.gremlin.neo4j.structure.Neo4jGraph.(Neo4jGraph.java:101)
... 17 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.transaction.XaDataSourceManager@6c130c45' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:343)
... 21 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@6a84a97d' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.start(XaDataSourceManager.java:164)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
... 23 more
Caused by: org.neo4j.kernel.impl.storemigration.UpgradeNotAllowedByConfigurationException: Failed to start Neo4j with an older data store version. To enable automatic upgrade, please set configuration parameter "allow_store_upgrade=true"
at org.neo4j.kernel.impl.storemigration.ConfigMapUpgradeConfiguration.checkConfigurationAllowsAutomaticUpgrade(ConfigMapUpgradeConfiguration.java:39)
at org.neo4j.kernel.impl.storemigration.StoreUpgrader.migrateIfNeeded(StoreUpgrader.java:143)
at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.start(NeoStoreXaDataSource.java:345)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)

Removing Edges

Is there a way to remove Edges once they are added? A cant see any function for this in GremlinScala.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.