SlideShare a Scribd company logo
1 of 16
Download to read offline
python-graph-lovestory Documentation
Release 0.99
Amirouche Boubekki
April 21, 2013
CONTENTS
1 Walkthrough 3
1.1 Blueprints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
i
ii
python-graph-lovestory Documentation, Release 0.99
Here you will find documentation about the component of my python graph lovestory, I hope you like it because I do.
CONTENTS 1
python-graph-lovestory Documentation, Release 0.99
2 CONTENTS
CHAPTER
ONE
WALKTHROUGH
There’s no direct to the matter of «Developping Web application using graph databases» tutorial instead you read the
following subject in order which introduce each library part of the stack each of which deal with specific matters and
as such complexities are introduced along way you discover the stack, so that you know all the good parts but also all
the bad parts before you start.
1.1 Blueprints
1.1.1 Kesako ?
Blueprints allows to use several graph database with the same API. It can be used to embed a graph database in your
Python program. If several process need to access the same database it’s not what you need. python-blueprints are
pyjnius powered bindings of Tinkerpop’s Java Blueprints.
1.1.2 Installation
There is no binary package for now so you may have some difficulties installing python-blueprints on Windows and
MacOS machines, but it’s possible.
Follow the cli dance:
mkvirtualenv --system-site-packages coolprojectname
pip install cython git+git://github.com/kivy/pyjnius.git blueprints
You are ready for some graph database awesomeness in Python.
1.1.3 Getting started with core API
The python-blueprints API is straightforward it’s basicly the Blueprints API in Python, if you know Neo4j’s python-
embedded the API is similar but not the same.
Create a graph
Creating a graph is just matter of knowing where to store the files and the backend you want to use, currently only
Neo4j and OrienDB are supported.
For the purpose of the tutorial, we will use /tmp/ as storage directory.
Using Neo4j:
3
python-graph-lovestory Documentation, Release 0.99
from printemps.core import Graph
graph = Graph(’neo4j’, ’/tmp/’)
Getting OrientDB running is very similar:
from printemps.core import Graph
graph = Graph(’orientdb’, ’local:/tmp/’)
A Wiki model
The following is exactly the same for both OrientDB and Neo4j. In order to make easier for everybody to under-
stand how graphs works, we will model a wiki, while we introduce the base API of any graph databases used with
printemps.core.
A wiki will be a set of pages which have several revisions.
Create and modify edge and vertex
To create a vertex just call Graph.create_vertex() method inside a transaction:
with graph.transaction():
wiki = graph.create_vertex()
There is no Vertex.save() method nor Edge.save(), the elements are automatically persisted if the transaction
succeed.
If you want to know the identifier of the wiki in the database to store it somewhere or learn it by hearth, you can use
Vertex.id(), Edge.id() does the same for edges.
Both vertex and edge work like a dictionary, you can set and get properties, they are persisted if you do it inside a
transaction, I don’t know what happens outside transactions. Let’s give a name and description to our wiki vertex:
with graph.transaction():
wiki[’title’] = ’Printemps Wiki’
wiki[’description’] = ’My first graph based wiki’
Keys are always strings, values can be:
• strings
• integers
• list of strings
• list of integers
We will see later how it can be done, it’s very natural for Python programmers.
Now we will create a page, a page will be vertex too:
with graph.transaction():
frontpage = graph.create_vertex()
frontpage[’title’] = ’Welcome to Printemps Wiki’
The page needs to be linked to wiki as a part of, for that matter there is a method Graph.create_edge(start,
label, end) than can be used like this:
4 Chapter 1. Walkthrough
python-graph-lovestory Documentation, Release 0.99
with graph.transaction():
partof = graph.edge(wiki, ’part of’, frontpage)
An edge has three important methods, that do actually nothing but return the value we are interested in, but since those
are not editable, you access them through methods:
• Edge.start() returns the vertex where the edge is starting, in the case of partof it’s wiki vertex
• Edge.end() returns the vertex where the edge is ending, in the case of partof it’s frontpage vertex
• Edge.label() returns the label of the edge, in the case of partof it’s the string ’part of’
In general, every object you think of is a vertex, but some times some «objects» are modeled as edges, those are links.
An object representing a link between two objects is an edge. If the link object involves more that two edges, then it
can be represented as an hyperedge.
Note: this is advanced topic you can skip it.
The idea behind the hyperedge is that a vertex can be linked to several other vertex using only one special edge the hy-
peredge, which means the edge starts with one vertex, and ends with several vertex. Here is an example representation
of an hyperedge:
1.1. Blueprints 5
python-graph-lovestory Documentation, Release 0.99
This can be modeled in a graph using only vertices and simple edges with an intermediate vertex which serves as a
hub for serveral edges that will link to the end vertices of the hyperedge. Here is the pattern illustrated:
6 Chapter 1. Walkthrough
python-graph-lovestory Documentation, Release 0.99
Hyperedges are not part of popular graphdbs as is, so you have to use the intermediate vertex pattern.
To sum up, link objects with more that two objects involved in the link are the exception among link objects and are
represented as vertex.
Navigation
Stay away with your motors, sails and emergency fire lighters, it’s just plain Python even though you can do it in boat
too, but this is not my issue at the present moment.
Before advancing any further, let’s sum up, we have a graph with two vertices, and one edge, it can be represented as
follow:
1.1. Blueprints 7
python-graph-lovestory Documentation, Release 0.99
Because we like the wiki so much we know its identifier by hearth and stored it in a variable named
wiki_identifier, we can retrieve the wiki vertex like so:
wiki = graph.vertex(wiki_identifier)
Vertices have two kinds of edges:
• Vertex.incomings(): a generator yielding edges that ends at this vertex, currently there is none on wiki
• Vertex.outgoings(): a generator yielding edges that starts at this vertex, currently there is only one.
To retrieve the frontpage we can use next function of wiki.outgoings() to rertrieve the first and only edge as
first hop and navigate to the index using Edge.end() as second hop:
link = next(wiki.outgoings())
frontpage = link.end()
We got back our frontpage vertex back, Ulysse himself wouldn’t believe it, it’s not the same object though.
More vertices and more edges
What we have right now is only a wiki with a page and its title, but there is no content and no revisions. For that matter
we will use more edges and more vertex. Before the actual code which re-use all the above we will have a look at what
we are going to build:
8 Chapter 1. Walkthrough
python-graph-lovestory Documentation, Release 0.99
This is one of the normalized graph that can be used to represent the wiki, every graph structure that solve this problem
has its strengths, this happens, I think, to be the simplest.
First let’s create a function that create a revision for a given page given a body text, if you followed the whole tutorial it
should be easy to understand, and even if you happen to be here by mistake, I think it semantically expressive enough
to be understood by any Python programmer:
def create_revision(graph, page, body):
with graph.transaction():
max_revision = 0
for link in page.outgoings()
max_revision = max(link[’revision’], max_revision)
new_revision = max_revision + 1
# create the vertex first
revision = graph.vertex()
revision[’body’] = body
# link the edge and annotate it
link = graph.edge(page, ’revised as’, revision)
link[’revision’] = new_revision
create_revision does the following:
1.1. Blueprints 9
python-graph-lovestory Documentation, Release 0.99
1. Look for the highest revision in edges linked to page
2. Increment the revision number for the new page
3. Create the new revision
4. Link it to page with the proper revision property on the link vertex
A basic wiki would only need to fetch the last revision that’s what we do in the following fetch_last_revision
function:
def fetch_last_revision(graph, page):
max_revision = None
for link in page.outgoings()
new_revision = max(link[’revision’], max_revision)
if new_revision != max_revision:
max_revision = link.end()
return max_revision # if it returns None, the page is empty
That is all! Creating a page is very similar to this, so I won’t repeat the same code... Oh! I almost forgot about the list
of strings as property, the following function will add the tags passed as arguments which must be a list of strings, as
tags property of the last revision:
def add_tags(graph, page, *tags):
rev = fetch_last_revision(graph, page)
rev[’tags’] = tags
The basics are straightforward. Getting links working between pages is left as an exercices to the reader.
Index
GraphDBs have index, to create an index of vertex use the following code:
pages = graph.index.create(’pages’, graph.VERTEX)
To create an index of edges do this:
revisions = graph.index.create(’revisions’, graph.EDGE)
Then you can put vertex in an index using put(key, value, element):
pages.put(’page’, ’page’, page)
key and value parameters are not really interesting in the above example but an index can be that simple. You can
use key and value to have a fine-grained index of related elements, for instances, the following snipped builds an
index for revisions, properly separating minor, major revisions and sorting them by date of revisions:
revisions.put(’all’, ’today’, r2)
revisions.put(’all’, ’yesterday’, r1)
revisions.put(’all’, ’before’, r0)
revisions.put(’minor’, ’today’, r2)
revisions.put(’major’, ’yesterday’, r1)
revisions.put(’all’, ’before’, r0)
You can use Graph.index.get(name) to retrieve an index:
index = graph.index.get(’pages’)
To retrieve an index content, use Index.get, like this:
10 Chapter 1. Walkthrough
python-graph-lovestory Documentation, Release 0.99
index = index.get(’pages’, ’pages’)
first_page = next(index)
That’s almost all the index API, for more please refer to the API documentation.
End
When you finished working with the database don’t forget to call Graph.close().
More
If you still struggle with the API here is it with more comments:
• from blueprints import Graph
– Graph(name, path) remember that name is lower case of the databases names and the path for Ori-
entDB is prepended with local:.
– Graph.transaction() is a contextmanager, thus used with with statement that starts a transaction,
elements are automatically saved and you must always do mutating operations in transaction.
– Graph.create_vertex() create a vertex in a transaction.
– Graph.create_edge(start, label, end) create an edge in a transaction starting at start
vertex, ending at end vertex with label as label. The tutorial doesn’t say much about labels, so I add
here that it’s a way to know which edge is which when they are several edges starting and ending at the
same vertices.
– Graph.vertex(id) and Graph.edge(id) the former retrieve the vertex with id as identifier and
the latter the edge.
– Graph.close() clean up your database after you finished work.
– Graph.edges() and Graph.vertices() were not presented because they IMO should not be used
outside debug in an application where speed matters.
• An element is a vertex or an edge, they both are usable as dict to get and set values but can only be mutated in a
transaction. Every element can be deleted with delete() method in a transaction.
• Vertex you don’t import Vertex class, you get it from Graph.vertex() or graph.get_vertex(id)
or hoping through Edge.end() or Edge.starts.
– Vertex.outgoings() is a generator over the edges that are starting from the current vertex, each edge
retrieved implied a hop.
– Vertex.incomings() is a generator over the edges that are ending in the current vertex, each edge
retrieved implied a hop.
• Edge similarly are not imported, they are created with Graph.edge(start, label, end)
retrieved with Graph.get_vertice(id) and via iteration of Vertex.outgoings() and
Vertex.incomings() generators.
– Vertex.start() retrieve starting vertex via a hop
– Vertex.end() retrieve ending vertex via a hop
– Vertex.label() retrieve the label associated with the edge.
• Similarly you don’t import the Index class, but create one using Graph.index.create(name,
ELEMENT) where ELEMENT should be one of Graph.EDGE or Graph.VERTEX or retrieve the index by
its name using Graph.index.get(name).
1.1. Blueprints 11
python-graph-lovestory Documentation, Release 0.99
– Index.put(key, value, element put element in the key, value namespace.
– Index.get(key, vallue) to retrieve the index content, this is a generator over the index content.
hops are a metric used to compute the complexity of a query.
1.1.4 Moar doc
blueprints Package
blueprints Package
edge Module
element Module
graph Module
index Module
java Module
vertex Module
Subpackages
12 Chapter 1. Walkthrough

More Related Content

Similar to python-graph-lovestory

A Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and AllegroA Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and Allegrosnowfarthing
 
Android application architecture
Android application architectureAndroid application architecture
Android application architectureRomain Rochegude
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshareSaleemMalik52
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperFabrit Global
 
Learn reactjs, how to code with example and general understanding thinkwik
Learn reactjs, how to code with example and general understanding   thinkwikLearn reactjs, how to code with example and general understanding   thinkwik
Learn reactjs, how to code with example and general understanding thinkwikHetaxi patel
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrAfreenK
 
Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)YangJerng Hwa
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
Building a dynamic SPA website with Angular
Building a dynamic SPA website with AngularBuilding a dynamic SPA website with Angular
Building a dynamic SPA website with AngularFilip Bruun Bech-Larsen
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On RailsSteve Keener
 
