Coder Social home page Coder Social logo

gremlinrestclient's Introduction

Gremlin REST Client

An HTTP client for the Gremlin server.

Features

  • An easy to use client class GremlinRestClient that allows you to submit scripts to the Gremlin Server.
  • A a series of mid-level classes that all inherit from GremlinRestClient and Graph. These classes correspond to various Tinkerpop 3 vendor implementations and provide convenience methods for creating indices, schemas, etc.
  • The Create API, utilized by the Graph classes. Allows for easy programmatic creation of nodes and edges using Python dict and tuple.

Installation

Install using pip.

$ pip install gremlinrestclient

Getting Started

Run a script to add a vertex to the graph.

>>> import gremlinrestclient
>>> client = gremlinrestclient.GremlinRestClient()
>>> resp = client.execute(
...     "graph.addVertex(label, p1, 'name', p2)",
...     bindings={"p1": "person", "p2": "dave"})
>>> resp
Response(status_code=200, data=[{u'properties': {u'name': [{u'id': 226, u'value': u'dave'}]}, u'type': u'vertex', u'id': 225, u'label': u'person'}], message={}, metadata=u'')

Create API

The Graph subclasses use the Create API to make the creation of nodes and edges easier. In the spirit of keeping it simple, nodes are dict objects. It is important to note that the key label always refers to the optional node label, and if the key id is passed it will be clobbered. If you need a property called id, consider using _id instead.

Consider the following example:

>>> graph = gremlinrestclient.TinkerGraph()
>>> d = {"name": "dave", "label": "person"}
>>> coll = graph.create(d)
>>> coll
Collection(
    vertices=(
        Vertex(id=227, label=u'person', properties={u'name': [{u'id': 228, u'value': u'dave'}]}),), edges=())
>>> vertex.vertices
(Vertex(id=227, label=u'person', properties={u'name': [{u'id': 228, u'value': u'dave'}]}),)

The create method returns a namedtuple called Collection. Collection contains two fields, vertices and edges, which are tuples of Vertex and Edge objects respectively. Lot’s of tuples.

To create edges, we use more tuple (not to be confused with the namedtuple Vertex). Observe:

>>> d = {"name": "dave", "label": "person"}
>>> p = {"name": "python", "label": "lang"}
>>> e = (d, "LIKES", p, {'weight': 1})
>>> graph.create(e)
Collection(
    vertices=(
        Vertex(id=248, label=u'person', properties={u'name': [{u'id': 249, u'value': u'dave'}]}),
        Vertex(id=250, label=u'lang', properties={u'name': [{u'id': 251, u'value': u'python'}]})),
    edges=(
        Edge(id=252, source_id=248, label=u'LIKES', target_id=250, properties={u'weight': 1}),))

Edge tuples are always the same (source, label, target, properties), but there are several ways to pass the source and target nodes to the tuple list. Instead of passing a node dictionary directly to an edge, you can pass the node dictionary as an argument, and pass its index to the edge tuple:

>>> p = {"name": "python", "label": "lang"}
>>> graph.create({"name": "dave", "label": "person"}, (0, "LIKES", p, {'weight': 1}))
Collection(
    vertices=(
        Vertex(id=229, label=u'person', properties={u'name': [{u'id': 230, u'value': u'dave'}]}),
        Vertex(id=231, label=u'lang', properties={u'name': [{u'id': 232, u'value': u'python'}]})),
    edges=(
        Edge(id=233, source_id=229, label=u'LIKES', target_id=231, properties={}),))

Here, the 0 in the edge tuple simple refers to the zeroith argument passed to the create() method.

Finally, you can pass a gremlinrestclient.graph.Vertex object (or two) to the edge tuple. Check:

>>> d = {"name": "dave", "label": "person"}
>>> coll = graph.create(d)
>>> dave, = coll.vertices  # Unpack tuple of length 1
>>> graph.create(
...     {"name": "python", "label": "lang"},
...     (dave, "LIKES", 0, {'weight': 1}))
Collection(
    vertices=(
        Vertex(id=261, label=u'lang', properties={u'name': [{u'id': 262, u'value': u'python'}]}),),
    edges=(
        Edge(id=263, source_id=259, label=u'LIKES', target_id=261, properties={u'weight': 1}),))

Note that only newly created nodes and edges are created in the collection.

Contribute

Contributions are welcome. If you find a bug, or have a suggestion, please open an issue on Github. If you would like to make a pull request, please make sure to add appropriate tests and run them:

$ python setup.py test

In the future there will be CI and more info on contributing.

gremlinrestclient's People

Contributors

amittr avatar davebshow avatar elubow avatar smunx avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

gremlinrestclient's Issues

