forked from zhen-liang/stackexchange
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
2659 lines (2232 loc) · 87.6 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division, unicode_literals
import base64
from io import StringIO
import re
from warnings import warn
import webbrowser
from py2neo import __version__
from py2neo.error import BindError, GraphError, JoinError
from py2neo.packages.httpstream import http, ClientError, ServerError, \
Resource as _Resource, ResourceTemplate as _ResourceTemplate
from py2neo.packages.httpstream.http import JSONResponse, user_agent
from py2neo.packages.httpstream.numbers import NOT_FOUND
from py2neo.packages.httpstream.packages.urimagic import URI
from py2neo.types import cast_property
from py2neo.util import is_collection, is_integer, round_robin, ustr, version_tuple, \
raise_from, xstr, ThreadLocalWeakValueDictionary
__all__ = ["Graph", "Node", "Relationship", "Path", "NodePointer", "Rel", "Rev", "Subgraph",
"ServiceRoot", "PropertySet", "LabelSet", "PropertyContainer",
"authenticate", "rewrite", "ServerPlugin", "UnmanagedExtension",
"Service", "Resource", "ResourceTemplate"]
DEFAULT_SCHEME = "http"
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 7474
DEFAULT_HOST_PORT = "{0}:{1}".format(DEFAULT_HOST, DEFAULT_PORT)
PRODUCT = ("py2neo", __version__)
NON_ALPHA_NUM = re.compile("[^0-9A-Za-z_]")
SIMPLE_NAME = re.compile(r"[A-Za-z_][0-9A-Za-z_]*")
http.default_encoding = "UTF-8"
_headers = {
None: [
("User-Agent", user_agent(PRODUCT)),
("X-Stream", "true"),
],
}
_http_rewrites = {}
def _add_header(key, value, host_port=None):
""" Add an HTTP header to be sent with all requests if no `host_port`
is provided or only to those matching the value supplied otherwise.
"""
if host_port in _headers:
_headers[host_port].append((key, value))
else:
_headers[host_port] = [(key, value)]
def _get_headers(host_port):
"""Fetch all HTTP headers relevant to the `host_port` provided.
"""
uri_headers = {}
for n, headers in _headers.items():
if n is None or n == host_port:
uri_headers.update(headers)
return uri_headers
def authenticate(host_port, user_name, password):
""" Set HTTP basic authentication values for specified `host_port`. The
code below shows a simple example::
from py2neo import authenticate, Graph
# set up authentication parameters
authenticate("camelot:7474", "arthur", "excalibur")
# connect to authenticated graph database
graph = Graph("http://camelot:7474/db/data/")
Note: a `host_port` can be either a server name or a server name and port
number but must match exactly that used within the Graph
URI.
:arg host_port: the host and optional port requiring authentication
(e.g. "bigserver", "camelot:7474")
:arg user_name: the user name to authenticate as
:arg password: the password
"""
credentials = (user_name + ":" + password).encode("UTF-8")
value = "Basic " + base64.b64encode(credentials).decode("ASCII")
_add_header("Authorization", value, host_port=host_port)
def rewrite(from_scheme_host_port, to_scheme_host_port):
""" Automatically rewrite all URIs directed to the scheme, host and port
specified in `from_scheme_host_port` to that specified in
`to_scheme_host_port`.
As an example::
from py2neo import rewrite
# implicitly convert all URIs beginning with <http://localhost:7474>
# to instead use <https://dbserver:9999>
rewrite(("http", "localhost", 7474), ("https", "dbserver", 9999))
If `to_scheme_host_port` is :py:const:`None` then any rewrite rule for
`from_scheme_host_port` is removed.
This facility is primarily intended for use by database servers behind
proxies which are unaware of their externally visible network address.
"""
global _http_rewrites
if to_scheme_host_port is None:
try:
del _http_rewrites[from_scheme_host_port]
except KeyError:
pass
else:
_http_rewrites[from_scheme_host_port] = to_scheme_host_port
class Resource(_Resource):
""" Base class for all local resources mapped to remote counterparts.
"""
#: The class of error raised by failure responses from this resource.
error_class = GraphError
def __init__(self, uri, metadata=None):
uri = URI(uri)
scheme_host_port = (uri.scheme, uri.host, uri.port)
if scheme_host_port in _http_rewrites:
scheme_host_port = _http_rewrites[scheme_host_port]
# This is fine - it's all my code anyway...
uri._URI__set_scheme(scheme_host_port[0])
uri._URI__set_authority("{0}:{1}".format(scheme_host_port[1],
scheme_host_port[2]))
if uri.user_info:
authenticate(uri.host_port, *uri.user_info.partition(":")[0::2])
self._resource = _Resource.__init__(self, uri)
#self._subresources = {}
self.__headers = _get_headers(self.__uri__.host_port)
self.__base = super(Resource, self)
if metadata is None:
self.__initial_metadata = None
else:
self.__initial_metadata = dict(metadata)
self.__last_get_response = None
uri = uri.string
service_root_uri = uri[:uri.find("/", uri.find("//") + 2)] + "/"
if service_root_uri == uri:
self.__service_root = self
else:
self.__service_root = ServiceRoot(service_root_uri)
self.__ref = NotImplemented
@property
def graph(self):
""" The parent graph of this resource.
:rtype: :class:`.Graph`
"""
return self.__service_root.graph
@property
def headers(self):
""" The HTTP headers sent with this resource.
"""
return self.__headers
@property
def metadata(self):
""" Metadata received in the last HTTP response.
"""
if self.__last_get_response is None:
if self.__initial_metadata is not None:
return self.__initial_metadata
self.get()
return self.__last_get_response.content
@property
def ref(self):
""" The URI of this resource relative to its graph.
:rtype: string
"""
if self.__ref is NotImplemented:
self_uri = self.uri.string
graph_uri = self.graph.uri.string
self.__ref = self_uri[len(graph_uri):]
return self.__ref
@property
def service_root(self):
""" The root service associated with this resource.
:return: :class:`.ServiceRoot`
"""
return self.__service_root
def get(self, headers=None, redirect_limit=5, **kwargs):
""" Perform an HTTP GET to this resource.
:arg headers: Extra headers to pass in the request.
:arg redirect_limit: Maximum number of times to follow redirects.
:arg kwargs: Other arguments to pass to the underlying `httpstream` method.
:rtype: :class:`httpstream.Response`
:raises: :class:`py2neo.GraphError`
"""
headers = dict(headers or {})
headers.update(self.__headers)
kwargs.update(cache=True)
try:
response = self.__base.get(headers=headers, redirect_limit=redirect_limit, **kwargs)
except (ClientError, ServerError) as error:
if isinstance(error, JSONResponse):
content = dict(error.content, request=error.request, response=error)
else:
content = {}
message = content.pop("message", "HTTP GET returned response %s" % error.status_code)
raise_from(self.error_class(message, **content), error)
else:
self.__last_get_response = response
return response
def put(self, body=None, headers=None, **kwargs):
""" Perform an HTTP PUT to this resource.
:arg body: The payload of this request.
:arg headers: Extra headers to pass in the request.
:arg kwargs: Other arguments to pass to the underlying `httpstream` method.
:rtype: :class:`httpstream.Response`
:raises: :class:`py2neo.GraphError`
"""
headers = dict(headers or {})
headers.update(self.__headers)
try:
response = self.__base.put(body, headers, **kwargs)
except (ClientError, ServerError) as error:
if isinstance(error, JSONResponse):
content = dict(error.content, request=error.request, response=error)
else:
content = {}
message = content.pop("message", "HTTP PUT returned response %s" % error.status_code)
raise_from(self.error_class(message, **content), error)
else:
return response
def post(self, body=None, headers=None, **kwargs):
""" Perform an HTTP POST to this resource.
:arg body: The payload of this request.
:arg headers: Extra headers to pass in the request.
:arg kwargs: Other arguments to pass to the underlying `httpstream` method.
:rtype: :class:`httpstream.Response`
:raises: :class:`py2neo.GraphError`
"""
headers = dict(headers or {})
headers.update(self.__headers)
try:
response = self.__base.post(body, headers, **kwargs)
except (ClientError, ServerError) as error:
if isinstance(error, JSONResponse):
content = dict(error.content, request=error.request, response=error)
else:
content = {}
message = content.pop("message", "HTTP POST returned response %s" % error.status_code)
raise_from(self.error_class(message, **content), error)
else:
return response
def delete(self, headers=None, **kwargs):
""" Perform an HTTP DELETE to this resource.
:arg headers: Extra headers to pass in the request.
:arg kwargs: Other arguments to pass to the underlying `httpstream` method.
:rtype: :class:`httpstream.Response`
:raises: :class:`py2neo.GraphError`
"""
headers = dict(headers or {})
headers.update(self.__headers)
try:
response = self.__base.delete(headers, **kwargs)
except (ClientError, ServerError) as error:
if isinstance(error, JSONResponse):
content = dict(error.content, request=error.request, response=error)
else:
content = {}
message = content.pop("message", "HTTP DELETE returned response %s" % error.status_code)
raise_from(self.error_class(message, **content), error)
else:
return response
class ResourceTemplate(_ResourceTemplate):
""" A factory class for producing :class:`.Resource` objects dynamically
based on a template URI.
"""
#: The class of error raised by failure responses from resources produced by this template.
error_class = GraphError
def expand(self, **values):
""" Produce a resource instance by substituting values into the
stored template URI.
:arg values: A set of named values to plug into the template URI.
:rtype: :class:`.Resource`
"""
resource = Resource(self.uri_template.expand(**values))
resource.error_class = self.error_class
return resource
class Service(object):
""" Base class for objects that can be optionally bound to a remote resource. This
class is essentially a container for a :class:`.Resource` instance.
"""
#: The class of error raised by failure responses from the contained resource.
error_class = GraphError
__resource__ = None
def bind(self, uri, metadata=None):
""" Associate this «class.lower» with a remote resource.
:arg uri: The URI identifying the remote resource to which to bind.
:arg metadata: Dictionary of initial metadata to attach to the contained resource.
"""
if "{" in uri and "}" in uri:
if metadata:
raise ValueError("Initial metadata cannot be passed to a resource template")
self.__resource__ = ResourceTemplate(uri)
else:
self.__resource__ = Resource(uri, metadata)
self.__resource__.error_class = self.error_class
@property
def bound(self):
""" :const:`True` if this object is bound to a remote resource,
:const:`False` otherwise.
"""
return self.__resource__ is not None
@property
def graph(self):
""" The graph associated with the remote resource.
:rtype: :class:`.Graph`
"""
return self.service_root.graph
@property
def ref(self):
""" The URI of the remote resource relative to its graph.
:rtype: string
"""
return self.resource.ref
@property
def resource(self):
""" The remote resource to which this object is bound.
:rtype: :class:`.Resource`
:raises: :class:`py2neo.BindError`
"""
if self.bound:
return self.__resource__
else:
raise BindError("Local entity is not bound to a remote entity")
@property
def service_root(self):
""" The root service associated with the remote resource.
:return: :class:`.ServiceRoot`
"""
return self.resource.service_root
def unbind(self):
""" Detach this object from any remote resource.
"""
self.__resource__ = None
@property
def uri(self):
""" The full URI of the remote resource.
"""
resource = self.resource
try:
return resource.uri
except AttributeError:
return resource.uri_template
class ServiceRoot(object):
""" Wrapper for the base REST resource exposed by a running Neo4j
server, corresponding to the ``/`` URI.
"""
#: The URI for a Neo4j service with default configuration.
DEFAULT_URI = "{0}://{1}/".format(DEFAULT_SCHEME, DEFAULT_HOST_PORT)
__instances = {}
__graph = None
def __new__(cls, uri=None):
if uri is None:
uri = cls.DEFAULT_URI
if not uri.endswith("/"):
uri += "/"
try:
inst = cls.__instances[uri]
except KeyError:
inst = super(ServiceRoot, cls).__new__(cls)
inst.__resource = Resource(uri)
inst.__graph = None
cls.__instances[uri] = inst
return inst
@property
def graph(self):
""" The graph exposed by this service.
:rtype: :class:`.Graph`
"""
if self.__graph is None:
self.__graph = Graph(self.resource.metadata["data"])
return self.__graph
@property
def resource(self):
""" The contained resource object for this instance.
:rtype: :class:`py2neo.Resource`
"""
return self.__resource
@property
def uri(self):
""" The full URI of the contained resource.
"""
return self.resource.uri
class Graph(Service):
""" The `Graph` class provides a wrapper around the
`REST API <http://docs.neo4j.org/chunked/stable/rest-api.html>`_ exposed
by a running Neo4j database server and is identified by the base URI
of the graph database. If no URI is specified, a default value of
`http://localhost:7474/db/data/` is assumed; therefore, to connect to a
local server with default configuration, simply use::
>>> from py2neo import Graph
>>> graph = Graph()
An explicitly specified graph database URI can be passed to the constructor
as a string::
>>> other_graph = Graph("http://camelot:1138/db/data/")
If the database server is behind a proxy that requires HTTP authorisation,
the relevant criteria can also be specified within the URI::
>>> secure_graph = Graph("http://arthur:excalibur@camelot:1138/db/data/")
Once obtained, the `Graph` instance provides direct or indirect access
to most of the functionality available within py2neo.
"""
__instances = {}
__batch = None
__cypher = None
__legacy = None
__schema = None
__node_labels = None
__relationship_types = None
# Auto-sync will be removed in 2.1
auto_sync_properties = False
@staticmethod
def cast(obj):
""" Cast an general Python object to a graph-specific entity,
such as a :class:`.Node` or a :class:`.Relationship`.
"""
if obj is None:
return None
elif isinstance(obj, (Node, NodePointer, Path, Rel, Relationship, Rev, Subgraph)):
return obj
elif isinstance(obj, dict):
return Node.cast(obj)
elif isinstance(obj, tuple):
return Relationship.cast(obj)
else:
raise TypeError(obj)
def __new__(cls, uri=None):
if uri is None:
uri = ServiceRoot().graph.uri.string
if not uri.endswith("/"):
uri += "/"
key = (cls, uri)
try:
inst = cls.__instances[key]
except KeyError:
inst = super(Graph, cls).__new__(cls)
inst.bind(uri)
cls.__instances[key] = inst
return inst
def __repr__(self):
return "<Graph uri=%r>" % self.uri.string
def __hash__(self):
return hash(self.uri)
def __len__(self):
return self.size
def __bool__(self):
return True
def __nonzero__(self):
return True
def __contains__(self, entity):
return entity.bound and entity.uri.string.startswith(entity.uri.string)
@property
def batch(self):
""" A :class:`py2neo.batch.BatchResource` instance attached to this
graph. This resource exposes methods for submitting iterable
collections of :class:`py2neo.batch.Job` objects to the server and
will often be used indirectly via classes such as
:class:`py2neo.batch.PullBatch` or :class:`py2neo.batch.PushBatch`.
:rtype: :class:`py2neo.cypher.BatchResource`
"""
if self.__batch is None:
from py2neo.batch import BatchResource
self.__batch = BatchResource(self.resource.metadata["batch"])
return self.__batch
@property
def cypher(self):
""" The Cypher execution resource for this graph providing access to
all Cypher functionality for the underlying database, both simple
and transactional.
::
>>> from py2neo import Graph
>>> graph = Graph()
>>> graph.cypher.execute("CREATE (a:Person {name:{N}})", {"N": "Alice"})
:rtype: :class:`py2neo.cypher.CypherResource`
"""
if self.__cypher is None:
from py2neo.cypher import CypherResource
metadata = self.resource.metadata
self.__cypher = CypherResource(metadata["cypher"], metadata.get("transaction"))
return self.__cypher
def create(self, *entities):
""" Create one or more remote nodes, relationships or paths in a
single transaction. The entity values provided must be either
existing entity objects (such as nodes or relationships) or values
that can be cast to them.
For example, to create a remote node from a local :class:`Node` object::
from py2neo import Graph, Node
graph = Graph()
alice = Node("Person", name="Alice")
graph.create(alice)
Then, create a second node and a relationship connecting both nodes::
german, speaks = graph.create({"name": "German"}, (alice, "SPEAKS", 0))
This second example shows how :class:`dict` and :class:`tuple` objects
can also be used to create nodes and relationships respectively. The
zero value in the relationship tuple references the zeroth item created
within that transaction, i.e. the "German" node.
.. note::
If an object is passed to this method that is already bound to
a remote entity, that argument will be ignored and nothing will
be created.
:arg entities: One or more existing graph entities or values that
can be cast to entities.
:return: A tuple of all entities created (or ignored) of the same
length and order as the arguments passed in.
:rtype: tuple
.. warning::
This method will *always* return a tuple, even when creating
only a single entity. To automatically unpack to a single
item, append a trailing comma to the variable name on the
left of the assignment operation.
"""
from py2neo.cypher.create import CreateStatement
statement = CreateStatement(self)
for entity in entities:
statement.create(entity)
return statement.execute()
def create_unique(self, *entities):
""" Create one or more unique paths or relationships in a single
transaction. This is similar to :meth:`create` but uses a Cypher
`CREATE UNIQUE <http://docs.neo4j.org/chunked/stable/query-create-unique.html>`_
clause to ensure that only relationships that do not already exist are created.
"""
from py2neo.cypher.create import CreateStatement
statement = CreateStatement(self)
for entity in entities:
statement.create_unique(entity)
return statement.execute()
def delete(self, *entities):
""" Delete one or more nodes, relationships and/or paths.
"""
from py2neo.cypher.delete import DeleteStatement
statement = DeleteStatement(self)
for entity in entities:
statement.delete(entity)
return statement.execute()
def delete_all(self):
""" Delete all nodes and relationships from the graph.
.. warning::
This method will permanently remove **all** nodes and relationships
from the graph and cannot be undone.
"""
from py2neo.batch import WriteBatch, CypherJob
batch = WriteBatch(self)
batch.append(CypherJob("START r=rel(*) DELETE r"))
batch.append(CypherJob("START n=node(*) DELETE n"))
batch.run()
def find(self, label, property_key=None, property_value=None, limit=None):
""" Iterate through a set of labelled nodes, optionally filtering
by property key and value
"""
if not label:
raise ValueError("Empty label")
from py2neo.cypher.lang import cypher_escape
if property_key is None:
statement = "MATCH (n:%s) RETURN n,labels(n)" % cypher_escape(label)
parameters = {}
else:
statement = "MATCH (n:%s {%s:{V}}) RETURN n,labels(n)" % (
cypher_escape(label), cypher_escape(property_key))
parameters = {"V": property_value}
if limit:
statement += " LIMIT %s" % limit
response = self.cypher.post(statement, parameters)
for record in response.content["data"]:
dehydrated = record[0]
dehydrated.setdefault("metadata", {})["labels"] = record[1]
yield self.hydrate(dehydrated)
response.close()
def find_one(self, label, property_key=None, property_value=None):
""" Find a single node by label and optional property. This method is
intended to be used with a unique constraint and does not fail if more
than one matching node is found.
"""
for node in self.find(label, property_key, property_value, limit=1):
return node
def hydrate(self, data):
""" Hydrate a dictionary of data to produce a :class:`.Node`,
:class:`.Relationship` or other graph object instance. The
data structure and values expected are those produced by the
`REST API <http://neo4j.com/docs/stable/rest-api.html>`__.
:arg data: dictionary of data to hydrate
"""
if isinstance(data, dict):
if "self" in data:
if "type" in data:
return Relationship.hydrate(data)
else:
return Node.hydrate(data)
elif "nodes" in data and "relationships" in data:
if "directions" not in data:
from py2neo.batch import Job, Target
node_uris = data["nodes"]
relationship_uris = data["relationships"]
jobs = [Job("GET", Target(uri)) for uri in relationship_uris]
directions = []
for i, result in enumerate(self.batch.submit(jobs)):
rel_data = result.content
start = rel_data["start"]
end = rel_data["end"]
if start == node_uris[i] and end == node_uris[i + 1]:
directions.append("->")
else:
directions.append("<-")
data["directions"] = directions
return Path.hydrate(data)
elif "columns" in data and "data" in data:
from py2neo.cypher import RecordList
return RecordList.hydrate(data, self)
elif "neo4j_version" in data:
return self
elif "exception" in data and "stacktrace" in data:
message = data.pop("message", "The server returned an error")
raise GraphError(message, **data)
else:
warn("Map literals returned over the Neo4j REST interface are ambiguous "
"and may be hydrated as graph objects")
return data
elif is_collection(data):
return type(data)(map(self.hydrate, data))
else:
return data
@property
def legacy(self):
""" Sub-resource providing access to legacy functionality.
:rtype: :class:`py2neo.legacy.LegacyResource`
"""
if self.__legacy is None:
from py2neo.legacy import LegacyResource
self.__legacy = LegacyResource(self.uri.string)
return self.__legacy
def match(self, start_node=None, rel_type=None, end_node=None, bidirectional=False, limit=None):
""" Return an iterator for all relationships matching the
specified criteria.
For example, to find all of Alice's friends::
for rel in graph.match(start_node=alice, rel_type="FRIEND"):
print(rel.end_node.properties["name"])
:arg start_node: :attr:`~py2neo.Node.bound` start :class:`~py2neo.Node` to match or
:const:`None` if any
:arg rel_type: type of relationships to match or :const:`None` if any
:arg end_node: :attr:`~py2neo.Node.bound` end :class:`~py2neo.Node` to match or
:const:`None` if any
:arg bidirectional: :const:`True` if reversed relationships should also be included
:arg limit: maximum number of relationships to match or :const:`None` if no limit
:return: matching relationships
:rtype: generator
"""
if start_node is None and end_node is None:
query = "START a=node(*)"
params = {}
elif end_node is None:
query = "START a=node({A})"
start_node = Node.cast(start_node)
if not start_node.bound:
raise TypeError("Nodes for relationship match end points must be bound")
params = {"A": start_node}
elif start_node is None:
query = "START b=node({B})"
end_node = Node.cast(end_node)
if not end_node.bound:
raise TypeError("Nodes for relationship match end points must be bound")
params = {"B": end_node}
else:
query = "START a=node({A}),b=node({B})"
start_node = Node.cast(start_node)
end_node = Node.cast(end_node)
if not start_node.bound or not end_node.bound:
raise TypeError("Nodes for relationship match end points must be bound")
params = {"A": start_node, "B": end_node}
if rel_type is None:
rel_clause = ""
elif is_collection(rel_type):
separator = "|:" if self.neo4j_version >= (2, 0, 0) else "|"
rel_clause = ":" + separator.join("`{0}`".format(_)
for _ in rel_type)
else:
rel_clause = ":`{0}`".format(rel_type)
if bidirectional:
query += " MATCH (a)-[r" + rel_clause + "]-(b) RETURN r"
else:
query += " MATCH (a)-[r" + rel_clause + "]->(b) RETURN r"
if limit is not None:
query += " LIMIT {0}".format(int(limit))
results = self.cypher.stream(query, params)
try:
for result in results:
yield result.r
finally:
results.close()
def match_one(self, start_node=None, rel_type=None, end_node=None, bidirectional=False):
""" Return a single relationship matching the
specified criteria. See :meth:`~py2neo.Graph.match` for
argument details.
"""
rels = list(self.match(start_node, rel_type, end_node,
bidirectional, 1))
if rels:
return rels[0]
else:
return None
def merge(self, label, property_key=None, property_value=None, limit=None):
""" Match or create a node by label and optional property and return
all matching nodes.
"""
if not label:
raise ValueError("Empty label")
from py2neo.cypher.lang import cypher_escape
if property_key is None:
statement = "MERGE (n:%s) RETURN n,labels(n)" % cypher_escape(label)
parameters = {}
else:
statement = "MERGE (n:%s {%s:{V}}) RETURN n,labels(n)" % (
cypher_escape(label), cypher_escape(property_key))
parameters = {"V": property_value}
if limit:
statement += " LIMIT %s" % limit
response = self.cypher.post(statement, parameters)
for record in response.content["data"]:
dehydrated = record[0]
dehydrated.setdefault("metadata", {})["labels"] = record[1]
yield self.hydrate(dehydrated)
response.close()
def merge_one(self, label, property_key=None, property_value=None):
""" Match or create a node by label and optional property and return a
single matching node. This method is intended to be used with a unique
constraint and does not fail if more than one matching node is found.
"""
for node in self.merge(label, property_key, property_value, limit=1):
return node
@property
def neo4j_version(self):
""" The database software version as a 4-tuple of (``int``, ``int``,
``int``, ``str``).
"""
return version_tuple(self.resource.metadata["neo4j_version"])
def node(self, id_):
""" Fetch a node by ID. This method creates an object representing the
remote node with the ID specified but fetches no data from the server.
For this reason, there is no guarantee that the entity returned
actually exists.
"""
resource = self.resource.resolve("node/%s" % id_)
uri_string = resource.uri.string
try:
return Node.cache[uri_string]
except KeyError:
data = {"self": uri_string}
return Node.cache.setdefault(uri_string, Node.hydrate(data))
@property
def node_labels(self):
""" The set of node labels currently defined within the graph.
"""
if not self.supports_node_labels:
raise NotImplementedError("Node labels not available for this Neo4j server version")
if self.__node_labels is None:
self.__node_labels = Resource(self.uri.string + "labels")
return frozenset(self.__node_labels.get().content)
def open_browser(self):
""" Open a page in the default system web browser pointing at
the Neo4j browser application for this graph.
"""
webbrowser.open(self.service_root.resource.uri.string)
@property
def order(self):
""" The number of nodes in this graph.
"""
return self.cypher.execute_one("START n=node(*) RETURN count(n)")
def pull(self, *entities):
""" Pull data to one or more entities from their remote counterparts.
"""
if entities:
from py2neo.batch.pull import PullBatch
batch = PullBatch(self)
for entity in entities:
batch.append(entity)
batch.pull()
def push(self, *entities):
""" Push data from one or more entities to their remote counterparts.
"""
if entities:
from py2neo.batch.push import PushBatch
batch = PushBatch(self)
for entity in entities:
batch.append(entity)
batch.push()
def relationship(self, id_):
""" Fetch a relationship by ID.
"""
resource = self.resource.resolve("relationship/" + str(id_))
uri_string = resource.uri.string
try:
return Relationship.cache[uri_string]
except KeyError:
try:
return Relationship.cache.setdefault(
uri_string, Relationship.hydrate(resource.get().content))
except ClientError:
raise ValueError("Relationship with ID %s not found" % id_)
@property
def relationship_types(self):
""" The set of relationship types currently defined within the graph.
"""
if self.__relationship_types is None:
self.__relationship_types = Resource(self.uri.string + "relationship/types")
return frozenset(self.__relationship_types.get().content)
@property
def schema(self):
""" The schema resource for this graph.
:rtype: :class:`SchemaResource <py2neo.schema.SchemaResource>`
"""
if self.__schema is None:
from py2neo.schema import SchemaResource
self.__schema = SchemaResource(self.uri.string + "schema")
return self.__schema
@property
def size(self):
""" The number of relationships in this graph.
"""
return self.cypher.execute_one("START r=rel(*) RETURN count(r)")
@property
def supports_cypher_transactions(self):
""" Indicates whether the server supports explicit Cypher transactions.
"""
return "transaction" in self.resource.metadata
@property
def supports_foreach_pipe(self):
""" Indicates whether the server supports pipe syntax for FOREACH.
"""
return self.neo4j_version >= (2, 0)
@property
def supports_node_labels(self):
""" Indicates whether the server supports node labels.
"""
return self.neo4j_version >= (2, 0)
@property
def supports_optional_match(self):
""" Indicates whether the server supports Cypher OPTIONAL MATCH
clauses.
"""
return self.neo4j_version >= (2, 0)
@property
def supports_schema_indexes(self):
""" Indicates whether the server supports schema indexes.
"""
return self.neo4j_version >= (2, 0)