Princeton RSE Peer network first meeting
Princeton RSE Peer network first meetingPrinceton RSE Peer network first meeting
Princeton RSE Peer network first meetingHenry Schreiner
 
Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Ahmed Bouchefra
 
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]
26 top angular 8 interview questions to know in 2020   [www.full stack.cafe]26 top angular 8 interview questions to know in 2020   [www.full stack.cafe]
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]Alex Ershov
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programmingsrijavel
 

Similar to python-graph-lovestory (20)

A Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and AllegroA Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and Allegro
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
 
Intro lift
Intro liftIntro lift
Intro lift
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Learn reactjs, how to code with example and general understanding thinkwik
Learn reactjs, how to code with example and general understanding   thinkwikLearn reactjs, how to code with example and general understanding   thinkwik
Learn reactjs, how to code with example and general understanding thinkwik
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrr
 
Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Shiny in R
Shiny in RShiny in R
Shiny in R
 
Building a dynamic SPA website with Angular
Building a dynamic SPA website with AngularBuilding a dynamic SPA website with Angular
Building a dynamic SPA website with Angular
 
django
djangodjango
django
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On Rails
 
Princeton RSE Peer network first meeting
Princeton RSE Peer network first meetingPrinceton RSE Peer network first meeting
Princeton RSE Peer network first meeting
 
Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps
 
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]
26 top angular 8 interview questions to know in 2020   [www.full stack.cafe]26 top angular 8 interview questions to know in 2020   [www.full stack.cafe]
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 

