Skip to content

Instantly share code, notes, and snippets.

@peterneubauer
Created August 14, 2012 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterneubauer/3347559 to your computer and use it in GitHub Desktop.
Save peterneubauer/3347559 to your computer and use it in GitHub Desktop.
Python basic index search
from neo4j import GraphDatabase
# Create db
db = GraphDatabase('db')
with db.transaction:
noun_id = 1
#-----1-----------------
#first creating the index, reference node and storing it...
noun_index = db.node.indexes.create('noun_idx')
noun_ref = db.node()
noun_index['type']['noun_ref'] = noun_ref
#------2------------------
#then later I use the reference node to add some new nodes and make sure they are "connected to" the ref-node
noun = db.node(id=noun_id)
noun.INSTANCE_OF(noun_ref)
#------3-------------------
#however the next time I run the code and want to actually grab the reference
#node from the index like this....
noun_index = db.index().forNodes('noun_idx')
noun_ref = noun_index['type']['noun_ref'].single
#and then traverse the nouns connected to the reference node (code below in step #4)
#-----4-------------
for relationship in noun_ref.INSTANCE_OF:
noun = relationship.start
print noun
# Always shut down your database
db.shutdown()
@technige
Copy link

Just as an aside, there's a helper method in py2neo called get_or_create_indexed_node which can help reduce the amount of code required in this type of case:

from py2neo import neo4j

db = neo4j.GraphDatabaseService()

noun_id = 1
noun = db.get_node(noun_id)
# can create a new node attached to the index if one doesn't already exist
noun_ref = db.get_or_create_indexed_node("noun_idx", "type", "noun_ref")
# make the relationship
db.create((noun, "INSTANCE_OF", noun_ref))

for relationship in noun_ref.get_relationships(neo4j.Direction.BOTH, "INSTANCE_OF"):
    noun = relationship.start_node
    print noun

http://packages.python.org/py2neo/neo4j.html#py2neo.neo4j.GraphDatabaseService.get_or_create_indexed_node

Nige

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment