Tutorial on using the NEO4J database in Python _python

Source: Internet
Author: User
Tags curl neo4j

A quick example of rest

First look at some basic knowledge. You cannot support other languages without a service api,neo4j. This interface provides a set of restful Web services based on 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 the JSON object from this endpoint contains a set of resource names and cypher endpoints that can be found under the URI. Accept the routed Cyper request in the message payload and execute the queries, returning the results in the HTTP response.

It is this rest API interface that makes the various neo4j drivers that are already in place. Py2neo provides a simple encapsulation of these rest resources, which allows Python application developers to be comfortable with neo4j without having to consider the underlying client-server protocol.

A simple application

To actually validate Py2neo, we will focus on creating a simple Address book management system for storing names and e-mail addresses. We naturally use nodes to simulate each individual entity, but it is to be remembered that neo4j does not have a type concept. Types are inferred from the surrounding relationships and attributes.

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

Our application 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 allows us to have a low-level processing implementation and set aside user-level functionality. The root node in the above figure is a fixed reference point in the above diagram, and we start at this point.

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

#!/usr/bin/env python #-*-coding:utf-8-*-from __future__ import print_function import sys from Py2neo import Neo 4j, node, rel graph_db = neo4j. Graphdatabaseservice () class Person (object): _root = Graph_db.get_or_create_indexed_node ("Reference", "Contac
       Ts "," root "@classmethod def create (CLS, name, *emails): Person_node, _ = graph_db.create (Node (name=name), Rel (cls._root, "person", 0)) for e-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): RET urn [person (person.end_node) for person in cls._root.match (' person ')] def __init__ (self, node): Self._nod E = node def __str__ (self): return self.name + "\ n" + "\ n". Join ("<{0}>". Format (email) for email i N self.emails) @property def name (self): return self._node["name" @property def emails (self): return [rel.end_node["emails"] for rel in Self._node.match ("email")] if __name__ = = "__main__": If Len (sys . argv) < 2:app = Sys.argv[0] Print ("Usage: {0} add <name> <email> [<email> ...]". Format (APP) print ("{0} list". Format (APP)) Sys.exit () method = Sys.argv[1] If method = = "Add": Print (P Erson.create (*sys.argv[2:]) Elif method = = "List": For person in Person.get_all (): Print (person) Else:prin
 T ("Unknown command")

On line No. 09 is the first line of Py2neo code, 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 this constructor, although if nothing is provided, the default local parameter is used instead. That means 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 fixed reference points in a graphic. The traditional neo4j index allows nodes and relationships to be accessed through key value pairs, and in this code we use reference index instances with concatenated 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).

On line 17th, we see the recommended markup for node and relationship abstraction, and the Create method that accepts and uses nodes and relational 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, type, and terminating node. 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, otherwise it is the item 0 (item 0).


This time we'll meet on line 24th and 38 with the match method form and relationship [@Lesus Note: There is a problem with the number of Oschina lines. Corresponds to lines 28th and 44 of this article]. It attempts to identify relationships using a special set of criteria, and then returns them using lists (list). In these examples, the 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 scenes that contain the match keyword.

The last thing to note is that accessing node properties in the above code is just one of the easiest ways to do it. Py2neo overrides standard Python's __getitem__ and __setitem__ methods to facilitate access to any property through a square bracket identifier. 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, showing how quickly and easily a neo4j application was pieced out of the Java environment, and how Py2neo was abstracting most of the heavy burdens through the rest API. The example here does not address uniqueness, although functionally it provides a unique index and cyphercreate unique statement. Django developers may also want to consider a layer, such as Neomodel, that 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.