More from Jie Bao

unix toolbox 中文版
unix toolbox 中文版unix toolbox 中文版
unix toolbox 中文版Jie Bao
 
unixtoolbox.book
unixtoolbox.bookunixtoolbox.book
unixtoolbox.bookJie Bao
 
Lean startup 精益创业 新创企业的成长思维
Lean startup 精益创业 新创企业的成长思维Lean startup 精益创业 新创企业的成长思维
Lean startup 精益创业 新创企业的成长思维Jie Bao
 
Towards social webtops using semantic wiki
Towards social webtops using semantic wikiTowards social webtops using semantic wiki
Towards social webtops using semantic wikiJie Bao
 
Expressive Query Answering For Semantic Wikis (20min)
Expressive Query Answering For  Semantic Wikis (20min)Expressive Query Answering For  Semantic Wikis (20min)
Expressive Query Answering For Semantic Wikis (20min)Jie Bao
 
Startup best practices
Startup best practicesStartup best practices
Startup best practicesJie Bao
 
Owl 2 quick reference card a4 size
Owl 2 quick reference card a4 sizeOwl 2 quick reference card a4 size
Owl 2 quick reference card a4 sizeJie Bao
 
ISWC 2010 Metadata Work Summary
ISWC 2010 Metadata Work SummaryISWC 2010 Metadata Work Summary
ISWC 2010 Metadata Work SummaryJie Bao
 
