Git Product home page Git Product logo

ipython-cypher's Introduction

ipython-cypher

Author: Javier de la Rosa, http://versae.es

Introduces a %cypher (and %%cypher) magic for Neo4j in IPython. Inspired by Catherine Devlin's ipython-sql.

Connect to a graph database, using neo4jrestclient_ driver, then issue Cypher commands within IPython or IPython Notebook. See examples.

Install

As easy as usual:

pip install ipython-cypher

Usage

Inside IPython, load the extension:

%load_ext cypher

And then you are reay to go by using the %cypher line magic:

%cypher MATCH (a)-[]-(b) RETURN a, b

Some Cypher queries can be very long, in those cases the the cell magic, %%cypher comes in handy:

%%cypher
create
    // Nodes
    (Neo:Crew {name:'Neo'}),
    (Morpheus:Crew {name: 'Morpheus'}),
    (Trinity:Crew {name: 'Trinity'}),
    // Relationships
    (Neo)-[:KNOWS]->(Morpheus),
    (Neo)-[:LOVES]->(Trinity),

Note that by default ipython-cypher will connect to http://localhost:7474/db/data.

Queries results can be stored in a variable and then converted to a Pandas DataFrame:

results = %cypher MATCH (a)-[]-(b) RETURN a, b
results.get_dataframe()

Or to a NetworkX MultiDiGraph:

results.get_graph()

For more detailed descriptions, please visit the official documentation.

ipython-cypher's People

Contributors

bruth avatar crabhi avatar davebshow avatar iamjoeker avatar versae 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

Watchers

 avatar  avatar  avatar  avatar

ipython-cypher's Issues

Message `IPython.config` package has been deprecated

Great package for cypher magic.

After latest evolutions of ipython / jupyter you get the warning below:

/Users/xyz/anaconda/lib/python3.5/site-packages/IPython/config.py:13: ShimWarning: The `IPython.config` package has been deprecated. You should import from traitlets.config instead.
  "You should import from traitlets.config instead.", ShimWarning)
/Users/xyz/anaconda/lib/python3.5/site-packages/IPython/utils/traitlets.py:5: UserWarning: IPython.utils.traitlets has moved to a top-level traitlets package.
  warn("IPython.utils.traitlets has moved to a top-level traitlets package.")

draw and get_graph appear to be broken

Using the neo4j example data (Movie Graph), I get the following error:

res = cypher.run("match (n)-[r]-() return n, r")  # as per the documentation
res.get_graph()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/<snip>/lib/python3.5/site-packages/cypher/run.py", line 202, in get_graph
    labels=node['labels'])
TypeError: add_node() takes 2 positional arguments but 3 were given

similarly:

res = cypher.run("match (n)-[r]-() return n, r")  # as per the documentation
res.draw()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/<snip>/lib/python3.5/site-packages/cypher/run.py", line 268, in draw
    graph = self.get_graph(directed=directed)
  File "/home/<snip>/lib/python3.5/site-packages/cypher/run.py", line 202, in get_graph
    labels=node['labels'])
TypeError: add_node() takes 2 positional arguments but 3 were given

Perhaps line 201-202 in run.py could be replaced with:

graph.add_node(node['id'], properties=node['properties'], labels=node['labels'])

Error with get_graph() and networkx 2.0

I have found and error calling the function get_graph() with the latest version of ipython-cypher and networkx

The following notebook shows the error:

!pip install -U ipython-cypher==0.2.5
Collecting ipython-cypher==0.2.5
Collecting neo4jrestclient>=2.1.0 (from ipython-cypher==0.2.5)
Collecting ipython>=1.0 (from ipython-cypher==0.2.5)
  Using cached ipython-6.2.1-py3-none-any.whl
Collecting prettytable (from ipython-cypher==0.2.5)
Collecting requests>=2.1.0 (from neo4jrestclient>=2.1.0->ipython-cypher==0.2.5)
  Using cached requests-2.18.4-py2.py3-none-any.whl