Vertex mixup in creating edges

To 'work around' #3 I assumed the python vertex needs to be created before connecting other vertices to it:

p, = graph.create({"name": "python", "label": "lang"}).vertices
d = {"name": "dave", "label": "person"}
f = {"name": "frens", "label": "person"}

coll = graph.create(
    (d, 'likes', p, {}),
    (f, 'likes', p, {})
)
pprint(coll.vertices + coll.edges)

But actually, Frens likes python twice!

(Vertex(id=28680, label='person', properties={'name': [{'id': '7i9-m4o-4flx', 'value': 'dave'}]}),
 Vertex(id=40968432, label='person', properties={'name': [{'id': 'odzq6-oe3g0-4flx', 'value': 'frens'}]}),
 Edge(id='oe04e-oe3g0-4h79-pgg', source_id=40968432, label='likes', target_id=32992, properties={}),
 Edge(id='oe04e-oe3g0-4h79-pgg', source_id=40968432, label='likes', target_id=32992, properties={}))

Duplicate Vertices created by readme sample code

Hi Dave,
When I'm running against tinkergraph I get duplicate vertices with the last example when starting with a clean database. See below for code, console output and reply from server using http://localhost:8182/?gremlin=g.V()

Also Id seems to be created as a property, which doesn't look right.
Will try sample on titan too and let you know.

Other than than that pretty cool library and better than gremlin console if we can solve the duplicates.
Cheers
Peter

Code

client = gremlinrestclient.GremlinRestClient()
graph = gremlinrestclient.TinkerGraph()
d = {"name": "dave", "label": "person"}
coll = graph.create(d)
dave, = coll.vertices  # Unpack tuple of length 1
print(dave)
print(coll)
coll = graph.create(
   {"name": "python", "label": "lang"},
   (dave, "LIKES", 0, {'weight': 1}))
print(coll)
resp = client.execute("g.V()")
print(resp)

Console output

Response(status_code=200,
data=[
  {
    u'properties': {
      u'name': [
        {
          u'id': 1,
          u'value': u'dave'
        }
      ]
    },
    u'type': u'vertex',
    u'id': 0,
    u'label': u'person'
  },
  {
    u'properties': {
      u'name': [
        {
          u'id': 3,
          u'value': [
            {
              u'id': 1,
              u'value': u'dave'
            }
          ]
        }
      ]
    },
    u'type': u'vertex',
    u'id': 2,
    u'label': u'person'
  },
  {
    u'properties': {
      u'name': [
        {
          u'id': 5,
          u'value': u'python'
        }
      ]
    },
    u'type': u'vertex',
    u'id': 4,
    u'label': u'lang'
  }
],
message={

},
metadata=u'')

Reply from server

{
  "requestId": "2d571957-c321-408c-b2b1-765c67abf2b1",
  "status": {
    "message": "",
    "code": 200,
    "attributes": {

    }
  },
  "result": {
    "data": [
      {
        "id": 0,
        "label": "person",
        "type": "vertex",
        "properties": {
          "name": [
            {
              "id": 1,
              "value": "dave"
            }
          ]
        }
      },
      {
        "id": 2,
        "label": "person",
        "type": "vertex",
        "properties": {
          "name": [
            {
              "id": 3,
              "value": [
                {
                  "id": 1,
                  "value": "dave"
                }
              ]
            }
          ]
        }
      },
      {
        "id": 4,
        "label": "lang",
        "type": "vertex",
        "properties": {
          "name": [
            {
              "id": 5,
              "value": "python"
            }
          ]
        }
      }
    ],
    "meta": {

    }
  }
}

Create a node with an attribute value as List

I have certain attributes in my dictionary whose value a list of string values, but I am unable to add those as an attribute in my graph.