Expressive Query Answering For Semantic Wikis
Expressive Query Answering For  Semantic WikisExpressive Query Answering For  Semantic Wikis
Expressive Query Answering For Semantic WikisJie Bao
 
24 Ways to Explore ISWC 2010 Data
24 Ways to Explore ISWC 2010 Data24 Ways to Explore ISWC 2010 Data
24 Ways to Explore ISWC 2010 DataJie Bao
 
Semantic Web: In Quest for the Next Generation Killer Apps
Semantic Web: In Quest for the Next Generation Killer AppsSemantic Web: In Quest for the Next Generation Killer Apps
Semantic Web: In Quest for the Next Generation Killer AppsJie Bao
 
Representing financial reports on the semantic web a faithful translation f...
Representing financial reports on the semantic web   a faithful translation f...Representing financial reports on the semantic web   a faithful translation f...
Representing financial reports on the semantic web a faithful translation f...Jie Bao
 
XACML 3.0 (Partial) Concept Map
XACML 3.0 (Partial) Concept MapXACML 3.0 (Partial) Concept Map
XACML 3.0 (Partial) Concept MapJie Bao
 
Development of a Controlled Natural Language Interface for Semantic MediaWiki
Development of a Controlled Natural Language Interface for Semantic MediaWikiDevelopment of a Controlled Natural Language Interface for Semantic MediaWiki
Development of a Controlled Natural Language Interface for Semantic MediaWikiJie Bao
 
