py2neo.database – Graph Databases 2020 py2neo 连接数据库Graph方式

py2neo.database – Graph Databases

The py2neo.database package contains classes and functions required to interact with a Neo4j server. For convenience, many of these classes are also exposed through the top-level package, py2neo.

The most useful of the classes provided here is the Graph class which represents a Neo4j graph database instance and provides access to a large portion of the most commonly used py2neo API.

To run a query against a local database is straightforward:

 >>> from py2neo import Graph
 >>> graph = Graph(password="password")
 >>> graph.run("UNWIND range(1, 3) AS n RETURN n, n * n as n_sq").to_table()
    n | n_sq
 -----|------
    1 |    1
    2 |    4
    3 |    9

Getting connected

The GraphService, Graph, and SystemGraph classes all accept an argument called profile plus individual keyword settings. Internally, these arguments are used to construct a ConnectionProfile object which holds these details.

The profile can either be a URI or a base ConnectionProfile object. The settings are individual overrides for the values within that, such as host or password. This override mechanism allows several ways of specifying the same information. For example, the three variants below are all equivalent:

 >>> from py2neo import Graph
 >>> graph_1 = Graph()
 >>> graph_2 = Graph(host="localhost")
 >>> graph_3 = Graph("bolt://localhost:7687")

Omitting the profile argument completely falls back to using the default ConnectionProfile. More on this, and other useful information, can be found in the documentation for that class.

URIs

The general format of a URI is <scheme>://[<user>[:<password>]@]<host>[:<port>]. Supported URI schemes are:

  • bolt - Bolt (unsecured)

  • bolt+s - Bolt (secured with full certificate checks)

  • bolt+ssc - Bolt (secured with no certificate checks)

  • http - HTTP (unsecured)

  • https - HTTP (secured with full certificate checks)

  • http+s - HTTP (secured with full certificate checks)

  • http+ssc - HTTP (secured with no certificate checks)

Note that py2neo does not support routing with a Neo4j causal cluster, so neo4j://... URIs are not available. For this functionality, please use the official Neo4j Driver for Python.

Individual settings

The full set of supported settings are:

KeywordDescriptionTypeDefault
schemeUse a specific URI schemestr'bolt'
secureUse a secure connection (TLS)boolFalse
verifyVerify the server certificate (if secure)boolTrue
hostDatabase server host namestr'localhost'
portDatabase server portint7687
addressColon-separated host and port stringstr'localhost:7687'
userUser to authenticate asstr'neo4j'
passwordPassword to use for authenticationstr'password'
authA 2-tuple of (user, password)tuple('neo4j', 'password')

GraphService objects

  • class py2neo.database.``GraphService(profile=None, **settings)[source]

    The GraphService class is the top-level accessor for an entire Neo4j graph database management system (DBMS). Within the py2neo object hierarchy, a GraphService contains one or more Graph objects in which data storage and retrieval activity chiefly occurs.An explicit URI can be passed to the constructor:>>> from py2neo import GraphService >>> gs = GraphService("bolt://camelot.example.com:7687")Alternatively, the default value of bolt://localhost:7687 is used:>>> default_gs = GraphService() >>> default_gs <GraphService uri='bolt://localhost:7687'>Note Some attributes of this class available in earlier versions of py2neo are no longer available, specifically kernel_start_time, primitive_counts, store_creation_time, store_file_sizes and store_id, along with the query_jmx method. This is due to a change in Neo4j 4.0 relating to how certain system metadata is exposed. Replacement functionality may be reintroduced in a future py2neo release.Changed in 2020.0: this class was formerly known as ‘Database’, but was renamed to avoid confusion with the concept of the same name introduced with the multi-database feature of Neo4j 4.0.iter(graph_service)Yield all named graphs.For Neo4j 4.0 and above, this yields the names returned by a SHOW DATABASES query. For earlier versions, this yields no entries, since the one and only graph in these versions is not named.New in version 2020.0.graph_service[name]Access a Graph by name.New in version 2020.0.**property configA dictionary of the configuration parameters used to configure Neo4j.>>> gs.config['dbms.connectors.default_advertised_address'] 'localhost'property connectorThe Connector providing communication for this graph service.New in version 2020.0.**property default_graphThe default Graph exposed by this graph service.classmethod forget_all()[source]Forget all cached GraphService details.property kernel_versionThe Version of Neo4j running.keys()[source]Return a list of all Graph names exposed by this graph service.New in version 2020.0.**property productThe product name.property profileThe ConnectionProfile for which this graph service is configured. This attribute is simply a shortcut for connector.profile.New in version 2020.0.**property system_graphThe SystemGraph exposed by this graph service.New in version 2020.0.**property uriThe URI to which this graph service is connected. This attribute is simply a shortcut for connector.profile.uri.

