[PYTHON] [Neo4J] ④ Try to handle the graph structure with Cypher

A corner where you can try Neo4J for a long time.

If you master the recently opened query language Cypher for graph databases, you will be able to create and search graph structures. So let's get started with Cypher.

I tried using py2neo, which I put in the last time, as a companion. Installation via pip:

sudo pip install py2neo $ python -V Python 2.7.10

1) Batch processing with py2neo

A subtle non-DRY example (and it doesn't work) that was on the web was copied and corrected for the time being so that batch processing was possible:

test.py


from py2neo import Graph

graph = Graph("http://neo4j:yourpassword@:7474/db/data/")
statement = """
  MERGE (person:Person {name:{person_name}}) ON CREATE SET
    person.age = {person_age},
    person.sex = {person_sex}

  MERGE (pet:Pet {name:{pet_name}}) ON CREATE SET
    pet.type = {pet_type}

  MERGE (person)-[:owns]->(pet)

  RETURN person
  """

tx = graph.cypher.begin()

persons = [
    {'name': 'Homer', 'age': 32, 'sex': 'Male', 'pet_name': 'Buller', 'pet_type': 'Dog'},
    {'name': 'Lucy', 'age': 12, 'sex': 'Male', 'pet_name': 'Buller', 'pet_type': 'Dog'},
    {'name': 'Lucy', 'age': 12, 'sex': 'Male', 'pet_name': 'Betty', 'pet_type': 'Cat'}
]

for person in persons:
    print person
    tx.append(statement, {
      'person_name': person['name'],
      'person_age': person['age'],
      'person_sex': person['sex'],

      'pet_name': person['pet_name'],
      'pet_type': person['pet_type']
    })

tx.process()

tx.commit()

You can see the flow by extracting only the transaction part:

tx = graph.cypher.begin() tx.append(statement, { ... }) tx.process() tx.commit()

Also, if you master the cypher syntax MERGE ~ ON CREATE in the statement, it looks pretty good.

See the example of py2neo committing JSON below, which could be written differently. http://jexp.github.io/blog/html/load_json.html

2) Write a query on the command line.

Next, try playing with cypher from the command line (environment is Mac).

$ neo4j-shell
Unable to find any JVMs matching version "1.7".
Welcome to the Neo4j Shell! Enter 'help' for a list of commands
NOTE: Remote Neo4j graph database service 'shell' at port 1337

neo4j-sh (?)$ MATCH (p)-[:owns]-(pet) WHERE p.name = "Lucy" RETURN p, pet;
+------------------------------------------------------------------------------+
| p                                       | pet                                |
+------------------------------------------------------------------------------+
| Node[11]{name:"Lucy",age:12,sex:"Male"} | Node[12]{name:"Betty",type:"Cat"}  |
| Node[11]{name:"Lucy",age:12,sex:"Male"} | Node[10]{name:"Buller",type:"Dog"} |
+------------------------------------------------------------------------------+
2 rows
46 ms

Something was complained when neo4j-shell was launched, but I was able to make a query.

3) Execute a query on the browser and graph it

Run the same query in your browser:

MATCH (p)-[:owns]-(pet) WHERE p.name = "Lucy" RETURN p, pet;

Press the Graph button on the right and you'll see the graph screen you expected: http://localhost:7474/browser/ スクリーンショット 2015-11-14 19.52.40.png

4) cypher query cheat sheet, etc.

Below on the original site: http://neo4j.com/docs/stable/cypher-refcard/

I can't find a good introduction to Japanese on the web.

Hurry up and look forward to "study notes" with updates from time to time! http://qiita.com/Keech/items/6bd5b667e935a20be018

Let's do this at our own pace ^^;

Recommended Posts

[Neo4J] ④ Try to handle the graph structure with Cypher
Try to solve the fizzbuzz problem with Keras
Try to solve the man-machine chart with Python
How to try the friends-of-friends algorithm with pyfof
Try to solve the programming challenge book with python3
Try to visualize the room with Raspberry Pi, part 1
Try to get the contents of Word with Golang
Display / update the graph according to the input with PySimpleGui
Try to specify the axis with PyTorch's Softmax function
Try to factorial with recursion
Try to play with the uprobe that supports Systemtap directly
[pyqtgraph] Add region to the graph and link it with the graph region
Try to automate the operation of network devices with Python
Try to decipher the garbled attachment file name with Python
Try to extract the features of the sensor data with CNN
[Python] Try to graph from the image of Ring Fit [OCR]
Try to operate Facebook with Python
Try to solve the N Queens problem with SA of PyQUBO
Try to profile with ONNX Runtime
Try to introduce the theme to Pelican
Output the call graph with PyCallGraph
Cython to try in the shortest
Try blurring the image with opencv2
Try to output audio with M5STACK
The fastest way to try EfficientNet
Try to solve the shortest path with Python + NetworkX + social data
From "drawing" to "writing" the configuration diagram: Try drawing the AWS configuration diagram with Diagrams
The easiest way to try PyQtGraph
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
I tried with the top 100 PyPI packages> I tried to graph the packages installed on Python
Try to react only the carbon at the end of the chain with SMARTS
[TensorFlow / Keras] The road to assembling an RNN with your favorite structure
[Cloudian # 5] Try to list the objects stored in the bucket with Python (boto3)
Try to separate the background and moving object of the video with OpenCV
Try logging in to qiita with Python
[Python] Set the graph range with matplotlib
I want to handle the rhyme part1
Try to face the integration by parts
Try using the camera with Python's OpenCV
I want to handle the rhyme part3
Try to predict cherry blossoms with xgboost
Trying to handle SQLite3 with Python [Note]
Try converting to tidy data with pandas
Quickly try to visualize datasets with pandas
Python amateurs try to summarize the list ①
First YDK to try with Cisco IOS-XE
Try rewriting the file with the less command
Match the colorbar to the figure with matplotlib
Try to generate an image with aliasing
I want to handle the rhyme part2
I want to handle the rhyme part5
I want to handle the rhyme part4
The road to compiling to Python 3 with Thrift
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to solve the traveling salesman problem with a genetic algorithm (execution result)
A simple workaround for bots to try to post tweets with the same content
[Verification] Try to align the point cloud with the optimization function of pytorch Part 1
Try to use up the Raspberry Pi 2's 4-core CPU with Parallel Python
Try to make your own AWS-SDK with bash
Log in to the remote server with SSH