How can I create nodes in Memgraph directly from Python? - memgraphdb

I have an application that uses Memgraph. At the moment, queries are written using Cypher. I'd like to move them to Python. What would be the equivalent of Cypher clauses CREATE (e.g.CREATE (:City {name: 'London'});) and MERGE (e.g. MERGE (:City {name: 'Dublin'});)?

First, you need to install GQLAlchemy. GQLAlchemy is a standalone Object Grap Mapper (OGM) for Python.
For creating nodes, use the method node() after create():
from gqlalchemy import Create
query = Create().node(labels="City", name="London").execute()
When you use the merge() method instead of create(), the node won't be created if it already exists, it will only be updated if the properties don't match:
from gqlalchemy import Merge
query = Merge().node(labels="City", name="Dublin").execute()

Related

Build list from nested object in apache freemarker?

I have a list of object and I want to get a list from its field.
Say I pass List<Auto> autos from java side to the template on the document side. Each Auto has a field of speed.
So the result should be list of speed.
I can do it manually looping through the autos and building a new list from the speed fields.
Is there any easier solution built in for this in the freemarker something like 'autos.speed?tolist'
You are looking for the sequence built-in map, which is available from version 2.3.29. It returns a new sequence where all elements are replaced with the result of the parameter lambda, function, or method. This allows you to do:
autos?map(auto -> auto.speed)
If you want to do this in Java, see:
Create list of object from another using Java 8 Streams
There it comes down to:
autos.stream().map(Auto::getSpeed).collect(Collectors.toList());

Get neo4j result

I'm using neo4j jdbc driver to access a local service and make the following query to find what I need:
"MATCH (u:User)-->(d:Deck)-[p:Played]->(g:Game)" +
"WHERE id(g) = ?" +
"RETURN {r {user :u, deck :d, played:p, game:g}}"
I cast it as a map and can find the parts and, right there in my face, I can see the stuff I need. How do I get it? (the {comment= ...} etc)
I do know how to get it by
RETURN p.comment, p.place ... etc
But I fear this will soon get out of hand. If I can just get at least that json string I would be happy.
There is a built-in Cypher function PROPERTIES(), outlined here, that will convert anything that has properties (nodes, relationships, even pre-existing Maps) to a Map of the properties with no other data. The language drivers have built-in tools to hydrate Nodes and Relationships so that property access is simple, but if you require a Map and only a Map to be returned, just use RETURN PROPERTIES(p) and you'll get it.
Reading between the lines, it looks like you are trying to get all the properties of specific nodes and properties, without any extraneous metadata.
After installing the APOC plugin, you can use the apoc.map.fromPairs procedure to generate a map with all the properties of a node or relationship.
For example, to get all the properties of every User node:
MATCH (u:User)
CALL apoc.map.fromPairs([k IN KEYS(u) | [k, u[k]]]) YIELD value AS props
RETURN props;
[k IN KEYS(u) | [k, u[k]]] generates a collection of key/value collections.
The apoc.map.fromPairs() procedure takes a collection of key/value collections, and converts it into a map.

Is there a way to use PathFinder from GraphAlgoFactory with spring-data

I took a look at movies-java-spring-data-neo4j-4 and I love it, but I want to use PathFinder from GraphAlgoFactory with spring-data 4.1.1.RELEASE.
I want to create some sort of Roadmap in my db and use the RestController to find a path between two given nodes.
(Basically the second (A*) example from here: neo4j-docs-graph-algo)
PathFinder<WeightedPath> astar = GraphAlgoFactory.aStar(
PathExpanders.allTypesAndDirections(),
doubleCostEvaluator, estimateEvaluator);
path = astar.findSinglePath(start, end);
findSinglePath needs an Object of org.neo4j.graphdb.Node is there a way to get this from a NodeEntity?
The only way I could find is using the EmbeddedDriver and looking up the node myself:
EmbeddedDriver embeddedDriver = (EmbeddedDriver) Components.driver();
GraphDatabaseService databaseService = embeddedDriver.getGraphDatabaseService();
Node node = databaseService.findNode(...)
Is there an easier way, preferably via HttpDriver?
The HTTP Driver does not provide access to the underlying graph database. You can write a stored procedure and call it via the session/template/repository query methods.
Here are some examples of stored procedures for graph algorithms- https://github.com/neo4j-contrib/neo4j-apoc-procedures/#graph-algorithms-work-in-progress

How to perform a NOT query with postgres_ext

Is it possible to perform a NOT type query with chained methods using postgres_ext?
rules = Rule.where.overlap(:tags => ["foo"])
Basically want the inverse of the above. Thanks!
In regular active record you can use .where.not as described in this article: https://robots.thoughtbot.com/activerecords-wherenot however looking through the source code of postgres_ext I don't know if it is defined in that library. You may be able to construct your query in a way that uses the native active record methods.

How to export neo4j data to csv/json

I am using Neo4j Python REST Client and I want to use D3.js for the visualisation of my data.
I am creating the data like this:
gdb = GraphDatabase("http://localhost:7474/db/data/")
alice = gdb.nodes.create(name="Alice",isTeacher=False)
bob = gdb.nodes.create(name="Bob"isTeacher=True)
bob.relationships.create("Knows", alice,strength = 0.4)
Is it possible to transform my data into json/csv in order to use that in D3?
Thanks in advance.
In the current version of neo4jrestclient, there is an option to return the data of a query as a list of rows or as a graph representation. So, you could run a query and use that.
results = gdb.query("MATCH (n)--() RETURN n", data_contents=True)
print(results.rows)
print(results.graph)
Only working for Neo4j 2.0+, though. In future releases, QuerySequence objects like results, will have to_csv() and to_json() helpers.

Resources