Digital image self-adaptive acquisition in medical x-ray imaging
Digital image self-adaptive acquisition in medical x-ray imagingDigital image self-adaptive acquisition in medical x-ray imaging
Digital image self-adaptive acquisition in medical x-ray imagingJie Bao
 
Privacy-Preserving Reasoning on the Semantic Web (Poster)
Privacy-Preserving Reasoning on the Semantic Web (Poster)Privacy-Preserving Reasoning on the Semantic Web (Poster)
Privacy-Preserving Reasoning on the Semantic Web (Poster)Jie Bao
 
Privacy-Preserving Reasoning on the Semantic Web
Privacy-Preserving Reasoning on the Semantic WebPrivacy-Preserving Reasoning on the Semantic Web
Privacy-Preserving Reasoning on the Semantic WebJie Bao
 
Collaborative Construction of Large Biological Ontologies
Collaborative Construction of Large Biological OntologiesCollaborative Construction of Large Biological Ontologies
Collaborative Construction of Large Biological OntologiesJie Bao
 
Representing and Reasoning with Modular Ontologies (2007)
Representing and Reasoning with Modular Ontologies (2007)Representing and Reasoning with Modular Ontologies (2007)
Representing and Reasoning with Modular Ontologies (2007)Jie Bao
 

More from Jie Bao (20)

unix toolbox 中文版
unix toolbox 中文版unix toolbox 中文版
unix toolbox 中文版
 
unixtoolbox.book
unixtoolbox.bookunixtoolbox.book
unixtoolbox.book
 
Lean startup 精益创业 新创企业的成长思维
Lean startup 精益创业 新创企业的成长思维Lean startup 精益创业 新创企业的成长思维
Lean startup 精益创业 新创企业的成长思维
 
Towards social webtops using semantic wiki
Towards social webtops using semantic wikiTowards social webtops using semantic wiki
Towards social webtops using semantic wiki
 
Expressive Query Answering For Semantic Wikis (20min)
Expressive Query Answering For  Semantic Wikis (20min)Expressive Query Answering For  Semantic Wikis (20min)
Expressive Query Answering For Semantic Wikis (20min)
 
Startup best practices
Startup best practicesStartup best practices
Startup best practices
 
Owl 2 quick reference card a4 size
Owl 2 quick reference card a4 sizeOwl 2 quick reference card a4 size
Owl 2 quick reference card a4 size
 
ISWC 2010 Metadata Work Summary
ISWC 2010 Metadata Work SummaryISWC 2010 Metadata Work Summary
ISWC 2010 Metadata Work Summary
 
Expressive Query Answering For Semantic Wikis
Expressive Query Answering For  Semantic WikisExpressive Query Answering For  Semantic Wikis
Expressive Query Answering For Semantic Wikis
 
CV
CVCV
CV
 
24 Ways to Explore ISWC 2010 Data
24 Ways to Explore ISWC 2010 Data24 Ways to Explore ISWC 2010 Data
24 Ways to Explore ISWC 2010 Data
 
Semantic Web: In Quest for the Next Generation Killer Apps
Semantic Web: In Quest for the Next Generation Killer AppsSemantic Web: In Quest for the Next Generation Killer Apps
Semantic Web: In Quest for the Next Generation Killer Apps
 
Representing financial reports on the semantic web a faithful translation f...
Representing financial reports on the semantic web   a faithful translation f...Representing financial reports on the semantic web   a faithful translation f...
Representing financial reports on the semantic web a faithful translation f...
 
XACML 3.0 (Partial) Concept Map
XACML 3.0 (Partial) Concept MapXACML 3.0 (Partial) Concept Map
XACML 3.0 (Partial) Concept Map
 
Development of a Controlled Natural Language Interface for Semantic MediaWiki
Development of a Controlled Natural Language Interface for Semantic MediaWikiDevelopment of a Controlled Natural Language Interface for Semantic MediaWiki
Development of a Controlled Natural Language Interface for Semantic MediaWiki
 
