Tutorials for using the NEO4J database in Python

Source: Internet
Author: User
Tags neo4j
A quick Rest example

Let's start with some basic knowledge. If you do not have a service api,neo4j you cannot support other languages. This interface provides a set of restful Web services based on the JSON message format and a comprehensive discovery mechanism. The quickest and easiest way to use this interface in use is by using curl:

$ Curl http://localhost:7474/db/data/{"extensions": {}, "node": "Http://localhost:7474/db/data/node", "Node_index": " Http://localhost:7474/db/data/index/node "," Relationship_index ":" http://localhost:7474/db/data/index/ Relationship "," Extensions_info ":" Http://localhost:7474/db/data/ext "," Relationship_types ":" http://localhost : 7474/db/data/relationship/types "," Batch ":" Http://localhost:7474/db/data/batch "," Cypher ":" http://localhost : 7474/db/data/cypher "," Transaction ":" Http://localhost:7474/db/data/transaction "," neo4j_version ":" 2.0.0-m03 "}

Returning a JSON object from this endpoint contains a set of resource names and cypher endpoints that can be found under the URI. The Cyper requests that are sent in the message payload are accepted and executed, and the results are returned in the HTTP response.

It is this rest API interface that enables the creation of various neo4j drivers that are now available. Py2neo provides a simple encapsulation of these rest resources, which enables Python application developers to use neo4j without regard to the underlying client-server protocol.

A simple application

To actually verify Py2neo, we will focus on building a simple address management system for storing names and email addresses. We naturally use nodes to emulate each individual entity, but it is to remember that NEO4J does not have a type concept. Types are inferred from the surrounding relationships and attributes.

The people in the following diagram appear in red, and the e-mail address nodes are displayed in blue. These are, of course, purely logical demo nodes, but the data itself is no different.

Our app will complete two features: Add new contact information and retrieve a complete list of contacts. To do this, we will create a person class wrapper py2neonodeobject, which gives us an implementation of the underlying processing and leaves the user-level functionality. The root node in is referred to as a fixed reference point, and we start along this point.

Let's look directly at the code. The following is a complete small application. This program allows you to add a new name to a command-line tool that connects to one or more email addresses and provides an easy way to display these connection information. Running without parameters is a display usage pattern, and this only dependency requires only a local unmodified neo4j instance (instance).

#!/usr/bin/env python#-*-coding:utf-8-*-from __future__ import print_function import sysfrom Py2neo import neo4j, nod E, rel graph_db = neo4j. Graphdatabaseservice () class Person (object): _root = Graph_db.get_or_create_indexed_node ("Reference", "Contacts", "Root") @classmethod def create (CLS, name, *emails): Person_node, _ = graph_db.create (Node (name=name), rel (c         Ls._root, "person", 0)) The for mail in Emails:graph_db.create (node (email=email), rel (cls._root, "email", 0), Rel (Person_node, "EMAIL", 0)) return person (person_node) @classmethod def get_all (CLS): return [person . end_node) for the person in Cls._root.match ("person")] def __init__ (self, node): Self._node = node Def __str __ (self): return self.name + "\ n" + "\ n". Join ("<{0}>". Format (email) for e-mail in self.emails) @proper Ty def name (self): return self._node["name"] @property def emails (self): return [rel.end_node["e-mail"] for rel In Self._node.match ("EMAIL")] if __name__ = = "__main__": If Len (SYS.ARGV) < 2:app = Sys.argv[0] Print ("U  Sage: {0} add
 
  
   
    
         [
  
    
     
   ...]". Format (APP) print ("{0} list". Format (APP)) Sys.exit () method = Sys.argv[1] If method = = "Add": Print (person  . Create (*sys.argv[2:])) Elif method = = "List": For person in Person.get_all (): Print (person) else:print ("Unknown Command ")
     
 
    
 

  
 

On line No. 09 is the first line of Py2neo code, which is used to create a Graphdatabaseservice object. With this, we can access most of the features that use NEO4J server. Optionally, a URI is passed to the constructor, although if nothing is provided, the default local parameters are used instead. This means that the following two lines are exactly equal:

graph_db = neo4j. Graphdatabaseservice () graph_db = neo4j. Graphdatabaseservice ("http://localhost:7474/db/data/")

Line 13th describes the invocation of Get_or_create_indexed_node, which provides a nice way to create a fixed reference point in a drawing. The traditional neo4j index allows nodes and relationships to be accessed through key-value pairs, where we use reference index instances with connected keywords and root values. At the first execution, a new node is created, and in subsequent executions, the node (that is, root) is reused (reused).

In line 17th, we see the recommended nodes and relationship abstractions, as well as the Create method that accepts and uses nodes and relationship abstractions. Any number of abstractions can be passed into this method, and entities are created in a single batch transformation and returned as a list in the order in which they are specified. Abstract nodes are represented by node functions with some attributes, whereas abstract relationships use the REL function to accept a starting node, a type, and a terminating node. In context, other nodes, relationship initiation and termination nodes may consolidate references to other nodes in other batches. In our example, we connect the root node to the newly created person node, or else as item 0 (item 0).


This time we meet on lines 24th and 38 in Match method [@Lesus Note: There is a problem with the Oschina code line number. Corresponds to lines 28th and 44 of this article]. It attempts to identify the relationship using a special set of conditions, and then returns them using the list. In these examples, this relationship matches the person relationship, starting with the root node and the email relationship to the given person node. Similar to cypher, it is used to query the scene that contains the match keyword.

Finally, it is important to note that the way in which the node properties are accessed in the code above is just one simple way. Py2neo overrides the standard Python __getitem__ and __setitem__ methods, with the square bracket identifier for easy access to any property. This can be seen on lines 34th and 38. [@Lesus Note: Corresponds to lines 39th and 44 of this article]

Summarize

There (lines 34 and 38) We did this, which shows how it's quick and easy to cobble together a neo4j application outside of the Java environment, and also shows how Py2neo is abstracting most of the heavy burden through the rest API. The example here does not address uniqueness, although functionally providing unique indexes and cyphercreate unique statements. Django developers may also want to consider a layer, such as Neomodel, which represents a Djangoesque orm-style layer on the Py2neo top level.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.