a= {"name":"package.json", "label":"package", "used_in":["A","B","C"]}
>>> a
{'used_in': ['A', 'B', 'C'], 'name': 'package.json', 'label': 'package'}
>>> graph.create(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/graph.py", line 182, in create
    return self._create(script, bindings)
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/graph.py", line 185, in _create
    resp = self.execute(script, bindings=bindings)
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/client.py", line 40, in execute
    resp = self._post(self._url, json.dumps(payload))
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/client.py", line 59, in _post
    raise GremlinServerError(resp.status_code, msg)
gremlinrestclient.exceptions.GremlinServerError: Code [500]: SERVER_ERROR. A general server error occurred that prevented the request from being processed..

Error encountered evaluating script: v18 = graph.addVertex(label, p0, 'used_in', p1, 'name', p2, );[[v18], []];

gremlin script does not work unless graph is set to TinkerGraph, Titan....

Hi,
I tried running the following snippet.

`>>> import gremlinrestclient

client = gremlinrestclient.GremlinRestClient()
resp = client.execute(
... "graph.addVertex(label, p1, 'name', p2)",
... bindings={"p1": "person", "p2": "dave"})
resp
Response(status_code=200, data=[{u'properties': {u'name': [{u'id': 226, u'value': u'dave'}]}, u'type': u'vertex', u'id': 225, u'label': u'person'}], message={}, metadata=u'')`

But this only works for me if I set graph variable to TinkerGraph.open()

>>> resp = client.execute( ... "graph = TinkerGraph.open(); graph.addVertex(label, p1, 'name', p2)", ... bindings={"p1": "person", "p2": "dave"})

And this is same for remaining functions.

Creating a Edge

Hi Dave,
I am trying to create a edge but the weight property is not working. Even if I specify the weight its creating a edge without the property.
I used your below example

>>> d = {"name": "dave", "label": "person"}
>>> p = {"name": "python", "label": "lang"}
>>> e = (d, "LIKES", p, {'weight': 1})
>>> graph.create(e)

I traced the gremlin query which was being generated. You can see the weight property is missing.

{"gremlin": "v0 = graph.addVertex(label, p0, 'name', p1, );v1 = graph.addVertex(label, p2, 'name', p3, );e0 = v1.addEdge('LIKES', v0, );graph.tx().commit();[[v0,v1], [e0]];", "bindings": {"p2": "lang", "p3": "python", "p0": "person", "p1": "dave"}, "language": "gremlin-groovy"}

Thanks,

Duplicate vertices

Maybe the same issue as #2, but I see some unexpected duplication in:

p = {"name": "python", "label": "lang"}
d = {"name": "dave", "label": "person"}
f = {"name": "frens", "label": "person"}

coll = graph.create(
    (d, 'likes', p, {}),
    (f, 'likes', p, {})
)
pprint(coll.vertices + coll.edges)

I would expect both Dave and Frens to like python. But for some reason, two vertices are created with the name 'python'; one without the 'lang' label.

(Vertex(id=49264, label='person', properties={'name': [{'id': 'ff2-120g-4flx', 'value': 'dave'}]}),
 Vertex(id=8344, label='lang', properties={'name': [{'id': '1zn-6fs-4flx', 'value': 'python'}]}),
 Vertex(id=40964336, label='person', properties={'name': [{'id': 'ody5a-oe0a8-4flx', 'value': 'frens'}]}),
 Vertex(id=53360, label='vertex', properties={'name': [{'id': 'g7i-1568-4flx', 'value': 'python'}]}),
 Edge(id='odyji-oe0a8-4h79-1568', source_id=40964336, label='likes', target_id=53360, properties={}),
 Edge(id='odyji-oe0a8-4h79-1568', source_id=40964336, label='likes', target_id=53360, properties={}))

Maybe this is the expected behavior, if so, consider this a 'improvement request' or at least a 'documentation request' ;)

P.S. see #4 for a related issue also exposed by the code above regarding the edges.

Create node with an attribute value None

I have certain attributes in my dictionary whose value is None, but I am unable to add those as an attribute in my graph
Example

>>>a= {"name":"package.json", "label":"package", "source":None}
>>>graph.create(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/graph.py", line 182, in create
    return self._create(script, bindings)
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/graph.py", line 185, in _create
    resp = self.execute(script, bindings=bindings)
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/client.py", line 40, in execute
    resp = self._post(self._url, json.dumps(payload))
  File "/usr/lib/python2.7/site-packages/gremlinrestclient/client.py", line 59, in _post
    raise GremlinServerError(resp.status_code, msg)
gremlinrestclient.exceptions.GremlinServerError: Code [500]: SERVER_ERROR. A general server error occurred that prevented the request from being processed..

Error encountered evaluating script: v16 = graph.addVertex(label, p0, 'source', p1, 'name', p2, );[[v16], []];

When I changed the source = "" it worked.

>>> a= {"name":"package.json", "label":"package", "source":""}
>>> graph.create(a)
Collection(vertices=(Vertex(id=16480, label=u'package', properties={u'source': [{u'id': u'4r0-cps-hdx', u'value': u''}], u'name': [{u'id': u'558-cps-1l1', u'value': u'package.json'}]}),), edges=())

Deleting vertex

Hi guys,

I'm currently struggling with trying to delete a vertex from my graph using gremlinrestclient. I tried executing queries as usual bot have no luck finding the right syntax. I tried g.V(123).remove(), g.V(123).delete() and various other notations but wasn't able to successfully delete a vertex from my graph.
Do you have any ideas on how to solve this problem?

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.