Collecting decorator (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached decorator-4.2.1-py2.py3-none-any.whl
Collecting traitlets>=4.2 (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached traitlets-4.3.2-py2.py3-none-any.whl
Collecting pygments (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached Pygments-2.2.0-py2.py3-none-any.whl
Collecting pexpect; sys_platform != "win32" (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached pexpect-4.3.1-py2.py3-none-any.whl
Collecting simplegeneric>0.8 (from ipython>=1.0->ipython-cypher==0.2.5)
Collecting jedi>=0.10 (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached jedi-0.11.1-py2.py3-none-any.whl
Collecting prompt-toolkit<2.0.0,>=1.0.4 (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached prompt_toolkit-1.0.15-py3-none-any.whl
Collecting setuptools>=18.5 (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached setuptools-38.4.0-py2.py3-none-any.whl
Collecting pickleshare (from ipython>=1.0->ipython-cypher==0.2.5)
  Using cached pickleshare-0.7.4-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.1.0->neo4jrestclient>=2.1.0->ipython-cypher==0.2.5)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests>=2.1.0->neo4jrestclient>=2.1.0->ipython-cypher==0.2.5)
  Using cached idna-2.6-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests>=2.1.0->neo4jrestclient>=2.1.0->ipython-cypher==0.2.5)
  Using cached urllib3-1.22-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests>=2.1.0->neo4jrestclient>=2.1.0->ipython-cypher==0.2.5)
  Using cached certifi-2017.11.5-py2.py3-none-any.whl
Collecting ipython-genutils (from traitlets>=4.2->ipython>=1.0->ipython-cypher==0.2.5)
  Using cached ipython_genutils-0.2.0-py2.py3-none-any.whl
Collecting six (from traitlets>=4.2->ipython>=1.0->ipython-cypher==0.2.5)
  Using cached six-1.11.0-py2.py3-none-any.whl
Collecting ptyprocess>=0.5 (from pexpect; sys_platform != "win32"->ipython>=1.0->ipython-cypher==0.2.5)
  Using cached ptyprocess-0.5.2-py2.py3-none-any.whl
Collecting parso==0.1.1 (from jedi>=0.10->ipython>=1.0->ipython-cypher==0.2.5)
  Using cached parso-0.1.1-py2.py3-none-any.whl
Collecting wcwidth (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=1.0->ipython-cypher==0.2.5)
  Using cached wcwidth-0.1.7-py2.py3-none-any.whl
Installing collected packages: chardet, idna, urllib3, certifi, requests, neo4jrestclient, decorator, ipython-genutils, six, traitlets, pygments, ptyprocess, pexpect, simplegeneric, parso, jedi, wcwidth, prompt-toolkit, setuptools, pickleshare, ipython, prettytable, ipython-cypher
Successfully installed certifi-2017.11.5 chardet-3.0.4 decorator-4.2.1 idna-2.6 ipython-6.2.1 ipython-cypher-0.2.5 ipython-genutils-0.2.0 jedi-0.11.1 neo4jrestclient-2.1.1 parso-0.1.1 pexpect-4.3.1 pickleshare-0.7.4 prettytable-0.7.2 prompt-toolkit-1.0.15 ptyprocess-0.5.2 pygments-2.2.0 requests-2.18.4 setuptools-38.4.0 simplegeneric-0.8.1 six-1.11.0 traitlets-4.3.2 urllib3-1.22 wcwidth-0.1.7
�[33mYou are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.�[0m
%load_ext version_information
%load_ext cypher
%version_information networkx, cypher
SoftwareVersion
Python3.5.2 64bit [GCC 5.4.0 20160609]
IPython6.2.1
OSLinux 4.4.0 62 generic x86_64 with Ubuntu 16.04 xenial
networkx2.0
cypherThe 'cypher' distribution was not found and is required by the application
Tue Jan 16 16:20:12 2018 CET
from py2neo import Graph
graph = Graph()
graph.delete_all()
%cypher CREATE CONSTRAINT ON (c:Character) ASSERT c.name IS UNIQUE;
0 rows affected.
%%cypher 

LOAD CSV WITH HEADERS FROM "https://www.macalester.edu/~abeverid/data/stormofswords.csv" AS row
MERGE (src:Character {name: row.Source})
MERGE (tgt:Character {name: row.Target})
MERGE (src)-[r:INTERACTS]->(tgt)
ON CREATE SET r.weight = toInt(row.Weight)
352 relationships created.
107 labels added.
459 properties set.
107 nodes created.
results = %cypher MATCH p=(:Character)-[:INTERACTS]-(:Character) RETURN p
704 rows affected.
g = results.get_graph()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-f54f19835208> in <module>()
----> 1 g = results.get_graph()


~/.local/lib/python3.5/site-packages/cypher/run.py in get_graph(self, directed)
    202                 properties = copy.deepcopy(node['properties'])
    203                 properties['labels'] = node['labels']
--> 204                 graph.add_node(node['id'], properties)
    205             for rel in item['relationships']:
    206                 properties = copy.deepcopy(rel['properties'])


TypeError: add_node() takes 2 positional arguments but 3 were given

Cannot authenticate - SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)

Running Jupyter 1.0.0 with Neo4j 2.3.1 on Windows. When I run the following query:

%%cypher https://neo4j:password@localhost:7474/db/data
MATCH (person:Person)-[:LIKES]->(drink:Drink)
RETURN person.name, drink.name, drink.calories

I get the following error:

Format: (http|https)://username:password@hostname:port/db/name
---------------------------------------------------------------------------
SSLError                                  Traceback (most recent call last)
c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, **response_kw)
    558                                                   timeout=timeout_obj,
--> 559                                                   body=body, headers=headers)
    560 

c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, **httplib_request_kw)
    344         try:
--> 345             self._validate_conn(conn)
    346         except (SocketTimeout, BaseSSLError) as e:

c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\connectionpool.py in _validate_conn(self, conn)
    783         if not getattr(conn, 'sock', None):  # AppEngine might not have  `.sock`
--> 784             conn.connect()
    785 

c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\connection.py in connect(self)
    251                                     server_hostname=hostname,
--> 252                                     ssl_version=resolved_ssl_version)
    253 