Graph objects

  • class py2neo.database.``Graph(profile=None, name=None, **settings)[source]

    The Graph class provides a handle to an individual named graph database exposed by a Neo4j graph database service.Connection details are provided using either a URI or a ConnectionProfile, plus individual settings, if required.The name argument allows selection of a graph database by name. When working with Neo4j 4.0 and above, this can be any name defined in the system catalogue, a full list of which can be obtained through the Cypher SHOW DATABASES command. Passing None here will select the default database, as defined on the server. For earlier versions of Neo4j, the name must be set to None.>>> from py2neo import Graph >>> sales = Graph("bolt+s://g.example.com:7687", name="sales") >>> sales.run("MATCH (c:Customer) RETURN c.name") c.name --------------- John Smith Amy Pond Rory WilliamsThe system graph, which is available in all 4.x+ product editions, can also be accessed via the SystemGraph class.>>> from py2neo import SystemGraph >>> sg = SystemGraph("bolt+s://g.example.com:7687") >>> sg.call("dbms.security.listUsers") username | roles | flags ----------|-------|------- neo4j | null | []In addition to the core connection details that can be passed to the constructor, the Graph class can accept several other settings:KeywordDescriptionTypeDefaultuser_agentUser agent to send for all connectionsstr(depends on URI scheme)max_connectionsThe maximum number of simultaneous connections permittedint40Once obtained, the Graph instance provides direct or indirect access to most of the functionality available within py2neo.auto()[source]Create a new auto-commit Transaction.New in version 2020.0.begin(autocommit=False)[source]Begin a new Transaction.Parametersautocommit – (deprecated) if True, the transaction will automatically commit after the first operationChanged in version 2020.0: the ‘autocommit’ argument is now deprecated. Use the ‘auto’ method instead.**property callAccessor for listing and calling procedures.This property contains a ProcedureLibrary object tied to this graph, which provides links to Cypher procedures in the underlying implementation.Calling a procedure requires only the regular Python function call syntax:>>> g = Graph() >>> g.call.dbms.components() name | versions | edition --------------|------------|----------- Neo4j Kernel | ['3.5.12'] | communityThe object returned from the call is a Cursor object, identical to that obtained from running a normal Cypher query, and can therefore be consumed in a similar way.Procedure names can alternatively be supplied as a string:>>> g.call["dbms.components"]() name | versions | edition --------------|------------|----------- Neo4j Kernel | ['3.5.12'] | communityUsing dir() or iter() on the call attribute will yield a list of available procedure names.New in version 2020.0.create(subgraph)[source]Run a create() operation within a Transaction.Parameterssubgraph – a Node, Relationship or other Subgraphdelete(subgraph)[source]Run a delete() operation within an autocommit Transaction. To delete only the relationships, use the separate() method.Note that only entities which are bound to corresponding remote entities though the graph and identity attributes will trigger a deletion.Parameterssubgraph – a Node, Relationship or other Subgraph objectdelete_all()[source]Delete all nodes and relationships from this Graph.Warning This method will permanently remove all nodes and relationships from the graph and cannot be undone.evaluate(cypher, parameters=None, kwparameters)[source]Run a evaluate() operation within an autocommit Transaction.Parameterscypher* – Cypher statementparameters – dictionary of parametersReturnsfirst value from the first record returned or None.exists(subgraph)[source]Run a exists() operation within an autocommit Transaction.Parameterssubgraph – a Node, Relationship or other Subgraph objectReturnsmatch(nodes=None*, r_type=None, limit=None)[source]Match and return all relationships with specific criteria.For example, to find all of Alice’s friends:for rel in graph.match((alice, ), r_type="FRIEND"): print(rel.end_node["name"])Parametersnodes – Sequence or Set of start and end nodes (None means any node); a Set implies a match in any directionr_type – type of relationships to match (None means any type)limit – maximum number of relationships to match (None means unlimited)match_one(nodes=None, r_type=None)[source]Match and return one relationship with specific criteria.Parametersnodes – Sequence or Set of start and end nodes (None means any node); a Set implies a match in any directionr_type – type of relationships to match (None means any type)merge(subgraph, label=None, property_keys*)[source]Run a merge() operation within an autocommit Transaction.The example code below shows a simple merge for a new relationship between two new nodes:>>> from py2neo import Graph, Node, Relationship >>> g = Graph() >>> a = Node("Person", name="Alice", age=33) >>> b = Node("Person", name="Bob", age=44) >>> KNOWS = Relationship.type("KNOWS") >>> g.merge(KNOWS(a, b), "Person", "name")Following on, we then create a third node (of a different type) to which both the original nodes connect:>>> c = Node("Company", name="ACME") >>> c.__primarylabel__ = "Company" >>> c.__primarykey__ = "name" >>> WORKS_FOR = Relationship.type("WORKS_FOR") >>> g.merge(WORKS_FOR(a, c) | WORKS_FOR(b, c))For details of how the merge algorithm works, see the merge() method. Note that this is different to a Cypher MERGE.Parameterssubgraph* – a Node, Relationship or other Subgraph objectlabel – label on which to match any existing nodesproperty_keys – property keys on which to match any existing nodesproperty* nameThe name of this graph.New in version 2020.0.**property nodesA NodeMatcher for this graph.This can be used to find nodes that match given criteria:>>> graph = Graph() >>> graph.nodes[1234] (_1234:Person {name: 'Alice'}) >>> graph.nodes.get(1234) (_1234:Person {name: 'Alice'}) >>> graph.nodes.match("Person", name="Alice").first() (_1234:Person {name: 'Alice'})Nodes can also be efficiently counted using this attribute:>>> len(graph.nodes) 55691 >>> len(graph.nodes.match("Person", age=33)) 12 ``play(work, args=None, kwargs=None)[source]Call a function representing a transactional unit of work.The function must always accept a Transaction object as its first argument. Additional arguments can be passed though the args and kwargs arguments of this method.Parameterswork – function containing the unit of workargs – sequence of additional positional arguments to pass into the functionkwargs – mapping of additional keyword arguments to pass into the functionNew in version 2020.0.pull(subgraph)[source]Pull data to one or more entities from their remote counterparts.Parameterssubgraph – the collection of nodes and relationships to pullpush(subgraph)[source]Push data from one or more entities to their remote counterparts.Parameterssubgraph – the collection of nodes and relationships to pushproperty relationshipsA RelationshipMatcher for this graph.This can be used to find relationships that match given criteria as well as efficiently count relationships.run(cypher, parameters=None, kwparameters)[source]Run a run() operation within an autocommit Transaction.Parameterscypher** – Cypher statement**parameters** – dictionary of parameters**kwparameters** – extra keyword parametersReturns`schema` = NoneThe Schema resource for this Graph.separate(subgraph)[source]Run a separate() operation within an autocommit Transaction.Note that only relationships which are bound to corresponding remote relationships though the graph and identity attributes will trigger a deletion.Parameterssubgraph – a Node, Relationship or other Subgraphservice = NoneThe GraphService to which this Graph belongs.

SystemGraph objects

  • class py2neo.database.``SystemGraph(profile=None, **settings)[source]

    A subclass of Graph that provides access to the system database for the remote DBMS. This is only available in Neo4j 4.0 and above.New in version 2020.0.

Schema objects

  • class py2neo.database.``Schema(graph)[source]

    The schema resource attached to a Graph instance.create_index(label, property_keys)[source]Create a schema index for a label and property key combination.create_uniqueness_constraint(label*, property_key)[source]Create a node uniqueness constraint for a given label and property key.While indexes support the use of composite keys, unique constraints may only be tied to a single property key.drop_index(label, property_keys)[source]Remove label index for a given property key.drop_uniqueness_constraint(label*, property_key)[source]Remove the node uniqueness constraint for a given label and property key.get_indexes(label)[source]Fetch a list of indexed property keys for a label.get_uniqueness_constraints(label)[source]Fetch a list of unique constraints for a label. Each constraint is the name of a single property key.property node_labelsThe set of node labels currently defined within the graph.property relationship_typesThe set of relationship types currently defined within the graph.

ProcedureLibrary objects

  • class py2neo.database.``ProcedureLibrary(graph)[source]

    Accessor for listing and calling procedures.This object is typically constructed and accessed via the Graph.call() attribute. See the documentation for that attribute for usage information.New in version 2020.0.

Procedure objects

  • class py2neo.database.``Procedure(graph, name)[source]

    Represents an individual procedure.New in version 2020.0.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值