Digital image self-adaptive acquisition in medical x-ray imaging
Digital image self-adaptive acquisition in medical x-ray imagingDigital image self-adaptive acquisition in medical x-ray imaging
Digital image self-adaptive acquisition in medical x-ray imaging
 
Privacy-Preserving Reasoning on the Semantic Web (Poster)
Privacy-Preserving Reasoning on the Semantic Web (Poster)Privacy-Preserving Reasoning on the Semantic Web (Poster)
Privacy-Preserving Reasoning on the Semantic Web (Poster)
 
Privacy-Preserving Reasoning on the Semantic Web
Privacy-Preserving Reasoning on the Semantic WebPrivacy-Preserving Reasoning on the Semantic Web
Privacy-Preserving Reasoning on the Semantic Web
 
Collaborative Construction of Large Biological Ontologies
Collaborative Construction of Large Biological OntologiesCollaborative Construction of Large Biological Ontologies
Collaborative Construction of Large Biological Ontologies
 
Representing and Reasoning with Modular Ontologies (2007)
Representing and Reasoning with Modular Ontologies (2007)Representing and Reasoning with Modular Ontologies (2007)
Representing and Reasoning with Modular Ontologies (2007)
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

python-graph-lovestory

  • 2.
  • 3. CONTENTS 1 Walkthrough 3 1.1 Blueprints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 i
  • 4. ii
  • 5. python-graph-lovestory Documentation, Release 0.99 Here you will find documentation about the component of my python graph lovestory, I hope you like it because I do. CONTENTS 1
  • 7. CHAPTER ONE WALKTHROUGH There’s no direct to the matter of «Developping Web application using graph databases» tutorial instead you read the following subject in order which introduce each library part of the stack each of which deal with specific matters and as such complexities are introduced along way you discover the stack, so that you know all the good parts but also all the bad parts before you start. 1.1 Blueprints 1.1.1 Kesako ? Blueprints allows to use several graph database with the same API. It can be used to embed a graph database in your Python program. If several process need to access the same database it’s not what you need. python-blueprints are pyjnius powered bindings of Tinkerpop’s Java Blueprints. 1.1.2 Installation There is no binary package for now so you may have some difficulties installing python-blueprints on Windows and MacOS machines, but it’s possible. Follow the cli dance: mkvirtualenv --system-site-packages coolprojectname pip install cython git+git://github.com/kivy/pyjnius.git blueprints You are ready for some graph database awesomeness in Python. 1.1.3 Getting started with core API The python-blueprints API is straightforward it’s basicly the Blueprints API in Python, if you know Neo4j’s python- embedded the API is similar but not the same. Create a graph Creating a graph is just matter of knowing where to store the files and the backend you want to use, currently only Neo4j and OrienDB are supported. For the purpose of the tutorial, we will use /tmp/ as storage directory. Using Neo4j: 3
  • 8. python-graph-lovestory Documentation, Release 0.99 from printemps.core import Graph graph = Graph(’neo4j’, ’/tmp/’) Getting OrientDB running is very similar: from printemps.core import Graph graph = Graph(’orientdb’, ’local:/tmp/’) A Wiki model The following is exactly the same for both OrientDB and Neo4j. In order to make easier for everybody to under- stand how graphs works, we will model a wiki, while we introduce the base API of any graph databases used with printemps.core. A wiki will be a set of pages which have several revisions. Create and modify edge and vertex To create a vertex just call Graph.create_vertex() method inside a transaction: with graph.transaction(): wiki = graph.create_vertex() There is no Vertex.save() method nor Edge.save(), the elements are automatically persisted if the transaction succeed. If you want to know the identifier of the wiki in the database to store it somewhere or learn it by hearth, you can use Vertex.id(), Edge.id() does the same for edges. Both vertex and edge work like a dictionary, you can set and get properties, they are persisted if you do it inside a transaction, I don’t know what happens outside transactions. Let’s give a name and description to our wiki vertex: with graph.transaction(): wiki[’title’] = ’Printemps Wiki’ wiki[’description’] = ’My first graph based wiki’ Keys are always strings, values can be: • strings • integers • list of strings • list of integers We will see later how it can be done, it’s very natural for Python programmers. Now we will create a page, a page will be vertex too: with graph.transaction(): frontpage = graph.create_vertex() frontpage[’title’] = ’Welcome to Printemps Wiki’ The page needs to be linked to wiki as a part of, for that matter there is a method Graph.create_edge(start, label, end) than can be used like this: 4 Chapter 1. Walkthrough
  • 9. python-graph-lovestory Documentation, Release 0.99 with graph.transaction(): partof = graph.edge(wiki, ’part of’, frontpage) An edge has three important methods, that do actually nothing but return the value we are interested in, but since those are not editable, you access them through methods: • Edge.start() returns the vertex where the edge is starting, in the case of partof it’s wiki vertex • Edge.end() returns the vertex where the edge is ending, in the case of partof it’s frontpage vertex • Edge.label() returns the label of the edge, in the case of partof it’s the string ’part of’ In general, every object you think of is a vertex, but some times some «objects» are modeled as edges, those are links. An object representing a link between two objects is an edge. If the link object involves more that two edges, then it can be represented as an hyperedge. Note: this is advanced topic you can skip it. The idea behind the hyperedge is that a vertex can be linked to several other vertex using only one special edge the hy- peredge, which means the edge starts with one vertex, and ends with several vertex. Here is an example representation of an hyperedge: 1.1. Blueprints 5
  • 10. python-graph-lovestory Documentation, Release 0.99 This can be modeled in a graph using only vertices and simple edges with an intermediate vertex which serves as a hub for serveral edges that will link to the end vertices of the hyperedge. Here is the pattern illustrated: 6 Chapter 1. Walkthrough
  • 11. python-graph-lovestory Documentation, Release 0.99 Hyperedges are not part of popular graphdbs as is, so you have to use the intermediate vertex pattern. To sum up, link objects with more that two objects involved in the link are the exception among link objects and are represented as vertex. Navigation Stay away with your motors, sails and emergency fire lighters, it’s just plain Python even though you can do it in boat too, but this is not my issue at the present moment. Before advancing any further, let’s sum up, we have a graph with two vertices, and one edge, it can be represented as follow: 1.1. Blueprints 7
  • 12. python-graph-lovestory Documentation, Release 0.99 Because we like the wiki so much we know its identifier by hearth and stored it in a variable named wiki_identifier, we can retrieve the wiki vertex like so: wiki = graph.vertex(wiki_identifier) Vertices have two kinds of edges: • Vertex.incomings(): a generator yielding edges that ends at this vertex, currently there is none on wiki • Vertex.outgoings(): a generator yielding edges that starts at this vertex, currently there is only one. To retrieve the frontpage we can use next function of wiki.outgoings() to rertrieve the first and only edge as first hop and navigate to the index using Edge.end() as second hop: link = next(wiki.outgoings()) frontpage = link.end() We got back our frontpage vertex back, Ulysse himself wouldn’t believe it, it’s not the same object though. More vertices and more edges What we have right now is only a wiki with a page and its title, but there is no content and no revisions. For that matter we will use more edges and more vertex. Before the actual code which re-use all the above we will have a look at what we are going to build: 8 Chapter 1. Walkthrough
  • 13. python-graph-lovestory Documentation, Release 0.99 This is one of the normalized graph that can be used to represent the wiki, every graph structure that solve this problem has its strengths, this happens, I think, to be the simplest. First let’s create a function that create a revision for a given page given a body text, if you followed the whole tutorial it should be easy to understand, and even if you happen to be here by mistake, I think it semantically expressive enough to be understood by any Python programmer: def create_revision(graph, page, body): with graph.transaction(): max_revision = 0 for link in page.outgoings() max_revision = max(link[’revision’], max_revision) new_revision = max_revision + 1 # create the vertex first revision = graph.vertex() revision[’body’] = body # link the edge and annotate it link = graph.edge(page, ’revised as’, revision) link[’revision’] = new_revision create_revision does the following: 1.1. Blueprints 9
  • 14. python-graph-lovestory Documentation, Release 0.99 1. Look for the highest revision in edges linked to page 2. Increment the revision number for the new page 3. Create the new revision 4. Link it to page with the proper revision property on the link vertex A basic wiki would only need to fetch the last revision that’s what we do in the following fetch_last_revision function: def fetch_last_revision(graph, page): max_revision = None for link in page.outgoings() new_revision = max(link[’revision’], max_revision) if new_revision != max_revision: max_revision = link.end() return max_revision # if it returns None, the page is empty That is all! Creating a page is very similar to this, so I won’t repeat the same code... Oh! I almost forgot about the list of strings as property, the following function will add the tags passed as arguments which must be a list of strings, as tags property of the last revision: def add_tags(graph, page, *tags): rev = fetch_last_revision(graph, page) rev[’tags’] = tags The basics are straightforward. Getting links working between pages is left as an exercices to the reader. Index GraphDBs have index, to create an index of vertex use the following code: pages = graph.index.create(’pages’, graph.VERTEX) To create an index of edges do this: revisions = graph.index.create(’revisions’, graph.EDGE) Then you can put vertex in an index using put(key, value, element): pages.put(’page’, ’page’, page) key and value parameters are not really interesting in the above example but an index can be that simple. You can use key and value to have a fine-grained index of related elements, for instances, the following snipped builds an index for revisions, properly separating minor, major revisions and sorting them by date of revisions: revisions.put(’all’, ’today’, r2) revisions.put(’all’, ’yesterday’, r1) revisions.put(’all’, ’before’, r0) revisions.put(’minor’, ’today’, r2) revisions.put(’major’, ’yesterday’, r1) revisions.put(’all’, ’before’, r0) You can use Graph.index.get(name) to retrieve an index: index = graph.index.get(’pages’) To retrieve an index content, use Index.get, like this: 10 Chapter 1. Walkthrough
  • 15. python-graph-lovestory Documentation, Release 0.99 index = index.get(’pages’, ’pages’) first_page = next(index) That’s almost all the index API, for more please refer to the API documentation. End When you finished working with the database don’t forget to call Graph.close(). More If you still struggle with the API here is it with more comments: • from blueprints import Graph – Graph(name, path) remember that name is lower case of the databases names and the path for Ori- entDB is prepended with local:. – Graph.transaction() is a contextmanager, thus used with with statement that starts a transaction, elements are automatically saved and you must always do mutating operations in transaction. – Graph.create_vertex() create a vertex in a transaction. – Graph.create_edge(start, label, end) create an edge in a transaction starting at start vertex, ending at end vertex with label as label. The tutorial doesn’t say much about labels, so I add here that it’s a way to know which edge is which when they are several edges starting and ending at the same vertices. – Graph.vertex(id) and Graph.edge(id) the former retrieve the vertex with id as identifier and the latter the edge. – Graph.close() clean up your database after you finished work. – Graph.edges() and Graph.vertices() were not presented because they IMO should not be used outside debug in an application where speed matters. • An element is a vertex or an edge, they both are usable as dict to get and set values but can only be mutated in a transaction. Every element can be deleted with delete() method in a transaction. • Vertex you don’t import Vertex class, you get it from Graph.vertex() or graph.get_vertex(id) or hoping through Edge.end() or Edge.starts. – Vertex.outgoings() is a generator over the edges that are starting from the current vertex, each edge retrieved implied a hop. – Vertex.incomings() is a generator over the edges that are ending in the current vertex, each edge retrieved implied a hop. • Edge similarly are not imported, they are created with Graph.edge(start, label, end) retrieved with Graph.get_vertice(id) and via iteration of Vertex.outgoings() and Vertex.incomings() generators. – Vertex.start() retrieve starting vertex via a hop – Vertex.end() retrieve ending vertex via a hop – Vertex.label() retrieve the label associated with the edge. • Similarly you don’t import the Index class, but create one using Graph.index.create(name, ELEMENT) where ELEMENT should be one of Graph.EDGE or Graph.VERTEX or retrieve the index by its name using Graph.index.get(name). 1.1. Blueprints 11
  • 16. python-graph-lovestory Documentation, Release 0.99 – Index.put(key, value, element put element in the key, value namespace. – Index.get(key, vallue) to retrieve the index content, this is a generator over the index content. hops are a metric used to compute the complexity of a query. 1.1.4 Moar doc blueprints Package blueprints Package edge Module element Module graph Module index Module java Module vertex Module Subpackages 12 Chapter 1. Walkthrough