c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir)
    304     if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
--> 305         return context.wrap_socket(sock, server_hostname=server_hostname)
    306 

c:\python34\Lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
    364                          server_hostname=server_hostname,
--> 365                          _context=self)
    366 

c:\python34\Lib\ssl.py in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context)
    582                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 583                     self.do_handshake()
    584 

c:\python34\Lib\ssl.py in do_handshake(self, block)
    809                 self.settimeout(None)
--> 810             self._sslobj.do_handshake()
    811         finally:

SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
c:\users\jan\venvs\jupyter\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    375                     retries=self.max_retries,
--> 376                     timeout=timeout
    377                 )

c:\users\jan\venvs\jupyter\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, **response_kw)
    587             release_conn = True
--> 588             raise SSLError(e)
    589 

SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
<ipython-input-14-bf5e4cff3852> in <module>()
----> 1 get_ipython().run_cell_magic('cypher', 'https://neo4j:password@localhost:7474/db/data', 'MATCH (person:Person)-[:LIKES]->(drink:Drink)\nRETURN person.name, drink.name, drink.calories')

c:\users\jan\venvs\jupyter\lib\site-packages\IPython\core\interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2291             magic_arg_s = self.var_expand(line, stack_depth)
   2292             with self.builtin_trap:
-> 2293                 result = fn(magic_arg_s, cell)
   2294             return result
   2295 

<decorator-gen-359> in execute(self, line, cell, local_ns)

c:\users\jan\venvs\jupyter\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

<decorator-gen-358> in execute(self, line, cell, local_ns)

c:\users\jan\venvs\jupyter\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

c:\users\jan\venvs\jupyter\lib\site-packages\cypher\magic.py in execute(self, line, cell, local_ns)
    101         user_ns.update(local_ns)
    102         parsed = parse("""{0}\n{1}""".format(line, cell), self)
--> 103         conn = Connection.get(parsed['as'] or parsed['uri'])
    104         first_word = parsed['cypher'].split(None, 1)[:1]
    105         if first_word and first_word[0].lower() == 'persist':

c:\users\jan\venvs\jupyter\lib\site-packages\cypher\connection.py in get(cls, descriptor)
     45                 cls.current = conn
     46             else:
---> 47                 cls.current = Connection(descriptor)
     48         if cls.current:
     49             return cls.current

c:\users\jan\venvs\jupyter\lib\site-packages\cypher\connection.py in __init__(self, connect_str, alias)
     24                 gdb = GraphDatabase(self.connections[connect_str])
     25             else:
---> 26                 gdb = GraphDatabase(connect_str)
     27                 alias = connect_str
     28         except:

c:\users\jan\venvs\jupyter\lib\site-packages\neo4jrestclient\client.py in __init__(self, url, username, password, cert_file, key_file)
     77         else:
     78             self.url = "%s/" % url
---> 79         response = Request(**self._auth).get(self.url)
     80         if response.status_code == 200:
     81             response_json = response.json()

c:\users\jan\venvs\jupyter\lib\site-packages\neo4jrestclient\request.py in get(self, url, headers)
     61         Returns the response object.
     62         """
---> 63         return self._request('GET', url, headers=headers)
     64 
     65     def post(self, url, data, headers=None):

c:\users\jan\venvs\jupyter\lib\site-packages\neo4jrestclient\request.py in _request(self, method, url, data, headers)
    196             response = getattr(session, method)(root_uri, headers=headers,
    197                                                 data=data, cert=cert,
--> 198                                                 auth=auth, verify=verify)
    199             if response.status_code == 401:
    200                 raise StatusException(401, "Authorization Required")

c:\users\jan\venvs\jupyter\lib\site-packages\requests\sessions.py in get(self, url, **kwargs)
    478 
    479         kwargs.setdefault('allow_redirects', True)
--> 480         return self.request('GET', url, **kwargs)
    481 
    482     def options(self, url, **kwargs):

c:\users\jan\venvs\jupyter\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    466         }
    467         send_kwargs.update(settings)
--> 468         resp = self.send(prep, **send_kwargs)
    469 
    470         return resp

c:\users\jan\venvs\jupyter\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    574 
    575         # Send the request
--> 576         r = adapter.send(request, **kwargs)
    577 
    578         # Total elapsed time of the request (approximately)

c:\users\jan\venvs\jupyter\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    445         except (_SSLError, _HTTPError) as e:
    446             if isinstance(e, _SSLError):
--> 447                 raise SSLError(e, request=request)
    448             elif isinstance(e, ReadTimeoutError):
    449                 raise ReadTimeout(e, request=request)

SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)

Internal server error 500 Server in trouble

Hi there,

Thx for your great work so far... looking forward to get all of it to work.
I installed Neo4J default, python default ipython notebook default but cannot get things to run...
I am on linux mint 17
python 2.7

notebook

In [1] : %load_ext cypher

In [2]: %config CypherMagic

CypherMagic options

-----------------

CypherMagic.auto_html=
Current: False
Return a D3 representation of the graph instead of regular result sets
CypherMagic.auto_limit=
Current: 0
Automatically limit the size of the returned result sets
CypherMagic.auto_networkx=
Current: False
Return Networkx MultiDiGraph instead of regular result sets
CypherMagic.auto_pandas=
Current: False
Return Pandas DataFrame instead of regular result sets
CypherMagic.data_contents=
Current: True
Bring extra data to render the results as a graph
CypherMagic.display_limit=
Current: 0
Automatically limit the number of rows displayed (full result set is still
stored)
CypherMagic.feedback=
Current: True
Print number of rows affected
CypherMagic.rest=
Current: False
Return full REST representations of objects inside the result sets
CypherMagic.short_errors=
Current: True
Don't display the full traceback on Neo4j errors
CypherMagic.style=
Current: u'DEFAULT'
Set the table printing style to any of prettytable's defined styles
(currently DEFAULT, MSWORD_FRIENDLY, PLAIN_COLUMNS, RANDOM)

basically as soon as i try to do someting in ipython i get the error 500 error

So

In [3]: %%cypher http://localhost:7474/db/data
match (n) return n limit 1

I get error:

Code [500]: Internal Server Error. Server got itself in trouble.
Element not found

/usr/lib/pymodules/python2.7/matplotlib/init.py:817: UserWarning: svg.embed_char_paths is deprecated and replaced with svg.fonttype; please use the latter.
warnings.warn(self.msg_depr % (key, alt))
/usr/lib/pymodules/python2.7/matplotlib/init.py:817: UserWarning: savefig.extension is deprecated and replaced with savefig.format; please use the latter.
warnings.warn(self.msg_depr % (key, alt))

any suggestions?

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.