question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I'm running a server at my office to process some files and report the results to a remote MySQL server. The files processing takes some time and the process dies halfway through with the following error: 2006, MySQL server has gone away I've heard about the MySQL setting, wait_timeout, but do I need to change that on the server at my office or the remote MySQL server?
I have encountered this a number of times and I've normally found the answer to be a very low default setting of max_allowed_packet. Raising it in /etc/my.cnf (under [mysqld]) to 8 or 16M usually fixes it. (The default in MySql 5.7 is 4194304, which is 4MB.) [mysqld] max_allowed_packet=16M Note: Just create the line if it does not exist, it must appear as an entry underneath [mysqld] Note: This can be set on your server as it's running but it will be lost after the mysql daemon is restarted. Use SET GLOBAL max_allowed_packet=104857600 (this sets it to 100MB) Note: On Windows you may need to save your my.ini or my.cnf file with ANSI not UTF-8 encoding.
MySQL
7,942,154
334
Is there a nice way in MySQL to replicate the SQL Server function ROW_NUMBER()? For example: SELECT col1, col2, ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow FROM Table1 Then I could, for example, add a condition to limit intRow to 1 to get a single row with the highest col3 for each (col1, col2) pair.
There is no ranking functionality in MySQL 5.7 or below. (This is supported in MySQL v8.0+, see @LukaszSzozda's answer) The closest you can get is to use a variable: SELECT t.*, @rownum := @rownum + 1 AS rank FROM YOUR_TABLE t, (SELECT @rownum := 0) r so how would that work in my case? I'd need two variables, one for each of col1 and col2? Col2 would need resetting somehow when col1 changed..? Yes. If it were Oracle, you could use the LEAD function to peak at the next value. Thankfully, Quassnoi covers the logic for what you need to implement in MySQL.
MySQL
1,895,110
334
I'm trying to manually execute SQL commands so I can access procedures in NuoDB. I'm using Ruby on Rails and I'm using the following command: ActiveRecord::Base.connection.execute("SQL query") The "SQL query" could be any SQL command. For example, I have a table called "Feedback" and when I execute the command: ActiveRecord::Base.connection.execute("SELECT `feedbacks`.* FROM `feedbacks`") This would only return a "true" response instead of sending me all the data requested. This is the output on the Rails Console is: SQL (0.4ms) SELECT `feedbacks`.* FROM `feedbacks` => true I would like to use this to call stored procedures in NuoDB but upon calling the procedures, this would also return a "true" response. Is there any way I can execute SQL commands and get the data requested instead of getting a "true" response?
The working command I'm using to execute custom SQL statements is: results = ActiveRecord::Base.connection.execute("foo") with "foo" being the sql statement( i.e. "SELECT * FROM table"). This command will return a set of values as a hash and put them into the results variable. So on my rails application_controller.rb I added this: def execute_statement(sql) results = ActiveRecord::Base.connection.execute(sql) if results.present? return results else return nil end end Using execute_statement will return the records found and if there is none, it will return nil. This way I can just call it anywhere on the rails application like for example: records = execute_statement("select * from table") "execute_statement" can also call NuoDB procedures, functions, and also Database Views.
NuoDB
22,752,777
215
I have been using cypher and neo4j for a while now, and I keep running into a similar problem again and again. I would like to be able to add a "temporary" property to a node thats exists only in the returned data and is not persisted to the Neo4j database. For example the current problem I am working on is given an N-ary tree structure in the graph database, I would like to return the children of a specific node, and an informational boolean letting me know weather those children have children. The query to get this information is simple enough: MATCH (parent:Item { guid: "Identifier here" })-[:HASCHILD]->(child:Item) OPTIONAL MATCH (child)-[:HASCHILD]->(grandchild:Item) WITH parent, child, LENGTH(COLLECT(grandchild)) > 0 AS has_children Now I have the parent, child and a boolean letting me know weather there are further children. What I would like to be able to do next is set the has_children boolean as a property on the child nodes, but just for returning the query, I don't need the property persisted. I know there is are some solutions to get what I am looking for but none of them are specifically what I am looking for. 1) I could create a temporary node: (Continued from above query) ... WITH parent, child, LENGTH(COLLECT(grandchild)) > 0 AS haschildren, { childkey1: child.childkey1, childkey2: child.childkey2, ... has_children: haschildren } AS tempnode RETURN parent, tempnode This solution is not great, you have to know the exact node type and all the properties of the node you are dealing with, it will not work in the general case. 2) I could SET and REMOVE the boolean, temporarily persisting it to the database (as described in Neo4J create temp variable within Cypher). This is not great as it will cause multiple db writes (for add and remove). Also, it is not as dynamic as option 1 as it would only be able to handle simple types. (Option 1 can handle more complex cases, like adding a collection of nodes instead of a simple boolean). As far as I know, these are the only options when it comes to temporary return data. I'm wondering am I missing any thing? Is it possible to make this more simple or dynamic? Something along the lines of WITH parent, child, LENGTH(COLLECT(grandchild)) > 0 AS haschildren, TEMPSET child.has_children = haschildren Please note that I have simplified the examples given a little. I have run into this issue multiple times in different contexts in neo4j. Most times I either go with option 1, or build the correct structure by post-processing on the application side once the query returns. Is there a better way?
You can try returning a map projection. Take a look in this example: // Creating a sample node CREATE (:Person {name:'Jon', id: 1}) Returning the projection with a extra boolean: MATCH (p:Person {id:1}) WITH p, true AS has_children RETURN p{.*, has_children:has_children} The result: ╒═════════════════════════════════════════╕ β”‚"p" β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚{"id":1,"name":"Jon","has_children":true}β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ The above query is returning all properties of p node with an extra boolean.
Neo4j
45,837,277
18
They just announced, they changed their name to Neo5j. I always thought that 4j meant for-Java. And as Neo4j is implemented in Java and Scala and the ~4j suffix has been highly popular (in the 90's) it never occurred to me that the 4j and now 5j is actually a version denomination. But it seems common in database circles to use that number + letter versioning scheme, like Oracle does with 9i, 11g and 12c. Now the question is what does the 5j stand for? The article doesn't answer it. Can anyone help me resolve this?
The Neo series of databases was developed in Sweden and attracted the 'j' suffix with the release of version 4 of the graph database. The 'j' is from the word 'jΓ€ttetrΓ€d', literally "giant tree", and was used to indicate the huge data structures that could now be stored. Incidentally the 'neo' portion of the name is a nod to a Swedish pop artist Linus Ingelsbo, who goes by the name NEO. In Neo1 the example graph was singers and bands and featured the favourite artists of the developers, including NEO. This was changed to the movie data set in the version 4 release.
Neo4j
43,157,146
18
I'm new to Neo4J, and have been learning Cypher query language the past few days. I realized I can write my query like this... MATCH (b:Beverage)<-[:likes]-(p:Person)-[:likes]->(r:Restaurant) WHERE b.name = 'Beer' and r.name = 'KFC' RETURN p.name ... or like this... MATCH (b:Beverage{name:'Beer'})<-[:likes]-(p:Person)-[:likes]->(r:Restaurant{name:'KFC'}) RETURN p.name Which approach is better in terms of performance? And why? Thank you.
I'm sorry to say, but @a-rodin's reply is wrong here: both of your statements result in the very same query plan. You can verify that by prefixing the statement with EXPLAIN and comparing the query plans. For readability I'd structure the query in question: MATCH (p:Person)-[:likes]->(b:Beverage{name:'Beer'}), (p)-[:likes]->(r:Restaurant{name:'KFC'}) RETURN p.name Here the query reads like a sentence in plain English "match a person that likes beer and and like KFC restaurants".
Neo4j
32,118,750
18
I'm trying to execute following query: MATCH (movie:Movie {title:"test"})-[r]-() DELETE movie, r to delete a :Movie node and all its relationships. It's all good, except if the query doesn't have any relationships, it fails to MATCH the movie. I've tried with OPTIONAL MATCH, but no luck. I'm looking for a way to DELETE a movie node no matter if it has or doesn't have any relationships, but if it has, to DELETE them as well.
In new Neo4j versions (since 2.3 I think) you can use such syntax: MATCH (movie:Movie {title:"test"}) DETACH DELETE movie
Neo4j
29,444,426
18
Using Match and Where can delete a relationship by ID. Match ()-[r]-() Where ID(r)=1 Delete r Is there a simpler way?
I use MATCH ()-[r]-() WHERE id(r)=49 DELETE r
Neo4j
28,185,623
18
How to write a CYPHER query that returns only those nodes that do not have labels attached to them? I tried: match (n:) return n Invalid input ')': expected whitespace or a label name (line 1, column 10) "match (n:) return n" ^
In Neo4j < 2.3: MATCH n WHERE length(labels(n)) = 0 RETURN n In Neo4j >= 2.3: MATCH (n) WHERE size(labels(n)) = 0 RETURN n
Neo4j
24,247,505
18
I'd like a query that counts how many nodes have each label in the dataset. For instance: LabelA 100 LabelB 200 I can do this for each individual label with something like MATCH (n:LabelA) return count(n); But, I'd like to do it for every label in one command.
Try something like this MATCH (n) RETURN count(labels(n)), labels(n); This will return the sum of the labels in the first column and the label name in the second.
Neo4j
21,555,529
18
Coming from a relational database mindset, it seems odd that one only one one graph db per instance of neo4j. Is the idea that we do multiple subgraphs starting from root ? Thanks
The concept of "root" node is going away. There are many problems with this, most of which revolve around node density. I believe the heart of your question is around database design, and whether it is smarter to have several graph database instances, or one instance with several subgraphs. Really it's up to you, but I would go with the subgraph idea as it allows some of your data to be shared in the same connection, and Neo4j doesn't really any performance penalties if you do this, provided you keep them separated, then the only problem you'll eventually run into is the max size of nodes/relationship, but this is an artificial limit that will be bumped up later.
Neo4j
17,392,478
18
So I looked into neo4j, and I may be using it in an upcoming project since its data model might fit my project very well. I looked through the docs but I still need an answer to this question: Can I set relationships to be one-directional? It seems that the neo4j people like movies so let's continue with that. If I have a graph like this: Actor A -> [:Acts in] -> Movie B then direction is obvious, because the nodes are different types. But I like horror movies so... Person A -> [:wants_to_kill] -> Person B I need this relationship to be one-directional so if I query "Who does Person A want to kill?" I get Person B, if I query "Who does Person B want to kill?" I get nothing. Sometimes I still need relationships to be two directional Like: Person A <-[:has_met] -> Person B ...which is obvious. documentation says: Relationships are equally well traversed in either direction. This means that there is no need to add duplicate relationships in the opposite direction (with regard to traversal or performance). While relationships always have a direction, you can ignore the direction where it is not useful in your application. So docs say, relationships by default have an direction and I can ignore that if I wish. Now this is where things get complicated: Consider the following graph (and note the arrows) Person A <- [:wants_to_kill] -> Person B Person B -> [:wants_to_kill] -> Person C Person C -> [:wants_to_kill] -> Person A If I ignore the Directions for all [:wants_to_kill] I get false results for "Who does Person A / C want to kill?" If I knew which ones I had to ignore, I would not do the query. So can I somehow set relationships to be two-directional (when creating them), or should I model this with two relationships (between Person A & B)?
A relationship in Neo4j always has a direction. If a relationship type's semantics do not incorporate a direction, e.g. has_met from your example, then it's best practice to apply an arbitrary direction on creation of the relationship. Querying is then done by using the "both directions" (there is no "larger/smaller than" character) notation in cypher: start ... match (a)-[:HAS_MET]-(b) .... In contrast, if the semantics of a relationship do have a direction like your wants_to_kill, you need to use two relationship to indicate that a and b wants kill the other one and vice versa. For the example above, you need to have 4 relationships: Person A -[:wants_to_kill]-> Person B Person B -[:wants_to_kill]-> Person A Person B -[:wants_to_kill]-> Person C Person C -[:wants_to_kill]-> Person A To find all the person that A wants to kill you do: start a=node:node_auto_index(name='A') match a-[:wants_to_kill]->victims_of_a return victims_of_a To find all persons who want to kill A: start a=node:node_auto_index(name='A') match murderer_of_a-[:wants_to_kill]->a return murderer_of_a
Neo4j
16,876,378
18
I have been dealing with Neo4j through python's Bulbflow and now need a way to save/export subgraphs. I have seen Java and even Ruby approaches for doing this, however a simple Python approach seems to be hiding from me.. So far, I have found two potential paths: Accessing Geoff through py2neo, but there is surprisingly little documentation for extracting a subgraph from a big local neo4j database or from a neo4jserver. Using Networkx: I found networkx can load graphs from many different formats (I am unsure which format neo4j stores their dbs), however I haven't found a way to extract a only a subgraph into Networkx. I assume this should be done from a gremlin query, but I'm not sure how to go about this. I have a preference for the Networkx path, as it also comes with network analysis algorithms I wish to apply to subgraphs. I feel it would also avoid potential clashes between Bulbflow and py2neo, although I'm not sure whether such a clash would exist. Any advice would be much appreciated! Thanks in advance
I didn't know the answer until you asked, but it seems like you can just export in gml, which networkx can read. Here are a few answers that might be useful: Neo4j export Tree Convert Neo4j DB to XML? https://github.com/tinkerpop/gremlin/wiki/Gremlin-Methods Hope that helps.
Neo4j
15,459,615
18
I am finding Neo4j slow to add nodes and relationships/arcs/edges when using the REST API via py2neo for Python. I understand that this is due to each REST API call executing as a single self-contained transaction. Specifically, adding a few hundred pairs of nodes with relationships between them takes a number of seconds, running on localhost. What is the best approach to significantly improve performance whilst staying with Python? Would using bulbflow and Gremlin be a way of constructing a bulk insert transaction? Thanks!
There are several ways to do a bulk create with py2neo, each making only a single call to the server. Use the create method to build a number of nodes and relationships in a single batch. Use a cypher CREATE statement. Use the new WriteBatch class (just released this week) to manually make a batch of nodes and relationships (this is really just a manual version of 1). If you have some code, I'm happy to look at it and make suggestions on performance tweaks. There are also quite a few tests you may be able to get inspiration from. Cheers, Nige
Neo4j
12,643,662
18
I'm trying to get the number of nodes of a Neo4j graph database using Python, but I don't find any method or property to do that. Does anybody how can I get this information? Other Python packages like NetworkX has a method to get this information. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> len(G) 3
Update: Since I first wrote this, the answer has changed. The database now keeps exact counts of total nodes, as well as counts by label. Unlike most databases, this is not a heuristic, these counters are transactionally kept in sync with the rest of the datastore. This means you can get exact node counts in O(1) time from Neo4j. You get access to them by asking Cypher: MATCH (n) RETURN count(*) Original reply: There are two ways to get the number of nodes in a neo4j database. The first one is to actually iterate through all the nodes, and counting them. Alternative two is to use the "number of node ids in use" statistic provided by the db kernel, which does not guarantee to be exact, but will be at least the number of nodes in use. In a high-load db it will be higher, since it also contains ids of deleted nodes that have not been reclaimed yet. Alt one is reasonably exact (depending on how many are created/deleted while you iterate), but can be super slow. Alt two is potentially way off, but is a O(1) operation. You currently don't have much choice, because alt one is the only one that works. It isn't officially supported, so doing it today looks a bit dirty: from neo4j import GraphDatabase db = GraphDatabase('..') node_count = sum(1 for _ in db.getAllNodes().iterator()) I've added two issues for this, one to add support for accessing management info (eg. support the alt two method), and one to add support for these use cases: node_count = sum(1 for _ in db.nodes) node_count = len(db.nodes) Follow these issues here: https://github.com/neo4j/python-embedded/issues/7 https://github.com/neo4j/python-embedded/issues/6 Please let us now if you run into any other trouble with neo4j-embedded, add a ticket to the github issues if you discover any bugs or think of any other enhancements!
Neo4j
8,159,756
18
I have some issues with APOC and Graph Algorithms plugins. I followed the instruction to put the .jars in {NEO4j_HOME}/plugins and also change the setting in my {NEO4j_HOME}/conf/neo4j.conf dbms.directories.data=/Users/mlo/neo4j-community-3.3.1/data dbms.directories.plugins=/Users/mlo/neo4j-community-3.3.1/plugins dbms.directories.certificates=/Users/mlo/neo4j-community-3.3.1/certificates dbms.directories.logs=/Users/mlo/neo4j-community-3.3.1/logs dbms.directories.lib=/Users/mlo/neo4j-community-3.3.1/lib dbms.directories.run=/Users/mlo/neo4j-community-3.3.1/run dbms.security.auth_enabled=false dbms.security.procedures.unrestricted=algo.* dbms.security.procedures.unrestricted=apoc.* A few procedures work. CALL apoc.help('dijkstra') CALL algo.list() However, most of the stored procedures do not work at all. Neo.ClientError.Procedure.ProcedureRegistrationFailed algo.unionFind is unavailable because it is sandboxed and has dependencies outside of the sandbox. Sandboxing is controlled by the dbms.security.procedures.unrestricted setting. Only unrestrict procedures you can trust with access to database internals. algo.pageRank is unavailable because it is sandboxed and has dependencies outside of the sandbox. Sandboxing is controlled by the dbms.security.procedures.unrestricted setting. Only unrestrict procedures you can trust with access to database internals. Can someone point out where goes wrong in my setting? Thanks.
Change these lines: dbms.security.procedures.unrestricted=algo.* dbms.security.procedures.unrestricted=apoc.* to: dbms.security.procedures.unrestricted=algo.*,apoc.* and restart Neo4j service.
Neo4j
48,773,505
17
I've built and installed the "apoc" procedures according to the github page (The apoc-1.0.0-SNAPSHOT.jar file was copied into the plugins directory after the suerver was stopped, and then I started the server again) but when I try to call any of the procedures, I get an error message. ex: $ call apoc.help('search') ; "There is no procedure with the name apoc.help registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed." I have come across the issue on both MacOs and Windows installations. I'm running Neo4j 3.0.0 as a server (locally on port 7474). Have I missed any of the settings? Thanks, Babak.
I had to manually add this line to the .neo4j.conf file: dbms.directories.plugins=/Applications/Neo4j\ Community\ Edition.app/Contents/Resources/app/plugins (assuming that's where you dropped the APOC jar) and then restart the server. (It's a little confusing as there's an option in the management app to configure this path, but it seems not actually to enable plug-ins on the server.)
Neo4j
36,897,634
17
This is an extremely simple question, but reading through the docs for the first time, I can't figure out how to construct this query. Let's say I have a graph that looks like: and additionally each person has an age associated with them. What CYPHER query will get me a list of John's age and all the ages of the entire friend tree of John? What I've tried so far: MATCH (start)-[:friend]>(others) WHERE start.name="John" RETURN start.age, others.age This has several problems, It only goes one one one friend deep and I'd like to go to all friends of John. It doesn't return a list, but a series of (john.age, other.age).
So what you need is not only friend of john, but also friends of friends. So you need to tell neo4j to recursively go deep in the graph. This query goes 2 level deep. MATCH (john:Person { name:"John" })-[:friend *1..2]->(friend: Person) RETURN friend.name, friend.age; To go n nevel deep, don't put anything i.e. *1.. Oh and I also found this nice example in neo4j So what does *1..2 here means: * to denote that its a recursion. 1 to denote that do not include john itself i.e. is the start node. If you put 0 here, it will also include the John node itself. .. to denote that go from this node till ... 2 denotes the level of recursion. Here you say to stop at level 2. i.e. dont go beyond steve. If you put nothing there, it will keep on going until it cannot find a node that "has" a friend relationship Documentation for these types of query match is here and a similar answer here.
Neo4j
31,079,881
17
Is there a R library that supports neo4j? I would like to construct a R graph (e.g. igraph) from neo4j or - vice versa - store a R graph in neo4j. More precisely, I am looking for something similar to bulbflow for Python. Update There is a new neo4j driver for R that looks promising: http://nicolewhite.github.io/RNeo4j/. I changed the correct answer.
This link might be helpful. I'm going to connect ne04j with R in the following days and will try first with the provided link. Hope it helps. I tried it out and it works well. Here is the function that works: First, install and load packages and then execute function: install.packages('RCurl') install.packages('RJSONIO') library('bitops') library('RCurl') library('RJSONIO') query <- function(querystring) { h = basicTextGatherer() curlPerform(url="localhost:7474/db/data/ext/CypherPlugin/graphdb/execute_query", postfields=paste('query',curlEscape(querystring), sep='='), writefunction = h$update, verbose = FALSE ) result <- fromJSON(h$value()) #print(result) data <- data.frame(t(sapply(result$data, unlist))) print(data) names(data) <- result$columns } and this is an example of calling function: q <-"start a = node(50) match a-->b RETURN b" data <- query(q)
Neo4j
11,188,918
17
I'm new to Neo4J and couldn't find the answer to my question despite my hours of googling. So far, I have been following the tutorials and now I have a basic understanding of how/when to use Neo4j. Now, I am about to start modifying my hello-world code and connect to a Neo4J server locally installed on my machine, accessible via http://127.0.0.1:7474. Original connection (using an embedded database): GraphDatabaseService gdb = new EmbeddedGraphDatabase("c:\\helloworld\\data\\graph.db"); The question is is there anyway to modify this line to connect to my "server" database in c:\neo4j\data\graph.db instead? The server is running currently as a windows service and I can view its database using the web admin tool. At this time, I am not interested in using the REST API since the server and the client app are running on the same machine. I feel like I'm missing something obvious here...
I couldn't find any example code on the wrapper so here is what I ended up doing. EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase("C:\\neo4j\\data\\graph.db"); WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper(graphDb); srv.start(); try { while (System.in.read() != 46) { // wait until we send a period (.) to kill the server } } catch (IOException e) {} srv.stop(); This will allow you to visit localhost:7474 and see the webadmin tool just like running the server but also continue with your usual Java code (write your own simple API using the input stream to read commands).
Neo4j
9,386,013
17
I just started to learn Neo4j.However, I come across a problem when connecting to Neo4j at the very beginning. As the image shown, it says "The client is unauthorized due to authentication failure." Any solutions?
For the command line, there is same situation. Give username and pass as argument. Like: -u neo4j -p neo4j
Neo4j
41,855,424
16
When should I choose Neo4j’s traversal framework over Cypher? For example, for a friend-of-a-friend query I would write a Cypher query as follows: MATCH (p:Person {pid:'56'})-[:FRIEND*2..2]->(fof) WHERE NOT (p)-[:FRIEND]->(fof) RETURN fof.pid And the corresponding Traversal implementation would require two traversals for friends_at_depth_1 and friends_at_depth_2 (or a core API call to get the relationships) and find the difference of these two sets using plain java constructs, outside of the traversal description. Correct me if I’m wrong here. Any thoughts?
The key thing to remember about Cypher vs. the traversal API is that the traversal API is an imperative way of accessing a graph, and Cypher is a declarative way of accessing a graph. You can read more about that difference here but the short version is that in imperative access, you're telling the database exactly how to go get the graph. (E.g. I want to do a depth first search, prune these branches, stop when I hit certain nodes, etc). In declarative graph query, you're instead specifying what you want, and you're delegating all aspects of how to get it to the Cypher implementation. In your query, I'd slightly revise it: MATCH (p:Person {pid:'56'})-[:FRIEND*2..2]->(fof) WHERE NOT (p)-[:FRIEND]->(fof) AND p <> fof RETURN fof.pid (I added making sure that p<>fof because friend links might go back to the original person) To do this in a traverser, you wouldn't need to have two traverser, just one. You'd traverse only FRIEND relationships, stop at depth 2, and accumulate a set of results. Now, I'm going to attempt to argue that you should almost always use Cypher, and never use the traversal API unless you have very specific circumstances. Here are my reasons: Declarative query is very powerful, in that it frees you from thinking about the how. All you need to know is what you want. This means you spend more time focusing on what your code is supposed to do, and less time in implementation detail. The cypher query executor is getting better all the time (version 2.2 will have a cost based planner) and of course they put a lot of effort into making sure cypher exploits all available indexes. I'ts possible that for many queries, cypher would do a better job of finding your data than your traversal, unless you were very careful in coding the traversal. Cypher is just way less code than writing your own traversal, which will frequently require you to implement certain classes to do specialized stop conditions, etc. At present, cypher can run in embedded databases, or on the server. If you want to run a traversal, you can't send that remotely to a server to be executed; maybe at best you could write a server extension that did the traversal. So I think cypher is more flexible at present. OK so when should you use traversal? Two key cases that I know of (others may suggest others) Sometimes you need to execute a complex custom java code operation on everything you traverse. In this case, you're using the traverser as a "visitor function" of sorts, and sometimes traversals are more convenient to use than cypher, depending on the nature of the java you're running on the nodes. Sometimes your performance requirements are so intense, you need to hand-traverse the graph, because there's some aspect of graph structure that you can exploit in the traverser to make it go faster that Cypher can't take advantage of. This does happen, but going to this first usually isn't a good idea.
Neo4j
28,657,178
16
I'm trying to implement the logic in Cypher where, based on a particular condition (CASE Statement), I would create some nodes and relationships; the code is as below MATCH (g:Game)-[:PLAYER]->(u:User)-[r1:AT]->(b1:Block)-[:NEXT]->(b2:Block) WHERE g.game_id='G222' and u.email_id = '[email protected]' and b1.block_id='16' SET r1.status='Skipped', r1.enddate=20141225 WITH u, b2,b1, g, r1 SET b1.test = CASE b2.fork WHEN 'y' THEN MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1 ELSE MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2) RETURN 2 END WITH u, g MATCH (u)-[:TIME]->(h:Time)<-[:TIME]-(g) SET h.after = 0 SET h.before = h.before + 1 In this query there is a merge statement within the WHEN 'y' THEN, this query throws an error: Invalid input ']': expected whitespace or a relationship pattern (line 7, column 82) "MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1" Basically I'm trying to create a relationship based on a property i.e. a MERGE within a CASE statement, I tried different ways to get this working like doing a return so that case when returns some value etc. but nothing worked so far. What could be the issue with this query?
To do conditional write operations you need to use the FOREACH trick. Using CASE you either return a one element array or a empty one. FOREACH iterates over the CASE expression and therefore conditionally executes the action. If you want an ELSE part as well you need to have a another FOREACH using the inverse condition in the CASE. As an example, instead of WHEN 'y' THEN MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1 ELSE MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2) RETURN 2 END use FOREACH(ignoreMe IN CASE WHEN 'y' THEN [1] ELSE [] END | MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) ) FOREACH(ignoreMe IN CASE WHEN NOT 'y' THEN [1] ELSE [] END | MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2) ) See also Mark's blog post on this.
Neo4j
27,576,427
16
I've seen a topic (Understanding Neo4j Cypher Profile keyword and execution plan) where profile keyword is mentioned. I couldn't use it in Neo4j 2.0.0RC1 Community. Peter wrote it's not fully implemented. Will it ever be supported? I mean, it could be interesting to watch the plan changes as we tune the query...
You can still find the neo4j shell, where you can run the profile command. Either by connecting to the running server by starting bin/neo4j-shell Or by switching to the old web-ui in the "(i)" Info-menu on the left side and selecting the bottommost link "webadmin" -> http://localhost:7474/webadmin Profiling information will be added to browser later on, when it is easier to read and understand.
Neo4j
20,628,663
16
I can't find the data directory for my Neo4j Enterprise installation. I have looked at the config files and understand that it is in the data/graph.db file. What is the default fully qualified path of the neo4j data directory?
The fully qualified path to the Neo4j 2.0M6 data directory on Ubuntu 12.04 is '/var/lib/neo4j/data' The path is also shown at the bottom of the 'Database Information' panel in the Neo4j Browser.
Neo4j
20,083,966
16
I've been using RDBMSes since college and am really struggling with the underlying concepts of NoSQL databases...but I think their concept is really cool. I believe I understand the following (please correct me if I'm wrong, because these play into my question here!): NoSQL is not some formal specification; it is a concept underlying a new "breed" of databases that are not relational and do not use SQL As such, each NoSQL system is different (for instance, MongoDB is JSON-centric) If these are true, then let us redirect our attention to Neo4j, a "graph-based" database. After perusing the site and the PDF, it seems like Neo4j is not only a database, but it also provides a Java API that essentially replaces the need for traditional ORM tools like Hibernate. So, my final question is actually a request for clarification/confirmation of that last assertion, specifically: Is it true that if my backend is entirely Neo4j-based, that I would have no need for Hibernate (which is my usual ORM)? Are these two APIs mutually-exclusive, or is there some way to benefit between using both of them? Thanks in advance!
I've been using RDBMSes since college and am really struggling with the underlying concepts of NoSQL databases...but I think their concept is really cool. A graph database like Neo4j expresses a domain in terms of vertices connected to other vertices with edges. An edge contains its start and end vertex. Each vertex and edge can have a map of properties, key-value pairs that can be used to store additional information about the vertices and edges. You can, of course, extend this with your own domain, but things are simple to start out. To see these concepts in action, I recommend the Getting Started Guide for Gremlin. Gremlin is a domain-specific language for traversing graphs that works with Neo4j and several other graph databases. Gremlin is to a graph database what SQL is to a relational database. I can't recommend Gremlin strongly enough while you're learning about graphs. In just a few minutes, you can be up and running working through the Gremlin tutorials. Gremlin will provide you with a REPL that will let you experiment with small graphs and get immediate feedback. Even if you don't use Gremlin in your production system, the knowledge gained at the REPL will help you validate your designs and can serve as a precursor to more rigorous unit testing and development. If you prefer working directly with Neo4j's API's, their traversal framework tutorial should help. Is it true that if my backend is entirely Neo4j-based, that I would have no need for Hibernate (which is my usual ORM)? Since you're new to Neo4j, I would recommend that you avoid ORM's until you first understand what the ORM needs to do for you. See how much pain you're really going to experience mapping the results of your query to your domain. If the pain can be ameliorated by an ORM, the Spring-Data framework mentioned by Peter may be useful. In all likelihood, you will probably be just fine. I have worked on several projects where the accidental complexity introduced by the ORM far outweighed the benefits. Mapping the query results to the domain was in no way the most complicated part of the system.
Neo4j
9,196,276
16
In neo4j, how can I index by date and search in a date range. Also for times, I would like to search between 8am and 9am in a date range as well.
Index the dates and times as integer timestamps. Then you can easily search in an index for dates between other timestamps. You can also index the time part of the timestamp separately as another integer, allowing you to query for specific times between given dates. Example: The date and time to store is "2012-02-05 8:15 AM" So in your index, store "timestamp=1328447700" and "time=815" Now you want to query the index for all events between 2012-02-01 and 2012-02-10 that occurred from 8:00 am to 9:00 am. You do that by querying the index for "timestamp>=1328072400 and timestamp<=1328936399 and time>=800 and time<=900" The exact syntax for doing this depends on how you are connecting to Neo4j (REST or embedded) and which programming language you are using. But the idea is the same in any case.
Neo4j
9,138,857
16
We're currently in the process of implementing a CRM-like solution internally for a professional firm. Due to the nature of the information stored, and the varying values and keys for the information we decided to use a document storage database, as it suited the purposes perfectly (In this case we chose MongoDB). As part of this CRM solution we wish to store relationships and associations between entities, examples include storing conflicts of interest information, shareholders, trustees etc. Linking all these entities together in the most effective way we determined a central model of "relationship" was necessary. All relationships should have history information attached to them ( commencement and termination dates), as well as varying meta data; for example a shareholder relationship would also contain number of shares held. As traditional RDBMS solutions didn't suit our former needs, using them in our current situation is not viable. What I'm trying to determine is whether using a graph database is more pertinent in our case, or if in fact just using mongo's built-in relational information is appropriate. The relationship information is going to be used quite heavily throughout the system. An example of some of the informational queries we wish to perform are: Get all 'key contact' people of companies who are 'clients' of 'xyz limited' Get all other 'shareholders' of companies where 'john' is a shareholder Get all 'Key contact' people of entities who are 'clients' of 'abc limited' and are clients of 'trust us bank limited' Given this "tree" structure of relationships, is using a graph database (such as Neo4j) more appropriate?
Mike, you should be able to store your relationship data in the graph database. Its high performance on traversing big graphs comes from locality, i.e. you don't run queries globally but rather start a a set of nodes (which equal documents in your case, which are looked up by an index. you might even store start-node-ids for quick access in your mongo documents). From there you can traverse arbitrarily large paths in constant time (wrt data set size). What are your other requirements (i.e. data set size, # of concurrent accesses etc, relationship/graph complexity). Your queries are a really good fit for the graph database and easily expressable in its terms. I'd suggest that you just grab a graphdb like neo4j and do a quick spike with your domain to verify the general feasibility and also find out additional questions you would like to have answered before investing in the second technology. P.S. If you hadn't started yet, you could also have gone with a pure graphdb approach as graph databases are a superset of document databases. And you'd rather talk domain in your case anyway than just generic documents. (E.g. structr is a CMS built on top of Neo4j).
Neo4j
5,817,182
16
Suppose there is a node, Student, that has a property Name. MATCH (s:Student) were s.Name contains "stack" RETURN s.Name the output should be like : stack, Stack, STACK etc
You can make the comparison on the upper/lower case version of each, for example: MATCH (s:Student) WHERE toLower(s.Name) CONTAINS toLower("stack") RETURN s.Name
Neo4j
45,212,213
15
Is there a way to return just an integer through cypher? I am working with neo4j and the javascript driver. However when I do a count() I get {low: 10, high: 0}. I would like to force this to return a low integer instead of the object above. Is this possible through cypher? Note that I don't want to do this in the neo4j javascript driver and prefer to do this in cypher since I know it will be a low number...
Starting from 1.6 version of the driver it is possible to configure it to only return native numbers instead of custom Integer objects. The configuration option affects all integers returned by the driver. Enabling this option can result in a loss of precision and incorrect numeric values being returned if the database contains integer numbers outside of the range [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]. const driver = neo4j.driver( 'neo4j://localhost', neo4j.auth.basic('neo4j', 'neo4j'), { disableLosslessIntegers: true } ) Keep in mind that MAX_SAFE_INTEGER is 2^53-1 = 9,007,199,254,740,991. Sources: Neo4j JS Driver on Github - Numbers and the Integer type Neo4j JS Driver on Github - Enabling native numbers
Neo4j
42,645,342
15
I execute a long running (5 mintues) Cypher query with py2neo 2.0: graph.cypher.run(query) or result = graph.cypher.execute(query) The query fails after ~60 sec with a Socket Error from httpstream: ERROR:httpstream:! SocketError: timed out The same happens when I use a Cypher transaction. This did not happen with the same query and py2neo 1.6.4. Can I increase the time py2neo waits for a response? I didn't find anything in the docs. Update I found a hard coded socket_timeout in py2neo.packages.httpstream.http. Setting it to a higher value avoids the SocketError: from py2neo.packages.httpstream import http http.socket_timeout = 9999 result = graph.cypher.execute("MATCH (g:Gene) RETURN count(g)") Can I somehow set the timeout for a single query?
There's currently no way to adjust the timeout for individual queries as this setting applies at a connection level and one connection can obviously be used for many queries. The socket_timeout you're using is the correct way to adjust the timeout globally though.
Neo4j
27,078,352
15
I'm trying to list all of the properties for a set of nodes. Match (n:"Indicator") return properties(n), ID(n) I'm unsure of the syntax and couldn't find the answer in the refcard or docs.
In Neo4j version 3.0.0 you may do: Match (n:Indicator) return properties(n), ID(n) To return the ID and properties of nodes.
Neo4j
23,066,853
15
Imagine a photo album schema w/ Users, Albums, and Photos: User -[owns]-> Album -[contains]-> Photo Can I do a nested collect to get Photos nested in Albums, and Albums nested in User? I'd like results similar to: { "users": [ { "name": "roger dodger", "albums": [ { "album": "album1", "photos": [ {"url": "photo1.jpg"}, {"url": "photo2.jpg"} ] } ] } ] } This seems close but I could not modify it to suit my needs: Nested has_many relationships in cypher (Could the problem be that neo4j 2.0 web console doesn't support the json syntax in that example?)
Try this query: MATCH (a:USER)-[:owns]->(b:ALBUM)-[:CONTAINS]->(c:PHOTO) WITH a,b,{url: c.name} as c_photos WITH a,{album: b.name , photos: collect(c_photos)} as b_albums WITH {name: a.name, albums: collect(b_albums)} as a_users RETURN {users: collect(a_users)} Edit To get all properties of a node you can use string representation of the node and then parse it separately using java etc MATCH (a:User) WITH {user: str(a)} as users RETURN {users: collect(users)}
Neo4j
21,896,382
15
The graph schema I have is (actors)-[:ACTED_IN]->(movies). I know how to find actors who have worked with a particular actor as below: MATCH (actor {name:"Tom Hanks"} )-[:ACTED_IN]->(movies)<-[:ACTED_IN]-(costars) return distinct costars; I know how to find all the actors who have worked in some movie: MATCH (all_actor)-[:ACTED_IN]->(movies) return distinct all_actor; However I don't know how to find all actors not in costars. How do I go about it?
As you want to deduct the coactors from the global list of actors this is not the best graph query, here are some suggestions. // Max de Marzi MATCH (actor:Actor {name:"Tom Hanks"})-[:ACTED_IN]->(movie), (other:Actor) WHERE NOT (movie)<-[:ACTED_IN]-(other) RETURN other // Wes Freeman MATCH (actor:Actor {name:"Tom Hanks"}), (other:Actor) WHERE NOT (actor)-[:ACTED_IN]->()<-[:ACTED_IN]-(other) RETURN other // Michael Hunger MATCH (actor:Actor {name:"Tom Hanks"} )-[:ACTED_IN]->(movies)<-[:ACTED_IN]-(coactor) WITH collect(distinct coactor) as coactors MATCH (actor:Actor) WHERE NOT actor IN coactors RETURN actor
Neo4j
21,185,463
15
When you install 1.9.4 using the new Windows installer, from where does one launch the Neo4j-Shell (previously found in bin)?
The neo4j-shell isn't currently shipping with the neo4j desktop but you can launch it by running the following command from 'C:\Program Files\Neo4j Community\' (or equivalent location:): jre\bin\java -classpath bin\neo4j-desktop-1.9.4.jar org.neo4j.shell.StartClient I'm not sure whether there are plans to include it in the next release, I'll check.
Neo4j
19,255,500
15
Given a query like the following: START n = node(123) MATCH p = n-[r:LIKES*..3]->x RETURN p; The result paths that I get with the query above contain cycles. How can I return only simple paths? Given this example: How can I avoid paths with repeated nodes like: [Neo, Morpheus, Trinity, Morpheus, Neo]
Specifying the uniqueness of paths is a planned feature of cypher. So right now we have to ascertain that no node is a duplicate in the path. There is an ALL predicate that must hold true for all elements of a collection (which a path is). And with filter you can extract the elements of an collection for that a certain condition holds true. START neo=node(1) MATCH path= neo-[r:KNOWS*..4]->other WHERE ALL(n in nodes(path) where 1=length(filter(m in nodes(path) : m=n))) RETURN neo, LENGTH(path) AS length, EXTRACT(p in NODES(path) : p.name), other ORDER BY length So what I did was: For all nodes of the path n Filter the path for the nodes that are equal to n determine the length of that collection assert with ALL that it has to be ONE for each n see: http://console.neo4j.org/r/dpalbl
Neo4j
13,767,748
15
I'm curious about naming conventions in neo4j. I noticed in their examples that relationship names where capitalized, e.g. left-[r:KNOWS]->right Is that the convention? Is neo4j case sensitive in relationship names? Are there other naming conventions around index names and property names?
That is the convention. I personally use lower case relationship types, and yes, it is case-sensitive. With underscores. Usually, people use underscores for index names as well, and they're usually lower case, and also case-sensitive. Also, something to remember: if you don't specify direction while creating, the default is left<--right. Not intuitive for me, but now I just specify direction always. For the properties, I think most people use JSON style conventions: http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml#Key_Names_in_JSON_Maps I've also seen underscores for properties, so I guess it goes either way. Just be consistent!
Neo4j
13,483,487
15
I have a simple setup and encountered a puzzling (at least for me) problem: I have three pojos which are related to each other: @NodeEntity public class Unit { @GraphId Long nodeId; @Indexed int type; String description; } @NodeEntity public class User { @GraphId Long nodeId; @RelatedTo(type="user", direction = Direction.INCOMING) @Fetch private Iterable<Worker> worker; @Fetch Unit currentUnit; String name; } @NodeEntity public class Worker { @GraphId Long nodeId; @Fetch User user; @Fetch Unit unit; String description; } So you have User-Worker-Unit with a "currentunit" which marks in user that allows to jump directly to the "current unit". Each User can have multiple workers, but one worker is only assigned to one unit (one unit can have multiple workers). What I was wondering is how to control the @Fetch annotation on "User.worker". I actually want this to be laoded only when needed, because most of the time I only work with "Worker". I went through http://static.springsource.org/spring-data/data-neo4j/docs/2.0.0.RELEASE/reference/html/ and it isn't really clear to me: worker is iterable because it should be read only (incoming relation) - in the documentation this is stated clarly, but in the examples ''Set'' is used most of the time. Why? or doesn't it matter... How do I get worker to only load on access? (lazy loading) Why do I need to annotate even the simple relations (worker.unit) with @Fetch. Isn't there a better way? I have another entity with MANY such simple relations - I really want to avoid having to load the entire graph just because i want to the properties of one object. Am I missing a spring configuration so it works with lazy loading? Is there any way to load any relationships (which are not marked as @Fetch) via an extra call? From how I see it, this construct loads the whole database as soon as I want a Worker, even if I don't care about the User most of the time. The only workaround I found is to use repository and manually load the entities when needed. ------- Update ------- I have been working with neo4j quite some time now and found a solution for the above problem that does not require calling fetch all the time (and thus does not load the whole graph). Only downside: it is a runtime aspect: import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mapping.model.MappingException; import org.springframework.data.neo4j.annotation.NodeEntity; import org.springframework.data.neo4j.support.Neo4jTemplate; import my.modelUtils.BaseObject; @Aspect public class Neo4jFetchAspect { // thew neo4j template - make sure to fill it @Autowired private Neo4jTemplate template; @Around("modelGetter()") public Object autoFetch(ProceedingJoinPoint pjp) throws Throwable { Object o = pjp.proceed(); if(o != null) { if(o.getClass().isAnnotationPresent(NodeEntity.class)) { if(o instanceof BaseObject<?>) { BaseObject<?> bo = (BaseObject<?>)o; if(bo.getId() != null && !bo.isFetched()) { return template.fetch(o); } return o; } try { return template.fetch(o); } catch(MappingException me) { me.printStackTrace(); } } } return o; } @Pointcut("execution(public my.model.package.*.get*())") public void modelGetter() {} } You just have to adapt the classpath on which the aspect should be applied: my.model.package..get())") I apply the aspect to ALL get methods on my model classes. This requires a few prerequesites: You MUST use getters in your model classes (the aspect does not work on public attributes - which you shouldn't use anyways) all model classes are in the same package (so you need to adapt the code a little) - I guess you could adapt the filter aspectj as a runtime component is required (a little tricky when you use tomcat) - but it works :) ALL model classes must implement the BaseObject interface which provides: public interface BaseObject { public boolean isFetched(); } This prevents double-fetching. I just check for a subclass or attribute that is mandatory (i.e. the name or something else except nodeId) to see if it is actually fetched. Neo4j will create an object but only fill the nodeId and leave everything else untouched (so everything else is NULL). i.e. @NodeEntity public class User implements BaseObject{ @GraphId private Long nodeId; String username = null; @Override public boolean isFetched() { return username != null; } } If someone finds a way to do this without that weird workaround please add your solution :) because this one works, but I would love one without aspectj. Base object design that doenst require a custom field check One optimization would be to create a base-class instead of an interface that actually uses a Boolean field (Boolean loaded) and checks on that (so you dont need to worry about manual checking) public abstract class BaseObject { private Boolean loaded; public boolean isFetched() { return loaded != null; } /** * getLoaded will always return true (is read when saving the object) */ public Boolean getLoaded() { return true; } /** * setLoaded is called when loading from neo4j */ public void setLoaded(Boolean val) { this.loaded = val; } } This works because when saving the object "true" is returned for loaded. When the aspect looks at the object it uses isFetched() which - when the object is not yet retrieved will return null. Once the object is retrieved setLoaded is called and the loaded variable set to true. How to prevent jackson from triggering the lazy loading? (As an answer to the question in the comment - note that I didnt try it out yet since I did not have this issue). With jackson I suggest to use a custom serializer (see i.e. http://www.baeldung.com/jackson-custom-serialization ). This allows you to check the entity before getting the values. You simply do a check if it is already fetched and either go on with the whole serialization or just use the id: public class ItemSerializer extends JsonSerializer<BaseObject> { @Override public void serialize(BaseObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // serialize the whole object if(value.isFetched()) { super.serialize(value, jgen, provider); return; } // only serialize the id jgen.writeStartObject(); jgen.writeNumberField("id", value.nodeId); jgen.writeEndObject(); } } Spring Configuration This is a sample Spring configuration I use - you need to adjust the packages to your project: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> <context:spring-configured/> <neo4j:repositories base-package="my.dao"/> <!-- repositories = dao --> <context:component-scan base-package="my.controller"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <!-- that would be our services --> </context:component-scan> <tx:annotation-driven mode="aspectj" transaction-manager="neo4jTransactionManager"/> <bean class="corinis.util.aspects.Neo4jFetchAspect" factory-method="aspectOf"/> </beans> AOP config this is the /META-INF/aop.xml for this to work: <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver> <!-- only weave classes in our application-specific packages --> <include within="my.model.*" /> </weaver> <aspects> <!-- weave in just this aspect --> <aspect name="my.util.aspects.Neo4jFetchAspect" /> </aspects> </aspectj>
Found the answer to all the questions myself: @Iterable: yes, iterable can be used for readonly @load on access: per default nothing is loaded. and automatic lazy loading is not available (at least as far as I can gather) For the rest: When I need a relationship I either have to use @Fetch or use the neo4jtemplate.fetch method: @NodeEntity public class User { @GraphId Long nodeId; @RelatedTo(type="user", direction = Direction.INCOMING) private Iterable<Worker> worker; @Fetch Unit currentUnit; String name; } class GetService { @Autowired private Neo4jTemplate template; public void doSomethingFunction() { User u = ....; // worker is not avaiable here template.fetch(u.worker); // do something with the worker } }
Neo4j
8,852,491
15
I'm starting on a new project that has some hierarchical data and I'm looking at all the options for storing that in a database at the moment. I am using PostgreSQL, which does allow recursive querying. I also looked into design patterns for relational databases, such as closure tables and I had a look at graph database solutions such as neo4j. I'm finding it difficult to decide between those options. For example: given that my RDBMS allows recursive queries, would it still make sense to use closure tables and how does that compare to graph database solutions in terms of maintainability and performance? Any opinions/experience would be much appreciated!
The whole closure table is redundant if you can use recursive queries :) I think it's much better to have a complicated recursive query that you have to figure out once than deal with the extra IO (and disk space) of a separate table and associated triggers. I have done some simple tests with recursive queries in postgres. With a few million rows in the table queries were still < 10ms for returning all parents of a particular child. Returning all children was fast too, depending on the level of the parent. It seemed to depend more on disk IO fetching the rows rather than the query speed itself. This was done single user, so not sure how it would perform under load. I suspect it would be very fast still if you can also hold most of the table in memory (and setup postgres correctly). Clustering the table by parent id also seemed to help.
Neo4j
7,497,812
15
I have found that relational databases are a very good fit for Clojure as the set functions (project/join/union etc) map very nicely to a database schema making Clojure almost a perfect fit for using with databases. I was wondering how Clojure fits in with graph databases like Neo4j however?
Neo4J has clojure'ey bindings here and here and here you can get the leiningen and maven config for each of these from clojars allegrograph is another similar graph data store that is widely supported in clojure. so there is some evidence that the answer may be yes! graph stores lend them selves well to immutable trees which may be an even better fit to Clojure than sets but this is all fairly subjective. The most objective answer I can give is to point to existing use of graph-stores/triple-stores.
Neo4j
5,680,976
15
I want to translate a SQL query to cypher. Please, is there any solution to make GROUP BY in cypher? SELECT dt.d_year, item.i_brand_id brand_id, item.i_brand brand, Sum(ss_ext_discount_amt) sum_agg FROM date_dim dt, store_sales, item WHERE dt.d_date_sk = store_sales.ss_sold_date_sk AND store_sales.ss_item_sk = item.i_item_sk AND item.i_manufact_id = 427 AND dt.d_moy = 11 GROUP BY dt.d_year, item.i_brand, item.i_brand_id ORDER BY dt.d_year, sum_agg DESC, brand_id;
In Cypher, GROUP BY is done implicitly by all of the aggregate functions. In a WITH/RETURN statement, any columns not part of an aggregate will be the GROUP BY key. So for example in MATCH (n:Person) RETURN COUNT(n), n.name, n.age The count will count all nodes that have the same name and age. If I instead do MATCH (n:Person) RETURN COUNT(n), n.name, MIN(n.age), MAX(n.age) I will get the count of how many people have the same name, as well as the age range for that name.
Neo4j
52,722,671
14
I'm researching graph databases for a work project. Since our data is highly connected, it appears that a graph database would be a good option for us. One of the first graph DB options I've run into is neo4j, and for the most part, I like it. However, I have one question about neo4j to which I cannot find the answer: Can I get neo4j to store the entire graph in-memory? If so, how does one configure this? The application I'm designing needs to be lightning-fast. I can't afford to wait for the db to go to disk to retrieve the data I'm searching for. I need the entire DB to be held in-memory to reduce the query time. Is there a way to hold the entire neo4j DB in-memory? Thanks!
Further to Bruno Peres' answer, if you want to run a regular server instance, Neo4j will load the entire graph into memory when resources are sufficient. This does indeed improve performance. The Manual has a chapter on configuring memory. The page cache portion holds graph data and indexes - this is configured via the dbms.memory.pagecache.size property in neo4j.conf. If it is large enough, the whole graph will be stored in memory. The heap space portion is for query execution, state management, etc. This is set via the dbms.memory.heap.initial_size and dbms.memory.heap.max_size properties. Generally these two properties should be set to the same value, so that the whole heap is allocated on startup. If the sole purpose of the server is to run Neo4j, you can allocate most of the memory to the heap and page cache, leaving enough left over for operating system tasks. Holding Very Large Graphs In Memory At Graph Connect in San Francisco, 2016, Neo4j's CTO, Jim Webber, in his typical entertaining fashion, gave details on servers that have a very large amount of high performance memory - capable of holding an entire large graph in memory. He seemed suitably impressed by them. I forget the name of the machines, but if you're interested, the video archive should have details.
Neo4j
47,764,067
14
I'm trying out the golang-neo4j-bolt-driver package github.com/johnnadratowski/golang-neo4j-bolt-driver I have imported the package and am using the example way of creating a new driver: driver := bolt.NewDriver() i get the following: ./neo.go:5: imported and not used: "github.com/johnnadratowski/golang-neo4j-bolt-driver" as golangNeo4jBoltDriver ./neo.go:34: undefined: bolt in bolt.NewDriver any pointers would be appreciated
You will want to alias the name of the library bolt "github.com/johnnadratowski/golang-neo4j-bolt-driver" You can see this in their code examples
Neo4j
42,818,747
14
I have a column in a csv that looks like this: I am using this code to test how the splitting of the dates is working: LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line WITH SPLIT(line.date_of_birth, '/') AS date_of_birth return date_of_birth; This code block works fine and gives me what I'd expect, which is a collection of three values for each date, or perhaps a null if there was no date ( e.g, [4, 5, 1971] [0, 0, 2003] [0, 0, 2005] . . . null null . . . My question is, what is this problem with the nulls that are created, and why can't I do a MERGE when there are nulls? LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line WITH SPLIT(line.date_of_birth, '/') AS date_of_birth, line MERGE (p:Person { date_of_birth: date_of_birth }); This block above gives me the error: Cannot merge node using null property value for date_of_birth I have searched around and have only found one other SO question about this error, which has no answer. Other searches didn't help. I was under the impression that if there isn't a value, then Neo4j simply doesn't create the element. I figured maybe the node can't be generated since, after all, how can a node be generated if there is no value to generate it from? So, since I know there are no ID's missing, maybe I could MERGE with ID and date, so Neo4j always sees a value. But this code didn't fare any better (same error message): LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line WITH SPLIT(line.date_of_birth, '/') AS date_of_birth, line MERGE (p:Person { ID: line.ID ,date_of_birth: date_of_birth }); My next idea is that maybe this error is because I'm trying to split a null value on slashes? Maybe the whole issue is due to the SPLIT. But alas, same error when simplified to this: LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line WITH line MERGE (p:Person { subject_person_id: line.subject_person_id ,date_of_birth: line.date_of_birth }); So I don't really understand the cause of the error. Thanks for looking at this. EDIT Both @stdob-- and @cybersam have both answered with equally excellent responses, if you came here via Google please consider them as if both were accepted
As @cybersam said,MERGE doesn't work well with queries where the properties are set within the scope in null. So, you can use ON CREATE and ON MATCH: LOAD CSV WITH HEADERS FROM 'file:///..some_csv.csv' AS line MERGE (p:Person { subject_person_id: line.subject_person_id }) ON CREATE SET p.date_of_birth = line.date_of_birth ON MATCH SET p.date_of_birth = line.date_of_birth
Neo4j
37,081,842
14
I want to build a social network. (E.g. Persons have other persons as friends) and I guess a graph database would do the trick better than a classic database. I would like to store attributes on the edges and on the nodes. They can be json, but I do not care if the DB understands JSON. ArangoDB can also store documents and Neo4J is "only" a graph Database. I would like to have an user node an to each person 2 eg. Users -[username]-> person Users -[ID]-> person And there is a need that there is an index on the edges. I do not want a different database, so it would be nice to store an image (byte array) in the database, maybe even different sizes for each image / video whatever. Also posts and such should be stored in the database. What I got is that Neo4j better supports an manufacture independent query language, but I guess it is easier and better to learn the manufacturer standard. Any recommendations on which database management system is better suited? I will be writing the code in Java (and some Scala).
Both ArangoDB and Neo4j are capable of doing the job you have in mind. Both projects have amazing documentation and getting answers for either of them is easy. Both can be used from Java (though Neo4j can be embedded). One thing that might help your decision making process is recognizing that many NoSQL databases solve a much narrower problem than people appreciate. Sarah Mei wrote an epic blog post about MongoDB, using an example with some data about TV shows. From the summary: MongoDB’s ideal use case is even narrower than our television data. The only thing it’s good at is storing arbitrary pieces of JSON. I believe that Neo4j solves a similarly narrow problem, as evidenced by how common it is to use Neo4j alongside some other data store. I don't know that storing picture or video data is a great idea in either ArangoDB or Neo4j. I would look to store it on some other server (like S3) and save the url to that file in Neo4j/Arango. While it's true that it is possible to create queries that only a graph database can answer, the performance of graph database on any given query varies wildly and can give you some pretty surprising results. For instance, here is a paper from the International Journal of Computer Science and Information Technologies doing a comparison of Neo4j vs MySQL, Vertica and VoltDB with queries you would assume Neo4j would be amazing at: The idea is that a "social network" does not automatically imply the superiority, or even the use of a graph database (especially since GraphQL and Falcor were released). To address your question about query languages. There is no standard language for graph databases. AQL is a query language that provides a unified interface for working with key/value, document and graph data. Cypher is a graph query language. Badwolf Query Language is a SPARQL inspired language for temporal graphs. These languages exist because they tackle different problems. The databases that support them also tackle different problems. Neo4j has an example of "polyglot persistence" on their site: I think that is the problem that ArangoDB and AQL is out to solve, the hypothesis being that it's possible to solve that without being worse than specialists like Neo4j. So far it looks like they might be right.
Neo4j
35,118,458
14
What is the behaviour and purpose of the new Cypher operator DETACH DELETE added in Neo4j 2.3.x?
If you want to delete nodes, you need to delete the relationships as well. In previous versions you would need to do: MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n, r Now you can simply say: MATCH (n) DETACH DELETE n
Neo4j
33,139,903
14
Single relationships can be excluded by types using Match (n:Person)-[r]-(m:Person) where type(r)<>"FRIENDS" return n,r,m Is there a way to exclude multilevel relationships with cypher? Match (n:Person)-[r*2..4]-(h:Hobby) where type(r)<>"FRIENDS" return n,r,h
Sure, you can do that. Like this: Match (n:Person)-[r*2..4]-(h:Hobby) where NONE( rel in r WHERE type(rel)="FRIENDS") return n,r,h Your query doesn't work because with multi-level paths, your r is a collection of relationships rather than a single one. So you can use any of the predicates on collections to do the filtering that you want. Here, I chose NONE with type(rel)=FRIENDS, which means that you'll only get the result back if NONE of the relationships are of type FRIENDS. But you might instead want to use ANY or ALL, depending on what your query is supposed to mean. Anyway, the main point here is to use a predicate function to turn a collection of things into a single boolean value.
Neo4j
31,746,120
14
I have a set of nodes with a property, myproperty = "James" I want to update that property from (myproperty) to (name). Is there any way to this with Cypher?
Solved by myself, heres what I did: MATCH (n:term) SET n.name = n.label REMOVE n.label RETURN n
Neo4j
22,821,714
14
I've got a property quantity on our Product-nodes and am looking to do a cypher query that gives me all nodes with quantity = 20 ... problem is that quantity is stored as a string in neo4j. Is there a way to cast the property to integer in the cypher query? // This fails to find the required nodes MATCH (p:Product) WHERE p.quantity = 20; // This finds them MATCH (p:Product) WHERE p.quantity = "20"; // I would like to do this MATCH (p:Product) WHERE INT(p.quantity) = 20; PS: this is a really simplified usecase, we don't really have products and quantities but are just faced with existing neo4j data that has integer values stored as strings, and we would like to do some matches on these strings
You can do it the other way round. MATCH (p:Product) WHERE p.quantity = str(20) RETURN p; should also work with params. MATCH (p:Product) WHERE p.quantity = str({quantity}) RETURN p; or even with inline property matches MATCH (p:Product {quantity : str({quantity})}) RETURN p;
Neo4j
21,132,844
14
Just wondering if anyone has any information on the status of project Rassilon, Neo4j's side project which focuses on improving horizontal scalability of Neo4j? It was first announced in January 2013 here. I'm particularly interested in knowing more about when the graph size limitation will be removed and when sharding across clusters will become available.
The node & relationship limits are going away in 2.1, which is the next release post 2.0 (which now has a release candidate). Rassilon is definitely still in the mix. That said, that work is not taking precedence over things like the significant bundle of new features that are in 2.0. The reason is that Neo4j as it stands today is extremely capable of scaling, using the variety of architecture features outlined below (with some live examples): www.neotechnology.com/neo4j-scales-for-the-enterprise/ There's lots of cleverness in the current architecture that allows the graph to perform & scale well without sharding. Because once you start sharding, you are destined to traverse over the network, which is a bad thing (for latency, query predictability etc.) So while there are some extremely large graphs that, largely for write throughput reasons, must trade off performance for uber scale (by sharding), the happy thing is that most graphs don't require this compromise. Sharding is required only in the 1% case, which means that nearly everyone can have their cake and eat it too. There are currently Neo4j clusters in production customers with 1B+ individuals in their graph, backing web applications with tens of millions of users. These use comparatively small (but very fast, very efficient) clusters. To give you some idea of the kinds of price-performance we regularly see: we've had users tell us that a single Neo4j instance could the same work as 10 Oracle instances, only faster. A well-tuned Neo4j cluster can support upwards of 10K transactional writes per second, and an arbitrarily high number of reads per second. Read throughput scales linearly as instances are elastically plugged in. Cache sharding is a design pattern that ensures that you don't have to keep the entire graph in memory.
Neo4j
20,198,982
14
In a Neo4j database with a couple of nodes and relationships, I am trying to find out the most "popular" users (in this case: The nodes participating in most relationships): START n=node:user('*:*') MATCH (n)-[r]->(x) RETURN n ORDER BY COUNT(r) DESC LIMIT 10 However, this query (Neo4j 1.9.2) results in the following error: ThisShouldNotHappenError Developer: Andres claims that: Aggregations should not be used like this. StackTrace: org.neo4j.cypher.internal.commands.expressions.AggregationExpression.apply(AggregationExpression.scala:31) org.neo4j.cypher.internal.commands.expressions.AggregationExpression.apply(AggregationExpression.scala:29) org.neo4j.cypher.internal.pipes.ExtractPipe$$anonfun$internalCreateResults$1$$anonfun$apply$1.apply(ExtractPipe.scala:47) org.neo4j.cypher.internal.pipes.ExtractPipe$$anonfun$internalCreateResults$1$$anonfun$apply$1.apply(ExtractPipe.scala:45) scala.collection.immutable.Map$Map1.foreach(Map.scala:109) org.neo4j.cypher.internal.pipes.ExtractPipe$$anonfun$internalCreateResults$1.apply(ExtractPipe.scala:45) org.neo4j.cypher.internal.pipes.ExtractPipe$$anonfun$internalCreateResults$1.apply(ExtractPipe.scala:44) scala.collection.Iterator$$anon$11.next(Iterator.scala:328) org.neo4j.cypher.internal.pipes.TopPipe.internalCreateResults(TopPipe.scala:45) org.neo4j.cypher.internal.pipes.PipeWithSource.createResults(Pipe.scala:69) org.neo4j.cypher.internal.pipes.PipeWithSource.createResults(Pipe.scala:66) org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl.org$neo4j$cypher$internal$executionplan$ExecutionPlanImpl$$prepareStateAndResult(ExecutionPlanImpl.scala:164) org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl$$anonfun$getLazyReadonlyQuery$1.apply(ExecutionPlanImpl.scala:139) org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl$$anonfun$getLazyReadonlyQuery$1.apply(ExecutionPlanImpl.scala:138) org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl.execute(ExecutionPlanImpl.scala:38) org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:72) org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:76) org.neo4j.cypher.javacompat.ExecutionEngine.execute(ExecutionEngine.java:79) org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:94) java.lang.reflect.Method.invoke(Method.java:611) org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112) Any ideas on how I can express this differntly?
In terms of neo4j mannual, if you need to use an aggregration in your "Order by", you must include the aggregration in your "Return", so you just need to add the count(r) in your "Return" as shown below, START n=node:user('*:*') MATCH (n)-[r]->(x) RETURN n, COUNT(r) ORDER BY COUNT(r) DESC LIMIT 10
Neo4j
18,329,904
14
I have the following graph as a Neo4j graph database: activates (80 Β°F) (A)------------------------------------->(D) | \__ _/->^ | \__ activates __/ | | \__(50 Β°F) __/ | | \__ __/ | | \__ __/ | activates | \__ __/ | (50 Β°F) | \/ | activates | __/\__ | (50 Β°F) | activates __/ \__ | | (60 Β°F)__/ \__ | | __/ \__ | | __/ \__ | | __/ \_ | v / \->| (B)------------------------------------->(C) activates (50 Β°F) Each relationship has a property denoting the required temperature for the 'activates' action. I need to retrieve all the available paths between (A) and (D) WHERE the temperature is 50 Β°F along the path. The output should include: A -[:activates{temperature:'50'}]-> B -[:activates{temperature:'50'}]-> C -[:activates{temperature:'50'}]-> D A -[:activates{temperature:'50'}]-> C -[:activates{temperature:'50'}]-> D but not A -[:activates{temperature:'80'}]-> D A -[:activates{temperature:'50'}]-> B -[:activates{temperature:'60'}]-> D How do I write the required Cypher query? Thanks in advance. Edit 1: I added another diagonal relationship (B -[:activates{temperature:'80'}]-> D) for more clarity. Edit 2: I need to retrieve all the available paths between (A) and (D) WHERE the temperature is the same along the path, i.e: A -> B -> C -> D, A -> C -> D, A -> D.
START a=node({A}), d=node({D}) MATCH p=a-[r:ACTIVATES*..]-d WHERE has(r.temperature) and r.temperature='50' RETURN p; substitute the values in the curved brackets (A,D) with their node IDs update: using function all START a=node(1), d=node(4) MATCH p=a-[r:ACTIVATES*..]-d WITH head(relationships(p))as r1,p //since the pointer r is a collection of rels we must declare a single relationship pointer WHERE all(r2 in relationships(p) where r2.temperature=r1.temperature) return p;
Neo4j
14,104,682
14
I changed the /ect file permissions on Ubuntu 12.10 so that i could edit bash.bashrc so that neo4j can see the JVM but now I am getting errors when i try run the neo4j server I entered the code below and I managed to edit bash.bashrc but now i cant use sudo at all! sudo chmod -R ugo+rw /ect sudo -u neo4j /home/neo4j-community-1.8/bin/neo4j start sudo: /etc/sudoers is world writable sudo: no valid sudoers sources found, quitting sudo: unable to initialize policy plugin I read a forum and a guy said I need to re-insatll ubuntu again, I hope this is not the case? Please HELP!!
I think i have sorted it out using this command pkexec chmod 0440 /etc/sudoers I can now do sudo -s root@ubuntu:~# Is this a good enough solution to the problem?
Neo4j
13,951,700
14
When I tried to create relationship using spring code, I am getting Transaction manager error. I am using Mysql and Neo4j database in my project. I tries different solution but not able to resolve. org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available: No matching PlatformTransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match! Pom.xml file as below <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.10.RELEASE</version> </dependency> <!-- For Neo4J Graph Database --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.9-rc</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>1.5.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> </project> Application.class @SpringBootApplication @EnableTransactionManagement @EntityScan("projectone.entities") public class Application { public static void main(String[] args) { //For Starting application ApplicationContext applicationContext=SpringApplication.run(Application.class, args); } } Database Configuration file: @Configuration @EnableJpaRepositories(basePackages = {"projectone.mysql"}, entityManagerFactoryRef = "dbEntityManager", transactionManagerRef = "dbTransactionManager") @EnableTransactionManagement public class DatabaseConfiguration { @Autowired private Environment env; @Bean @Primary public LocalContainerEntityManagerFactoryBean dbEntityManager() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dbDatasource()); em.setPackagesToScan(new String[]{"projectone.mysql"}); em.setPersistenceUnitName("dbEntityManager"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<String, Object> properties = new HashMap<>(); properties.put("hibernate.dialect",env.getProperty("hibernate.dialect")); properties.put("hibernate.show-sql",env.getProperty("jdbc.show-sql")); em.setJpaPropertyMap(properties); return em; } @Primary @Bean public DataSource dbDatasource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName( env.getProperty("spring.datasource.driverClassName")); dataSource.setUrl(env.getProperty("spring.datasource.url")); dataSource.setUsername(env.getProperty("spring.datasource.username")); dataSource.setPassword(env.getProperty("spring.datasource.password")); return dataSource; } @Primary @Bean public PlatformTransactionManager dbTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( dbEntityManager().getObject()); return transactionManager; } } I tried minimal configuration by removing the database configuration class. After that my application is not running and I am getting Person is not a managed Bean error. If I use only @SpringBootApplication annotation then I am getting following Exception: It is throwing org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingController': Unsatisfied dependency expressed through field 'branchService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'branchServiceImplementaion': Unsatisfied dependency expressed through field 'branchRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'branchRepository': Unsatisfied dependency expressed through method 'setSession' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is NullPointerException
Finally, I found the mistake: Due to this method being named dbTransactionManager, Spring couldn't find it. I just had to change its name to transactionManager, by changing @Bean to @Bean(name = "transactionManager"), as shown below. @Bean(name = "transactionManager") public PlatformTransactionManager dbTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( dbEntityManager().getObject()); return transactionManager; } Also: I could've simply renamed the entire method to transactionManager()
Neo4j
48,861,439
13
I have this kinds of relationships: (:User)<-[:MENTIONS]-(:Tweet)-[:ABOUT]->(:Topic) I would like to count all the users mentioned in the tweets regarding some topic. With the following query match (n:Topic)<--(t:Tweet)-[:MENTIONS]->(u:User) where n.name='politics' return distinct count(u) all I get is the relationships count. What I would like to get is, instead, the number of users mentioned (without duplicates if a user is mentioned several times). How is that possible?
Try putting distinct inside count function, this way: match (n:Topic)<-[:ABOUT]-(t:Tweet)-[:MENTIONS]->(u:User) where n.name='politics' return count(distinct u)
Neo4j
47,550,506
13
Part of my graph has the following schema: Main part of the graph is the domain, that has some persons linked to it. Person has a unique constraint on the email property, as I also have data from other sources and this fits nicely. A person can be an admin in my case, where he has some devices/calendars linked to him. I get this data from an SQL db, where I import few tables to combine the whole picture. I start with a table, that has two columns, email of the admin and his user id. This user id is specific only for production database and is not globally used for other sources as well. That is why I use email as global ID for persons. I am currently using the following query to import user id, that all the production tables are linked to. I always get the current snapshot of the user settings and info. This query runs 4x/day: CALL apoc.load.jdbc(url, import_query) yield row MERGE (p:Person{email:row.email}) SET p.user_id = row.id And then I import all the data that is linked to this user id from other tables. Now the problem occurs, because the user from production db can change his email. So the way I am importing this right now I will end up with two persons having the same user_id and subsequently all the devices/calendars will be linked to both persons, as they both share the same user_id. So this is not an accurate representation of the reality. We also need to capture the connecting/disconnecting of devices to particular user_id through time, as one can connect/disconnect a device and loan it to a friend, that has a different admin (user_id). How to change my graph model ( importing query ), so that : Querying who is currently the admin will not require complex queries Querying who has currently the device connected will not require complex queries Querying history can be a bit more complex.
This answer is based on Ian Robinson's post about time-based versioned graphs. I don't know if this answer covers ALL the requirements of the question, but I believe that can provide some insights. Also, I'm considering you are only interested in structural versioning (that is: you are not interested in queries about the changes of the domain user's name over the time). Finally, I'm using a partial representation of your graph model, but I believe that the concepts shown here can be applied in the whole graph. The initial graph state: Considering this Cypher to create an initial graph state: CREATE (admin:Admin) CREATE (person1:Person {person_id : 1}) CREATE (person2:Person {person_id : 2}) CREATE (person3:Person {person_id : 3}) CREATE (domain1:Domain {domain_id : 1}) CREATE (device1:Device {device_id : 1}) CREATE (person1)-[:ADMIN {from : 0, to : 1000}]->(admin) CREATE (person1)-[:CONNECTED_DEVICE {from : 0, to : 1000}]->(device1) CREATE (domain1)-[:MEMBER]->(person1) CREATE (domain1)-[:MEMBER]->(person2) CREATE (domain1)-[:MEMBER]->(person3) Result: The above graph has 3 person nodes. These nodes are members of a domain node. The person node with person_id = 1 is connected to a device with device_id = 1. Also, person_id = 1 is the current administrator. The properties from and to inside the :ADMIN and :CONNECTED_DEVICE relationships are used to manage the history of the graph structure. from is representing a start point in time and to an end point in time. For simplification purpose I'm using 0 as the initial time of the graph and 1000 as the end-of-time constant. In a real world graph the current time in milliseconds can be used to represent time points. Also, Long.MAX_VALUE can be used instead as the EOT constant. A relationship with to = 1000 means there is no current upper bound to the period associated with it. Queries: With this graph, to get the current administrator I can do: MATCH (person:Person)-[:ADMIN {to:1000}]->(:Admin) RETURN person The result will be: ╒═══════════════╕ β”‚"person" β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚{"person_id":1}β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Given a device, to get the current connected user: MATCH (:Device {device_id : 1})<-[:CONNECTED_DEVICE {to : 1000}]-(person:Person) RETURN person Resulting: ╒═══════════════╕ β”‚"person" β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚{"person_id":1}β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ To query the current administrator and the current person connected to a device the End-Of-Time constant is used. Query the device connect / disconnect events: MATCH (device:Device {device_id : 1})<-[r:CONNECTED_DEVICE]-(person:Person) RETURN person AS person, device AS device, r.from AS from, r.to AS to ORDER BY r.from Resulting: ╒═══════════════╀═══════════════╀══════╀════╕ β”‚"person" β”‚"device" β”‚"from"β”‚"to"β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════════════β•ͺ══════β•ͺ════║ β”‚{"person_id":1}β”‚{"device_id":1}β”‚0 β”‚1000β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜ The above result shows that person_id = 1 is connected to device_id = 1 of the beginning until today. Changing the graph structure Consider that the current time point is 30. Now user_id = 1 is disconnecting from device_id = 1. user_id = 2 will connect to it. To represent this structural change, I will run the below query: // Get the current connected person MATCH (person1:Person)-[old:CONNECTED_DEVICE {to : 1000}]->(device:Device {device_id : 1}) // get person_id = 2 MATCH (person2:Person {person_id : 2}) // set 30 as the end time of the connection between person_id = 1 and device_id = 1 SET old.to = 30 // set person_id = 2 as the current connected user to device_id = 1 // (from time point 31 to now) CREATE (person2)-[:CONNECTED_DEVICE {from : 31, to: 1000}]->(device) The resultant graph will be: After this structural change, the connection history of device_id = 1 will be: MATCH (device:Device {device_id : 1})<-[r:CONNECTED_DEVICE]-(person:Person) RETURN person AS person, device AS device, r.from AS from, r.to AS to ORDER BY r.from ╒═══════════════╀═══════════════╀══════╀════╕ β”‚"person" β”‚"device" β”‚"from"β”‚"to"β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════════════β•ͺ══════β•ͺ════║ β”‚{"person_id":1}β”‚{"device_id":1}β”‚0 β”‚30 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€ β”‚{"person_id":2}β”‚{"device_id":1}β”‚31 β”‚1000β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜ The above result shows that user_id = 1 was connected to device_id = 1 from 0 to 30 time. person_id = 2 is currently connected to device_id = 1. Now the current person connected to device_id = 1 is person_id = 2: MATCH (:Device {device_id : 1})<-[:CONNECTED_DEVICE {to : 1000}]-(person:Person) RETURN person ╒═══════════════╕ β”‚"person" β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚{"person_id":2}β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ The same approach can be applied to manage the admin history. Obviously this approach has some downsides: Need to manage a set of extra relationships More expensive queries More complex queries But if you really need a versioning schema I believe this approach is a good option or (at least) a good start point.
Neo4j
45,669,949
13
I have a almost 5000 nodes of Recipes and 5 nodes of Meal_Types in neo4j database. Right now there is no relationship between them. I am running CQL below: MATCH (n) RETURN n LIMIT 100000 This is running fine, but it is returning node related to Recipes only. There may be something hidden, I mean there might be nodes related to Meal_Types but as they are in same color it is very hard to differentiate them. So is there a way to bring all nodes to dispaly with different colors respectively?
Since you write about "display" and "colors", I assume you're writing about the Neo4j browser. Your query might limit its results to the first 100000, but the browser will actually display much less nodes, with a default number of 300. You can change that value using the following command in the browser: :config initialNodeDisplay: 1000 or through the settings pane on the bottom left (see the "Graph Visualization" section). Since you only have 5 Meal_Types nodes, vs 5000 Repices, it's unlikely they'll be part of any partial result. You can bias the result by ordering on the label, since Meal_Type will sort alphabetically before Recipes: MATCH (n) RETURN n ORDER BY head(labels(n)) LIMIT 300 That way, you don't need to display more nodes (since you can't zoom out, it's pretty useless anyway) and you'll always get your 5 Meal_Types.
Neo4j
38,501,814
13
I have a simple Neo4j graph database that I created while trying to model something for a new application. When I run the following query, I get the nodes that I am expecting, but I also get more relationships than I bargained for: MATCH (o:Office)-[r:REPORTS_VARIABLE_TO]->() RETURN o,r This is what the results look like: Since I specifically requested things that match with [:REPORTS_VARIABLE_TO] I expected to see only that relationship in the results. What I see, though, is all relationships that exist between any matching nodes (as you can see on the bottom of the image). Is there a way to filter out those relationships that are not of the type I'm looking for?
For the newest versions (e.g 3.2, 3.3) the "auto-complete" toggle has been moved to the browser settings and its new name is "Connected all results". If it is checked, it connects nodes with all of their relationships. Otherwise, you only see relationships which meet the filtering criteria.
Neo4j
38,224,897
13
We've hit an issue when upgrading from spring-boot 1.3.2 to the recently released 1.3.3. Our application has been making use of the following dependencies, each the latest, without issue: <neo4j.version>2.3.2</neo4j.version> <sdn.version>4.0.0.RELEASE</sdn.version> <sdn.rest.version>3.4.0.RELEASE</sdn.rest.version> <neo4j.ogm.version>1.1.5</neo4j.ogm.version> Today I upgraded our spring-boot and Spring Data Neo4j -based application, which starts and works well with spring-boot 1.3.2.RELEASE, by changing the pom.xml from: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> </parent> to <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> With this being literally the only change, the application now fails to start with the following error: ... Failed to instantiate [ch.qos.logback.classic.LoggerContext] Reported exception: java.lang.AbstractMethodError: ch.qos.logback.classic.pattern.EnsureExceptionHandling.process(Lch/qos/logback/core/pattern/Converter;)V at ch.qos.logback.core.pattern.PatternLayoutBase.start(PatternLayoutBase.java:88) at ch.qos.logback.classic.encoder.PatternLayoutEncoder.start(PatternLayoutEncoder.java:28) at ch.qos.logback.core.joran.action.NestedComplexPropertyIA.end(NestedComplexPropertyIA.java:167) at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:317) at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:196) at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:182) at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62) at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:149) at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:135) at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:99) at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:49) at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:77) at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:152) at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:85) at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:143) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:122) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:378) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:328) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:349) at com.mycompany.Application.<clinit>(Application.java:35) As expected, returning to 1.3.2.RELEASE does not cause any issues. Searching so far reveals no trail to follow. Comparing the mvn dependency:tree output between using spring-boot 1.3.2.RELEASE and 1.3.3.RELEASE, I can see that the transient dependencies of ch.qos.logback:logback-classic and ch.qos.logback:logback-access jars have changed from 1.1.3 for spring-boot 1.3.2.RELEASE to 1.1.5 for spring-boot 1.3.3.RELEASE, while ch.qos.logback:logback-core remains at 1.1.3 for both spring-boot flavors. Does anyone have any idea of what the underlying issue is (I'm guessing the class failing to instantiate has been removed or relocated) and/or -- more importantly -- what I can do to resolve it?
Spring Boot is missing some dependency management for logback-core which is allowing different versions to creep in. I've opened an issue to address that. In the meantime, you can avoid the problem by adding your own dependency management for it to your pom: <dependencyManagement> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> </dependencies> </dependencyManagement>
Neo4j
35,738,674
13
I am preplexed on why I am getting an issue with this Cypher statment when I have a unique constraint on the address of the location node but am using a merge which should find that if it exists and only return the id for the rest of the statment. What am I missing? Here is my statement: MERGE(l:Location{location_name:"Starbucks", address:"36350 Van Dyke Ave", city: "Sterling Heights",state: "MI", zip_code:"48312",type:"location",room_number:"",long:-83.028889,lat:42.561152}) CREATE(m:Meetup{meet_date:1455984000,access:"Private",status:"Active",type:"project",did_happen:"",topic:"New features for StudyUup",agenda:"This is a brainstorming session to come with with new ideas for the companion website, StudyUup. Using MatchUup as the base, what should be added, removed, or modified? Bring your thinking caps and ideas!"}) WITH m,l MATCH (g:Project{title_slug:"studyuup"}) MATCH (p:Person{username:"wkolcz"}) WITH m,l,g,p MERGE (g)-[:CREATED {rating:0}]->(m) MERGE (m)-[:MEETUP_AT {rating:0}]->(l)-[:HOSTED_MEETUP]->(m) MERGE (m)<-[:ATTENDING]-(p) RETURN id(m) as meeting_id I am getting: Node 416 already exists with label Location and property "address"=[36350 Van Dyke Ave]
You've encountered a common misunderstanding of MERGE. MERGE merges on everything you've specified within the single MERGE clause. So the order of operations are: Search for a :Location node with all of the properties you've specified. If found, return the node. If not found, create the node. Your problem occurs at step 3. Because a node with all of the properties you've specified does not exist, it goes to step 3 and tries to create a node with all of those properties. That's when your uniqueness constraint is violated. The best practice is to merge on the property that you've constrained to be unique and then use SET to update the other properties. In your case: MERGE (l:Location {address:"36350 Van Dyke Ave"}) SET l.location_name = "Starbucks", l.city = "Sterling Heights" ... The same logic is going to apply for the relationships you're merging later in the query. If the entire pattern doesn't exist, it's going to try to create the entire pattern. That's why you should stick to the best practice of: MERGE (node1:Label1 {unique_property: "value"}) MERGE (node2:Label2 {unique_property: "value"}) MERGE (node1)-[:REL]-(node2)
Neo4j
35,381,968
13
If I have a set of nodes with the same attributes in Neo4j, is there a way to convert the type of a certain attribute from string to int (or vice versa) for all of those nodes?
How about MATCH (n:Type) WHERE <filter if required> SET n.strProp = toInt(n.strProp) and MATCH (n:Type) WHERE <filter if required> SET n.intProp = toString(n.intProp)
Neo4j
35,236,519
13
I spent a week at Gremlin shell trying to compose one query to get all incoming and outgoing vertexes, including their edges and directions. All i tried everything. g.V("name","testname").bothE.as('both').select().back('both').bothV.as('bothV').select(){it.map()} output i need is (just example structure ): [v{'name':"testname"}]___[ine{edge_name:"nameofincomingedge"}]____[v{name:'nameofconnectedvertex'] [v{'name':"testname"}]___[oute{edge_name:"nameofoutgoingedge"}]____[v{name:'nameofconnectedvertex'] So i just whant to get 1) all Vertices with exact name , edge of each this vertex (including type inE or outE), and connected Vertex. And ideally after that i want to get their map() so i'l get complete object properties. i dont care about the output style, i just need all of information present, so i can manipulate with it after. I need this to train my Gremlin, but Neo4j examples are welcome. Thanks!
There's a variety of ways to approach this. Here's a few ideas that will hopefully inspire you to an answer: gremlin> g = TinkerGraphFactory.createTinkerGraph() ==>tinkergraph[vertices:6 edges:6] gremlin> g.V('name','marko').transform{[v:it,inE:it.inE().as('e').outV().as('v').select().toList(),outE:it.outE().as('e').inV().as('v').select().toList()]} ==>{v=v[1], inE=[], outE=[[e:e[9][1-created->3], v:v[3]], [e:e[7][1-knows->2], v:v[2]], [e:e[8][1-knows->4], v:v[4]]]} The transform converts the incoming vertex to a Map and does internal traversal over in/out edges. You could also use path as follows to get a similar output: gremlin> g.V('name','marko').transform{[v:it,inE:it.inE().outV().path().toList().toList(),outE:it.outE().inV().path().toList()]} ==>{v=v[1], inE=[], outE=[[v[1], e[9][1-created->3], v[3]], [v[1], e[7][1-knows->2], v[2]], [v[1], e[8][1-knows->4], v[4]]]} I provided these answers using TinkerPop 2.x as that looked like what you were using as judged from the syntax. TinkerPop 3.x is now available and if you are just getting started, you should take a look at the latest that has to offer: http://tinkerpop.incubator.apache.org/ Under 3.0 syntax you might do something like this: gremlin> g.V().has('name','marko').as('a').bothE().bothV().where(neq('a')).path() ==>[v[1], e[9][1-created->3], v[3]] ==>[v[1], e[7][1-knows->2], v[2]] ==>[v[1], e[8][1-knows->4], v[4]] I know that you wanted to know what the direction of the edge in the output but that's easy enough to detect on analysis of the path. UPDATE: Here's the above query written with Daniel's suggestion of otherV usage: gremlin> g.V().has('name','marko').bothE().otherV().path() ==>[v[1], e[9][1-created->3], v[3]] ==>[v[1], e[7][1-knows->2], v[2]] ==>[v[1], e[8][1-knows->4], v[4]] To see the data from this you can use by() to pick apart each Path object - The extension to the above query applies valueMap to each piece of each Path: gremlin> g.V().has('name','marko').bothE().otherV().path().by(__.valueMap(true)) ==>[{label=person, name=[marko], id=1, age=[29]}, {label=created, weight=0.4, id=9}, {label=software, name=[lop], id=3, lang=[java]}] ==>[{label=person, name=[marko], id=1, age=[29]}, {label=knows, weight=0.5, id=7}, {label=person, name=[vadas], id=2, age=[27]}] ==>[{label=person, name=[marko], id=1, age=[29]}, {label=knows, weight=1.0, id=8}, {label=person, name=[josh], id=4, age=[32]}]
Neo4j
33,676,566
13
On a fresh install of neo4j-community-2.2.4 I get the message "Invalid username or password." when submitting the login form at localhost:7474/browser with the default username neo4j and password neo4j. I did enable org.neo4j.server.webserver.address=0.0.0.0 and dbms.security.auth_enabled=true with a server stop and start and a browser shift-reload. I then changed the property org.neo4j.server.webserver.address=127.0.0.1 to match my /etc/hosts and tried on 127.0.0.1:7474/browser but got the same message. Here is the browser console output: Remote Address:127.0.0.1:7474 Request URL:http://localhost:7474/db/data/ Request Method:GET Status Code:401 Unauthorized Request Headersview source Accept:application/json, text/plain, */* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8,fr;q=0.6,ru;q=0.4,es;q=0.2,sv;q=0.2,nb;q=0.2,et;q=0.2 Authorization:Basic bmVvNGo6bmVvNGo= Cache-Control:no-cache Connection:keep-alive Cookie:languageCodeAdmin=en; PHPSESSID=vcbvfkvj3shajhlh5u2pue9i70; admin_template_phone_client=0; admin_template_touch_client=0; admin_template_model=1 Host:localhost:7474 If-Modified-Since:Wed, 11 Dec 2013 08:00:00 GMT Pragma:no-cache Referer:http://localhost:7474/browser/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36 X-stream:true Response Headersview source Content-Length:135 Content-Type:application/json; charset=UTF-8 Date:Sat, 19 Sep 2015 09:14:03 GMT Server:Jetty(9.2.4.v20141103) WWW-Authenticate:None { "errors" : [ { "message" : "Invalid username or password.", "code" : "Neo.ClientError.Security.AuthorizationFailed" } ] } So I then tried to change the default password. To do that, I first disabled the authentication with a dbms.security.auth_enabled=false and a server stop and start. And I then tried the following curl request: curl -H "Accept:application/json; charset=UTF-8" -H "Content-Type: application/json" "http://localhost:7474/user/neo4j/password" -X POST -d "{ \"password\" : \"neo4j\" }" -i But it gives me the response: HTTP/1.1 404 Not Found Date: Sat, 19 Sep 2015 09:25:38 GMT Access-Control-Allow-Origin: * Content-Length: 0 Server: Jetty(9.2.4.v20141103)
Since you get an authentication error on your browser request which uses the default credentials neo4j:neo4j your database has already a different password configured. To reset it to default, stop neo4j, delete data/dbms/auth and start it again. Now you can use the default pw.
Neo4j
32,666,453
13
I have a domain class which has a property by name "alias" which is an arraylist of strings like below: private List<String> alias; alias contains the following values: {"John Doe","Alex Smith","Greg Walsh"} I'd like to be able to make a query like: "I saw Smith today" using my repository query shown below and get the array value Output "Alex Smith": @Query("MATCH (p:Person) WHERE {0} IN p.alias RETURN p") Iterable<Person> findByAlias(String query); I tried a bunch of different queries like the one shown above but this would only match if the input query matches the array value exactly. I want do a input query sub-string match with the array values. Eg: Input Query: "I saw Smith today" Output: "Alex Smith"
Summary It is sort of possible to do what you want, but the query will be horribly ugly and slow. You'd be better off using nodes and relationships instead of collection properties: it will make your queries more sensible and allows you to use a full-text index. You should also figure out what part of the 'input string' you are looking for before you send your query to the database. As it stands, you are confusing the regex pattern with the data it is supposed to match and even if it were possible to express your intention as a regex it would be much better to do that processing your application, before sending the query. 1) WHERE ... IN ... doesn't do regex WHERE x IN y will not treat x as a regular expression, it will take x's value for what it is and look for an exact match. WHERE ... IN ... is analogous to WHERE ... = ... in this sense, and you would need the analogue of =~ for collections, something like IN~, for this. There is no such construct in Cypher. 2) You can do regex over collections with predicates, but it is inefficient You can use a string as a regular expression to test for matches over a collection by using a predicate like ANY or FILTER. CREATE (p:Person {collectionProperty:["Paulo","Jean-Paul"]}) and WITH "(?i).*Paul" as param MATCH (p:Person) WHERE ANY(item IN p.collectionProperty WHERE item =~ param) RETURN p will return the node because it makes a successful regular expression match on "Jean-Paul". This, however, will have terrible performance since you will run your regular expression on every item in every collectionProperty for every :Person in your database. The solution is to use a full-text index, but his query can't use indices for two reasons: the values you are querying are in an array you are using regular expressions to filter results instead of doing an index query 3) You can't do regex over collections at all with your kind of input The biggest problem with your query is that you are trying to turn "I saw Smith today" into "Smith" by adding some regular expression sugar. How do you intend to do that? If you use the string as a regular expression, each of those characters is a literal character expected to be in the data that you match it on. You are confused about .*, which when used in 'Smith.*' would match 'Smith' plus zero or more additional characters in the data. But you try to use it to say that zero or more characters may follow something in the pattern. Take the query in your comment: MATCH (p:Person) WHERE '(?i).*I saw Smith today.*' IN p.alias RETURN p The regular expression '(?i).*I saw Smith today.*' will match ignoring the case of the literal string–'i SAW smith TOday', etc. with zero or more characters before and after the literal string–'Yes, I saw Smith today and he looked happy.' But adding .* won't somehow magically make the pattern mean '.*Smith.*'. What's more, it's almost impossible to express 'I saw Smith today' as a subset of 'Alex Smith' by any amount of added regular expression sugar. Instead, you should process that string and figure out what parts of it you want to use in a regular expression before you send your query. How is the database to know that 'Smith' is the part of the input string that you want to use? However it is that you know it, you should know it before you send the query, and only include that relevant part. Aside: examples of added regular expression sugar that won't work and why You could insert a ? after each character in the pattern to make each character optional RETURN "Smith" =~ "I? ?s?a?w? ?S?m?i?t?h? ?t?o?d?a?y?" But now your pattern is way too loosie goosie, and it will match strings like 'I sat today' and 'sam toy'. Moreover, it won't match 'Alex Smith' unless you prepend .*, but then it is even more loosie goosie and will match any string whatever. You could divide characters that belong together into groups and make the groups and the spaces between them optional. RETURN "Smith" =~ "(I)? ?(saw)? ?(Smith)? ?(today)?" But this also is too broad, fails to match 'Alex Smith' and will match any string whatever if you prepend .*. 4) Bad solution The only 'solution' I can think of is a hideous query that splits your string on whitespace, concatenates some regex sugar into each word and compares it as a regular expression in a predicate clause. It really is hideous, and it assumes that you already know that you want match the words in the string and not the whole string, in which case you should be doing that processing before you send your query and not in Cypher. Look upon this hideousness and weep WITH "I saw Paul today" AS paramString MATCH (p:Person) WHERE ANY (param IN split(paramString, ' ') WHERE ANY (item IN p.collectionProperty WHERE item =~('(?i).*' + param))) RETURN p 5) Conclusion The conclusion is as follows: 1) Change your model. Keep a node for each alias like so CREATE (a:Alias) SET a.aliasId = "Alex Smith" Create a full-text index for these nodes. See blog and docs for the generic case and docs for SDN. Connect the nodes that now have the alias in a collection property to the new alias node with a relationship. Look up the alias node that you want and follow the relationship to the node that 'has' the alias. A node can still have many aliases, but you no longer store them in a collection property–your query logic will be more straightforward and you will benefit from the full-text lucene index. Query with START n=node:indexName("query") when using cypher and use findAllByQuery() in SDN. This is necessary for the query to use the full-text index. Your query might then finally look something like START n=node:myIndex("aliasId:*smith") MATCH n<-[:HAS_ALIAS]-smith RETURN smith 2) Don't do all your work in the database. If your program is supposed to receive a string like 'I saw Smith today' and give back a node based on a pattern match on 'Smith', then don't send 'I saw' and 'today' to the database. You're better off identifying 'Smith' as the relevant part of the string in your application–when you send the query you should already know what it is you want.
Neo4j
32,044,348
13
How to create unique CONSTRAINT to relationship by neo4j cypher?
At present, there is only one kind of CONSTRAINT neo4j will let you create, and that's a UNIQUENESS constraint. That link cites what's in the internal API, and you'll notice there's only one type at present. Here's a link on how to create a uniqueness constraint. This lets you assert that a certain property of a node must be unique, but it doesn't say anything about relationships. I don't think it's possible to constrain what sort of relationships can come off of various nodes.
Neo4j
23,610,548
13
I am new to Neo4j. I am using v2.0.1. By default the browser application's stream (output) section only displays the ID properties of the nodes in the graph db. I have added several nodes with additional properties and relationships. When the graph is displayed in the stream window I only see default ID inside of the node pictures. When I click on the node a popup will show all my properties. I would like to know if there is a configuration or style setting to cause a more useful property to be displayed so that the visible graph's nodes can be seen in a more useful way in the Neo4j browser. thanks
While the accepted answer is correct, it doesn't show how to do it. Since Neo4j Browser version v2.0.1, you can click on the label name at the top of the graph, options for size, color, and caption of the nodes appear at the bottom of the graph. Change the caption option to select a different property to display in the graph. Here's a screenshot taken from Neo4j Browser v4.0.3.
Neo4j
21,739,837
13
I am using Neo4j 2.0 version. Suppose, I have lot of records which have date as one of their fields and if we need to support lot of queries like count of records between two specific dates etc, I think that I may have tpo index all the records by Date field. Is this correct? Then., how do I do it. All nodes of the type "RECORD" need to be indexed dy date. How can I achieve this? Please note that Date is a not unique field. And how do I even store Date property in the records. Is Date supported in CYPHER or Neo4j. How do I sort the records by Date field?
Dates as values for properties are not directly supported. Depending on your usecase you typically store the millis since epoch (aka date.getTime()) in a long property or a string representation using a DateFormatter (when being in Java land). The long representation is better suited if you intend to do any math operation with dates. String is better if you want your properties being human readable without any conversion. When requiring indexes on dates the easiest approach would be storing millis since epoch and apply a schema index on this.
Neo4j
21,643,896
13
How should I check if two nodes have relationship with each other,in neo4j embedded database in java? I want the syntax please or a tutorial link,I have seen neo4j website but didn't find it. Thanks.
Given two nodes "nodeA" and "nodeB", gets all relationships attached to "nodeA", rels = nodeA.getRelationships(); iterate through the collection of relationships "rels", for each relationship "rel", test whether the other end node is nodeB rel.getOtherNode(nodeA).equals(nodeB) if the above expression holds true for one of the relationships, then nodeA and nodeB are connected. Here is the java API for "Node" and "Relationshiip", http://api.neo4j.org/current/
Neo4j
19,477,638
13
I have imported data using Michael Hunger's Batch Import, through which I created:- 4,612,893 nodes 14,495,063 properties node properties are indexed. 5,300,237 relationships {Question} Cypher queries are executing too slow almost crawling, simple traversal is taking > 5 mins to return resultset, Please let me know how to tune the server to get better performance and what I am doing wrong. Store Details:- -rw-r--r-- 1 root root 567M Jul 12 12:42 data/graph.db/neostore.propertystore.db -rw-r--r-- 1 root root 167M Jul 12 12:42 data/graph.db/neostore.relationshipstore.db -rw-r--r-- 1 root root 40M Jul 12 12:42 data/graph.db/neostore.nodestore.db -rw-r--r-- 1 root root 7.8M Jul 12 12:42 data/graph.db/neostore.propertystore.db.strings -rw-r--r-- 1 root root 330 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.keys -rw-r--r-- 1 root root 292 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.names -rw-r--r-- 1 root root 153 Jul 12 12:42 data/graph.db/neostore.propertystore.db.arrays -rw-r--r-- 1 root root 88 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index -rw-r--r-- 1 root root 69 Jul 12 12:42 data/graph.db/neostore -rw-r--r-- 1 root root 58 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.nodestore.db.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.arrays.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.index.keys.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.propertystore.db.strings.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.relationshipstore.db.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.id -rw-r--r-- 1 root root 9 Jul 12 12:42 data/graph.db/neostore.relationshiptypestore.db.names.id I am using neo4j-community-1.9.1 java version "1.7.0_25" Amazon EC2 m1.large instance with Ubuntu 12.04.2 LTS (GNU/Linux 3.2.0-40-virtual x86_64) RAM ~8GB. EBS 200 GB, neo4j is running on EBS volume. Invoked as ./neo4j-community-1.9.1/bin/neo4j start Below are the neo4j server info: neostore.nodestore.db.mapped_memory 161M neostore.relationshipstore.db.mapped_memory 714M neostore.propertystore.db.mapped_memory 90M neostore.propertystore.db.index.keys.mapped_memory 1M neostore.propertystore.db.strings.mapped_memory 130M neostore.propertystore.db.arrays.mapped_memory 130M mapped_memory_page_size 1M all_stores_total_mapped_memory_size 500M {Data Model} is like Social Graph :- User-User User-[:FOLLOWS]->User User-Item User-[:CREATED]->Item User-[:LIKE]->Item User-[:COMMENT]->Item User-[:VIEW]->Item Cluster-User User-[:FACEBOOK]->SocialLogin_Cluster Cluster-Item Item-[:KIND_OF]->Type_Cluster Cluster-Cluster Cluster-[:KIND_OF]->Type_Cluster {Some Queries} and time: START u=node(467242) MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b WHERE NOT(a=b) RETURN u,COUNT(b) Query took 1015348ms. Returned 70956115 result count. START a=node:nodes(kind="user") RETURN a,length(a-[:CREATED|LIKE|COMMENT|FOLLOWS]-()) AS cnt ORDER BY cnt DESC LIMIT 10 Query took 231613ms From the suggestions, I upgraged the box to M1.xlarge and M2.2xlarge M1.xlarge (vCPU:4,ECU:8,RAM:15 GB,Instance Storage:~600 GB) M2.2xlarge (vCPU:4,ECU:13,RAM:34 GB,Instance Storage:~800 GB) I tuned the properties like below, and running from instance storage (as against EBS) neo4j.properties neostore.nodestore.db.mapped_memory=1800M neostore.relationshipstore.db.mapped_memory=1800M neostore.propertystore.db.mapped_memory=100M neostore.propertystore.db.strings.mapped_memory=150M neostore.propertystore.db.arrays.mapped_memory=10M neo4j-wrapper.conf wrapper.java.additional.1=-d64 wrapper.java.additional.1=-server wrapper.java.additional=-XX:+UseConcMarkSweepGC wrapper.java.additional=-XX:+CMSClassUnloadingEnabled wrapper.java.initmemory=4098 wrapper.java.maxmemory=8192 but still the queries (like below) run in minutes ~5-8 minutes, which is not acceptable from recommendation point of view. Query: START u=node(467242) MATCH u-[r1:LIKE]->a<-[r2:LIKE]-lu-[r3:LIKE]-b RETURN u,COUNT(b) {Profiling} neo4j-sh (0)$ profile START u=node(467242) MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b RETURN u,COUNT(b); ==> +-------------------------+ ==> | u | COUNT(b) | ==> +-------------------------+ ==> | Node[467242] | 70960482 | ==> +-------------------------+ ==> 1 row ==> ==> ColumnFilter(symKeys=["u", " INTERNAL_AGGREGATEad2ab10d-cfc3-48c2-bea9-be4b9c1b5595"], returnItemNames=["u", "COUNT(b)"], _rows=1, _db_hits=0) ==> EagerAggregation(keys=["u"], aggregates=["( INTERNAL_AGGREGATEad2ab10d-cfc3-48c2-bea9-be4b9c1b5595,Count)"], _rows=1, _db_hits=0) ==> TraversalMatcher(trail="(u)-[r1:LIKE|COMMENT WHERE true AND true]->(a)<-[r2:LIKE|COMMENT WHERE true AND true]-(lu)-[r3:LIKE WHERE true AND true]-(b)", _rows=70960482, _db_hits=71452891) ==> ParameterPipe(_rows=1, _db_hits=0) neo4j-sh (0)$ profile START u=node(467242) MATCH u-[r1:LIKE|COMMENT]->a<-[r2:LIKE|COMMENT]-lu-[r3:LIKE]-b RETURN count(distinct a),COUNT(distinct b),COUNT(*); ==> +--------------------------------------------------+ ==> | count(distinct a) | COUNT(distinct b) | COUNT(*) | ==> +--------------------------------------------------+ ==> | 1950 | 91294 | 70960482 | ==> +--------------------------------------------------+ ==> 1 row ==> ==> ColumnFilter(symKeys=[" INTERNAL_AGGREGATEe6b94644-0a55-43d9-8337-491ac0b29c8c", " INTERNAL_AGGREGATE1cfcd797-7585-4240-84ef-eff41a59af33", " INTERNAL_AGGREGATEea9176b2-1991-443c-bdd4-c63f4854d005"], returnItemNames=["count(distinct a)", "COUNT(distinct b)", "COUNT(*)"], _rows=1, _db_hits=0) ==> EagerAggregation(keys=[], aggregates=["( INTERNAL_AGGREGATEe6b94644-0a55-43d9-8337-491ac0b29c8c,Distinct)", "( INTERNAL_AGGREGATE1cfcd797-7585-4240-84ef-eff41a59af33,Distinct)", "( INTERNAL_AGGREGATEea9176b2-1991-443c-bdd4-c63f4854d005,CountStar)"], _rows=1, _db_hits=0) ==> TraversalMatcher(trail="(u)-[r1:LIKE|COMMENT WHERE true AND true]->(a)<-[r2:LIKE|COMMENT WHERE true AND true]-(lu)-[r3:LIKE WHERE true AND true]-(b)", _rows=70960482, _db_hits=71452891) ==> ParameterPipe(_rows=1, _db_hits=0) Please let me know the configuration and neo4j startup arguments for tuning. Thanks in advance
Running this on my macbook air with little RAM and CPU with your dataset. You will get much faster than my results with more memory mapping, GCR cache and more heap for caches. Also make sure to use parameters in your queries. You are running into combinatorial explosion. Every step of the path adds "times rels" elements/rows to your matched subgraphs. See for instance here: you end up at 269268 matches but you only have 81674 distinct lu's The problem is that for each row the next match is expanded. So if you use distinct in between to limit the sizes again it will be some order of magnitutes less data. Same for the next level. START u=node(467242) MATCH u-[:LIKED|COMMENTED]->a WITH distinct a MATCH a<-[r2:LIKED|COMMENTED]-lu RETURN count(*),count(distinct a),count(distinct lu); +---------------------------------------------------+ | count(*) | count(distinct a) | count(distinct lu) | +---------------------------------------------------+ | 269268 | 1952 | 81674 | +---------------------------------------------------+ 1 row 895 ms START u=node(467242) MATCH u-[:LIKED|COMMENTED]->a WITH distinct a MATCH a<-[:LIKED|COMMENTED]-lu WITH distinct lu MATCH lu-[:LIKED]-b RETURN count(*),count(distinct lu), count(distinct b) ; +---------------------------------------------------+ | count(*) | count(distinct lu) | count(distinct b) | +---------------------------------------------------+ | 2311694 | 62705 | 91294 | +---------------------------------------------------+ Here you have 2.3M total matches and only 91k distinct elements. So almost 2 orders of magnitude. This is a huge aggregation which is rather a BI / statistics query that an OLTP query. Usually you can store the results e.g. on the user-node and only re-execute this in the background. THESE kind of queries are again global graph queries (statistics / BI ), in this case top 10 users. Usually you would run these in the background (e.g. once per day or hour) and connect the top 10 user nodes to a special node or index that then can be queried in a few ms. START a=node:nodes(kind="user") RETURN count(*); +----------+ | count(*) | +----------+ | 3889031 | +----------+ 1 row 27329 ms After all you are running a match across the whole graph, i.e. 4M users that's a graph global, not a graph local query. START n=node:nodes(kind="top-user") MATCH n-[r?:TOP_USER]-() DELETE r WITH distinct n START a=node:nodes(kind="user") MATCH a-[:CREATED|LIKED|COMMENTED|FOLLOWS]-() WITH n, a,count(*) as cnt ORDER BY cnt DESC LIMIT 10 CREATE a-[:TOP_USER {count:cnt} ]->n; +-------------------+ | No data returned. | +-------------------+ Relationships created: 10 Properties set: 10 Relationships deleted: 10 70316 ms The querying would then be: START n=node:nodes(kind="top-user") MATCH n-[r:TOP_USER]-a RETURN a, r.count ORDER BY r.count DESC; +--------------------------------------------------------------------------------------------------------------------------------------------------------------+ | a | r.count | +--------------------------------------------------------------------------------------------------------------------------------------------------------------+ …. +--------------------------------------------------------------------------------------------------------------------------------------------------------------+ 10 rows 4 ms
Neo4j
17,661,902
13
Is there any update query in cypher using which we can update the property of any node or relationship ? For e.g. I have following node and relationship: NodeA-[r:relatedTo]-NodeB where relatedTo is a relationship having properties like active or inactive How can I change this property using cypher query ?
using SET keyword in cypher query, see http://docs.neo4j.org/chunked/snapshot/query-set.html . (Since I have not came across any update query in cypher like in other RDBMS) NodeA-[r:relatedTo]-NodeB try to set value by : SET r.<your property name>="<desired value>"; before returning any value from start n=node(...)... return n; query.
Neo4j
16,963,183
13
I have been trying to run this query as recommended in the neo4j google group and in other sources online: START n = node(*) MATCH n-[r?]-() WHERE ID(n)>0 DELETE n, r; in order to delete all nodes and relationships between tests. When I do so from the console, I run out of java heap space. When I do so from python (using the newish graph_db.clear(), which appears uses the same query), I get a "SystemError: None" which, I assume, is the same java heap space error. I have a database with 500k nodes, only 5k relationships, and 7M properties. I am running on a Mac laptop (10.6.8) with 8GB RAM using neo4j-1.8.1. I guess I am a bit surprised that deleting nodes (with essentially no relationships, so very small subgraphs) would exceed the java heap space, but I am pretty naive about how neo4j works. Any suggestions in how to go forward are appreciated. I do know that rm -rf in the data directory and starting from scratch will work, but I thought there might be a less-drastic solution. [cross-posted to neo4j google groups]
The cypher statement above causes all nodes (besides the root node with ID 0) to be instantiated before deletion in one single transaction. This eats up too much memory when done with 500k nodes. Try to limit the number of nodes to delete to something around 10k-50k, like e.g.: START n = node(*) MATCH n-[r?]-() WHERE (ID(n)>0 AND ID(n)<10000) DELETE n, r; START n = node(*) MATCH n-[r?]-() WHERE (ID(n)>0 AND ID(n)<20000) DELETE n, r; etc. However, there's nothing wrong with removing the entire database directory, it's good practice.
Neo4j
14,690,522
13
Neo4j is a really fast and scalable graph database, it seems that it can be used on business projects and it is free, too! At the same time, there are no RDF triple stores that work well with large data or deliver a high-speed access. And what is more, free RDF triple stores perform even worse. So what is the advantage of RDF and RDF triple stores to Neo4j?
The advantage of using a triple store for RDF rather than Neo4j is that that's what they're designed for. Neo4j is pretty good for many use cases, but in my experience its performance for loading and querying RDF is well below all dedicated RDF databases. It's a fallacy that RDF databases don't scale or are not fast. Sure, they're not yet up to the performance & scale levels that relational databases have, but they have a 50 year head start. Many triple stores scale into the billions of triples, provide 'standard' enterprise features, and provide great performance for many use cases. If you're going to use RDF for a project, use a triple store; it's going to provide the best performance and set of features/APIs for working with RDF to build your application.
Neo4j
10,366,131
13
Say instead of documents I have small trees that I need to store in a Lucene index. How do I go about doing that? An example node in the tree: class Node { String data; String type; List<Node> children; } In the above node the "data" member variable is a space separated string of words, so that needs to be full-text searchable. The "type" member variable is just a single word. The search query will be a tree itself and will search both the data and type in each node and also the structure of the tree for a match. Before matching against a child node, the query must first match the parent node data and type. Approximate matching on the data value is acceptable. What's the best way to index this kind of data? If Lucene does not directly support indexing these data then can this be done by Solr or Elasticsearch? I took a quick look at neo4j, but it seems to store an entire graph in the db, not a large collection (say billions or trillions) of small tree structures. Or my understanding was wrong? Also, is a non-Lucene based NoSQL solution is better suited for this?
Another approach is to store a representation of the current node's location in the tree. For example, the 17th leaf of the 3rd 2nd-level node of the 1st 1st-level node of the 14th tree would be represented as 014.001.003.017. Assuming 'treepath' is the field name of the tree location, you would query on 'treepath:014*' to find all nodes and leaves in the 14th tree. Similarly, to find all of the children of the 14th tree you would query on 'treepath:014.*'. The major problem with this approach is that moving branches around requires re-ordering every branch after the branch that was moved. If your trees are relatively static, that may only be a minor problem in practice. (I've seen this approach called either a 'path enumeration' or a 'Dewey Decimal' representation.)
Neo4j
9,970,193
13
I'am a little bit confused about what is the best solution for my application. As I've seen so far, I have to choose between neo4j standalone (RestGraphDatabase) and an EmbeddedGraphDatabase (the RemoteGraphDatabase is not for production use yet). Pros REST: -> Different services can access the neo4j DB (sample: i have one service that is responsible for Nodes of kind A,B and C. The second service is responsible for nodes D and H and can connect D-nodes to A-nodes). In that way i have clean domain structures. Every service is only responsible for its own domain nodes. I can update each service and don't have to shutdown my whole application. -> I can access the neo4j DB from different languages (PHP) Cons: - Performance is not that good as an EmbeddedGraphDatabase (since the neo4j server and the services are on the same machine the latency is not that big). - No transactions My questions: Is this a good decision to go with the standalone server? Or should I use the embedded one and mix up the services into a big one? Is it possible to run a big (complex) application without transaction support?
You're correct that performance with the REST server will be less. However, you can have something like transactions with the REST server using batch operations; see http://docs.neo4j.org/chunked/milestone/rest-api-batch-ops.html. You can also build domain specific server plugins that perform your transactional logic on the server side: http://docs.neo4j.org/chunked/milestone/server-extending.html. If your architecture requires that you be able to access the database from multiple client machines, your only options are the REST server or Neo4j HA (High Availability). HA is only available with a Neo4j Enterprise license. Let application architecture inform which tools are used, not the other way around. If you've already decided that your application is best as separate services, don't combine them into one just to support the underlying persistence model. I don't know anything about your application, but from your description, I would choose the REST server and utilize batches or server plugins.
Neo4j
8,224,523
13
A Rails 3 application running on Postgresql needs to switch to a graph database to be able to grow up. There are many of them and they all offer different kind of API, REST mostly. I am highly inspired by talks of Emil Eifrem, CEO of NeoTechnologies, about what can be accomplished with Neo4j. I must confess, I've played with it and this thing is absolutely what we need, but there are several obstacles. REST API is not transactional. Rails 3 apps are running on ruby 1.9.2, but not jRuby 1.5.3 or 1.6 to achieve native API. Some databases are also driven by Java and offer REST API, so taking them changes nothing. Someother are not an option for us because of a license or a cost or a lack of team behind them. I assume I'm missing something, so would appreciate any tip, insight or advice about what are our options and and what can play well for us. Thanks.
You can run Neo4jrb with Rails 3 on jruby 1.6, so that should not be a problem. To run a transactional (REST) API on top of that you can easily write your own Neo4j-Server plugin/extension that could also use Neo4jrb internally but exposes an API that fits your domain and is less verbose/chatty than the fine grained Neo4j-Server REST API. This should also be easier to consume for your clients as it talks in your terms, vocabulary and use-cases. We're currently working on creating a generic (j)ruby server extension that is able to consume posted code and make it available as new REST endpoints.
Neo4j
5,896,288
13
Neo4j doesn't seem to allow me to store binary objects. Does this mean I must used Neo4j in conjuntion with another data store, such as the filesystem., Oracle, etc?
Daniel already answered that it's possible to store binary objects in Neo4J. But i would suggest you not to do so. You can do nothing interesting with binary objects in database. You cannot search them. The only thing you will achieve by storing binary objects - grow the file size of your database. Mind you, Neo4J is not scalable horizontally. It does not have automatic sharding. So if your db grows too big, you are in trouble. By storing binaries in a file system or external distributed key-value store like riak, cassandra, hadoop etc, you are keeping your database small, which is good for performance, backups and avoiding horizontal scaling problems.
Neo4j
5,686,692
13
I have an application backed by Neo4j database written in python. Does anyone know what is the best approach to unit test my application ? I have found this can be easily done in Java with usage of ImpermanentGraphDatabase. Is there a similar approach in python ? Any tips are appreciated.
I'm going to say the easiest way would be to mock out Neo4j entirely. What I like to do is to simplify your entity classes to as little pure-python functionality as possible. Even if you're using some fancy ORM to access your data - for example in Django - I still prefer to create a pure-python class to represent my model and create a minimalistic dao method, which will be mocked-out during unit tests. That way I don't have to ever touch the database in my unit tests, which I think is how unit tests should behave. That being said, if you really want to have neo4j functionality in your tests, have a look at the IntegrationTestCase of the official neo4j-python-driver package. It looks like it is providing a base class to inherit your integration tests (because if you're pulling the DB into your tests, you're essentially doing Integration Tests) from, as it takes care of starting up and shutting down the server between test runs.
Neo4j
49,348,839
12
I had worked on relational database; but now want to learn about graph database. I came to know that these two are graph database. What is difference between these two databases. What should we prefer among them?
One approach is to simply try to choose one database over the other. For example, you might quickly search around to find that Titan has been forked to JanusGraph where it is more actively maintained. In your research you may find that there are other open source graph databases as well like OrientDb, ChronoGraph, or Sqlg as well as commercial alternatives like Microsoft's CosmosDb, DSE Graph or IBM Graph. How do you decide now? There is a graph framework that ties together all of these graphs including Neo4j/Titan (and more than those listed here): Apache TinkerPop. TinkerPop provides an abstraction over different graph databases and graph processors allowing the same code to be used with different configurable backends. This pattern is quite similar to the one you find in SQL with JDBC which helps make your code vendor agnostic. You can try all of the different supported graph databases before you make a choice and you can do this type of prototyping/benchmarking fairly quickly with the Gremlin Console. You will be able to make self-informed choice as to what is the best way to go for your project. It occurs to me as I come to the end of this post that I haven't directly answered your question. If you are just getting started and are just interested in learning about graph databases, then I likely wouldn't recommend starting with Titan/JanusGraph as it requires a bit of configuration to get started (schemas, backend selection, etc). Start with TinkerGraph or Neo4j using the Gremlin Console to try out some simple graph traversals and go from there.
Neo4j
45,347,593
12
I have a graph with three node types: NodeX, NodeY, and NodeZ I have the this cypher query: MATCH (x:NodeX)-[*]->(d) WHERE x.Name = 'pqr' RETURN x,d; Here (d) may could be either NodeY or NodeZ. I'm looking to handle different nodetypes separately. Something like: MATCH (x:NodeX)-[*]->(d) WHERE x.Name = 'pqr' WITH d CASE WHEN typeof(d)=NodeY THEN {MATCH (y:NodeY)-[*]-(z:NodeZ)} WHEN typeof(d)=NodeZ THEN {MATCH (z:NodeZ)-[*]-(y:NodeY)} RETURN y,z y and z correspond to d. Is this possible to do so?
Nodes have "labels", not "types" (the latter term only applies to relationships). To get the labels of a node, you can use the LABELS() function. So, to test if node n has the label Foo, you can do something like this in Cypher: CASE WHEN 'Foo' IN LABELS(n) THEN ... However, the CASE clause cannot contain a MATCH clause. [EDITED] In your specific case, something like this query (which assumes that, as you said, the only labels possible for d are NodeY and NodeZ) may work: MATCH (x:NodeX)-[*]->(d) WHERE x.Name = 'pqr' WITH d, CASE WHEN 'NodeY' IN LABELS(d) THEN 'NodeZ' ELSE 'NodeY' END AS otherLabel MATCH (d)-[*]-(other) WHERE otherLabel IN LABELS(other) RETURN d, other;
Neo4j
44,835,575
12
I'm trying store a map or json object as a property in Neo4j, but it doesn't work.
That's a limitation of node properties right now. You have a few workarounds to choose from. You can turn your json object into a string and save it as a property. You can use APOC Procedures to convert JSON strings to and from Cypher map objects. You can instead save the map properties as properties on the node, though that loses the grouping you would get from the object itself. If #2 isn't enough, you could also alter your graph model so the data in the JSON object corresponds to graph objects, nodes and properties related to the original node.
Neo4j
44,364,282
12
Every node in my DB has a property that holds a list. I need to check whether any item in a given list is in that property. I'm looking for a query like match (n) where any(x in n.list where x=[101,102,103]) return n - which means "check if n.list contains 101, 102, 103. If so, return n" Is there anything like that in cypher?
You pretty much have the answer to your question ! Check this : https://neo4j.com/docs/cypher-manual/current/functions/predicate/#functions-any, the any predicate exists. The only error in your query is x=[101,102,103] that you should change by x IN [101,102,103] So the final query is : MATCH (n) WHERE any(x IN n.list WHERE x IN [101,102,103]) RETURN n
Neo4j
39,327,437
12
I have an existing live neo4j db with relationships like this... User-[:Owner]->Item User contains the usual properties; name, email etc. Owner relationship has created_on property Item has a bunch of properties about the item; title, description etc. I want to add in a geo-location property for the Item. This will be a latitude and longitude of where the user created the item. A JSON api is serving up this data to our clients. The API will merge some of the data, so an Item object in the api will have a nested User object as a property of it... "item": { "title":"my item", "user":{ "name":"smith" } } And I was initially thinking the location would follow suit... "item": { "title":"my item", "user":{ "name":"smith" }, "geo_position":{ "latitude":"10.123456789", "longitude":"10.123456789" } } As we cant nest data in Neo, was wondering how to store this data... JSON serialise the latitude and longitude data under a geo_position property of the Item ? As properties of the relationship Owner.latitude? As a new Node ? Location `User-[:owns]->Mite<-[:created_at]-Location? As individual properties of the Item so not nested, item.latitude ? 1 - I assume we cant query. 2 - doesn't feel like the right place. 3 - its extremely unlikely 2 Items will have the same location as lat long is very precise, so almost No Items will share this node, so is it really a node? So is 4 really the way to do it, and just not nest them ? m
You own analysis is basically correct. I would go with number 4. Here is more about why number 2 is not a good idea. Logically: the location of an item belongs in that item's node, not in a particular relationship to it. Practically: if the object changed ownership you should not have to copy its location to a new relationship, and querying for an item's location should be as quick and simple as just getting its node.
Neo4j
36,743,819
12
A co-worker coded something like this: match (a)-[r]->(b), (c) set c.x=y What does the comma do? Is it just shorthand for MATCH?
Since Cypher's ASCII-art syntax can only let you specify one linear chain of connections in a row, the comma is there, at least in part, to allow you to specify things that might branch off. For example: MATCH (a)-->(b)<--(c), (b)-->(d) That represents three nodes which are all connected to b (two incoming relationships, and one outgoing relationship. The comma can also be useful for separating lines if your match gets too long, like so: MATCH (a)-->(b)<--(c), (c)-->(d) Obviously that's not a very long line, but that's equivalent to: MATCH (a)-->(b)<--(c)-->(d) But in general, any MATCH statement is specifying a pattern that you want to search for. All of the parts of that MATCH form the pattern. In your case you're actually looking for two unconnected patterns ((a)-[r]->(b) and (c)) and so Neo4j will find every combination of each instance of both patterns, which could potentially be very expensive. In Neo4j 2.3 you'd also probably get a warning about this being a query which would give you a cartesian product. If you specify multiple matches, however, you're asking to search for different patterns. So if you did: MATCH (a)-[r]->(b) MATCH (c) Conceptually I think it's a bit different, but the result is the same. I know it's definitely different with OPTIONAL MATCH, though. If you did: MATCH (a:Foo) OPTIONAL MATCH (a)-->(b:Bar), (a)-->(c:Baz) You would only find instances where there is a Foo node connected to nothing, or connected to both a Bar and a Baz node. Whereas if you do this: MATCH (a:Foo) OPTIONAL MATCH (a)-->(b:Bar) OPTIONAL MATCH (a)-->(c:Baz) You'll find every single Foo node, and you'll match zero or more connected Bar and Baz nodes independently. EDIT: In the comments Stefan Armbruster made a good point that commas can also be used to assign subpatterns to individual identifiers. Such as in: MATCH path1=(a)-[:REL1]->(b), path2=(b)<-[:REL2*..10]-(c) Thanks Stefan! EDIT2: Also see Mats' answer below
Neo4j
34,089,692
12
I want to change the color of my nodes based on their properties: Say I have many "Person" nodes. And I want those who live in New York to be red and those who live in Los Angeles to be blue. How would I write that. In cypher or in py2neo?
The styling of nodes and relationships in Neo4j Browser is controlled by a graph style sheet (GRASS), a cousin of CSS. You can view the current style by typing :style in the browser. To edit it, you can click on nodes and relationships and pick colors and sizes, or you can view the style sheet (:style), download it, make changes, and drag-n-drop it back into the view window. Unfortunately for your case, color can only be controlled a) for all nodes and all relationships or b) for nodes by label and relationships by type. Properties can only be used for the text displayed on the node/rel.
Neo4j
33,466,999
12
I wrote the following python code to neo4j using py2neo from py2neo import Graph from py2neo import neo4j,Node,Relationship sgraph = Graph() alice = Node("person",name="alice") bob = Node("person",name="bob") alice_knows_bob = Relationship(alice,"KNOWS",bob) sgraph.create(alice_knows_bob) but i got the following error Traceback (most recent call last): File "C:\Python34\lib\site-packages\py2neo\core.py", line 258, in get response = self.__base.get(headers=headers, redirect_limit=redirect_limit, * *kwargs) File "C:\Python34\lib\site-packages\py2neo\packages\httpstream\http.py",line 966, in get return self.__get_or_head("GET", if_modified_since, headers, redirect_limit, **kwargs) File "C:\Python34\lib\site-packages\py2neo\packages\httpstream\http.py",line 943, in __get_or_head return rq.submit(redirect_limit=redirect_limit, **kwargs) File "C:\Python34\lib\site-packages\py2neo\packages\httpstream\http.py",line 452, in submit return Response.wrap(http, uri, self, rs, **response_kwargs) File "C:\Python34\lib\site-packages\py2neo\packages\httpstream\http.py",line 489, in wrap raise inst py2neo.packages.httpstream.http.ClientError: 401 Unauthorized During handling of the above exception, another exception occurr ed: Traceback (most recent call last): File "neo.py", line 7, in <module> sgraph.create(alice_knows_bob) File "C:\Python34\lib\site-packages\py2neo\core.py", line 704, in create statement = CreateStatement(self) File "C:\Python34\lib\site-packages\py2neo\cypher\create.py", 44,in__init__ self.supports_node_labels = self.graph.supports_node_labels File "C:\Python34\lib\site-packages\py2neo\core.py", line 1078, in supports_node_labels return self.neo4j_version >= (2, 0) File "C:\Python34\lib\site-packages\py2neo\core.py", line 956, in neo4j_version return version_tuple(self.resource.metadata["neo4j_version"]) File "C:\Python34\lib\site-packages\py2neo\core.py", line 213, in metadata self.get() File "C:\Python34\lib\site-packages\py2neo\core.py", line 261, in get raise Unauthorized(self.uri.string) py2neo.error.Unauthorized: http://localhost:7474/db/data/ can anyone please help me.This is the first time i writing python code to connect to neo4j.
If you're using Neo4j 2.2, authentication for database servers is enabled by default. You need to authenticate before performing further operations. Read documentation. from py2neo import authenticate, Graph # set up authentication parameters authenticate("localhost:7474", "user", "pass") # connect to authenticated graph database sgraph = Graph("http://localhost:7474/db/data/") # create alice and bob ... From the same documentation, Py2neo provides a command line tool to help with changing user passwords as well as checking whether a password change is required. For a new installation, use: $ neoauth neo4j neo4j my-p4ssword Password change succeeded After a password has been set, the tool can also be used to validate credentials $ neoauth neo4j my-p4ssword Password change not required
Neo4j
29,986,317
12
In Neo4j 2.1.6, I have nodes that are non-unique in respect of a certain property, inputID. Using Cypher, how do I remove all nodes that are duplicates in terms of a given property, leaving only uniques? I have tried the following... MATCH (n:Input) WITH n.inputID, collect(n) AS nodes WHERE size(nodes) > 1 FOREACH (n in tail(nodes) | DELETE n) ...but it results in... Expression in WITH must be aliased (use AS) (line 2, column 6) "WITH n.inputID, collect(n) AS nodes" ^ Thanks, G
You're not aliasing that WITH variable. Change this: WITH n.inputID, collect(n) AS nodes To this: WITH n.inputID AS inputID, collect(n) AS nodes
Neo4j
28,771,150
12
I am using Neo4j as my primary database. It is a nice piece of graph database that gives me very good control over connections between nodes. However, it seems to lack highly in searching full text (search feature on a website). And therefore, I am thinking of using Elasticsearch for creating search feature on my application. But there are few issues while doing this. Let's say we are searching for user posts. In neo4j posts could have the following model. (post)<-[:AUTHOR]-(user) (post)-[:LIKED_BY]->(otherusers) (post)-[:COMMENTED_BY]->(otherusers) (post)-[:HAS_PHOTO]->(photos) Nice thing about Neo4j (let's say while getting posts in a user profile) is that you can grab all this at once (also profile picture and user details while you're at it and if you have already liked the post). That is a lot of detail in one query (cypher command). Now if we want to give the same level of detail to Elasticsearch output I can think of the following at the moment: Store everything in Neo4j and Elasticsearch. When a text is searched list the results from elasticsearch itself. But there are still problems like getting if the user has already liked the post (this might need querying neo again for each post? this sounds not so nice) Store post id in Elasticsearch. When populating search results, grab information of each post from neo4j database with this post id and display the results. (10 results -> 10 separate calls, sounds very inefficient again) Get a list of ids that the Elasticsearch provides and make 1 call to neo4j and grab results (don't know how to do this or if there are performance issues). A cypher reference could be helpful. Any solutions apart from these? These sound a little inefficient.
This is a bit of an opinion-based question because it doesn't have a "right" answer, so prepare for the SO no-fun hammer to come crashing down... but I've been thinking that a one-two (Elasticsearch then Neo) punch is the best way to handle this: index properties in Elasticsearch, perform a full-text search to get possible IDs, then build a Cypher match that limits results to returned IDs. In Cypher, you can use IN [] to return records that match within an array. So you could do MATCH (u:Student { age: 30 }) WHERE ID(u) IN [1, 2, 3, 4] RETURN u. The trick of integrating Elasticsearch with Neo, then, is to make it easy to build Cypher queries around ES results. I don't really have tips on doing that cause it will depend on your language and driver. In Neo4j.rb, I'm thinking about trying to automate this so you can do this: student.lessons(:l).where(name: 'Chris').to_a ...and it'll know that the Lesson model is using Elasticsearch, do the query, and then change the query for the user so it is effectively this: student.lessons(:l).where('ID(l) IN {elasticsearch_results}').params(elasticsearch_results: [1, 2, 3, 4]).to_a` I've been using Searchkick for full-text search with Neo and it's been going well. I think this is doable. Not a solution to your problem but it's how I'm thinking through it, so maybe it'll give you some ideas. It's worth noting that Neo does have fuzzy search using =~, it just doesn't use indexes so there may be a performance hit. This might not be a problem, though, since you can filter the number of nodes and properties Cypher has to inspect by adding more information to other parts your query. You should do some benchmarks with your data to figure out if the added overhead of Elasticsearch and more complicated queries are necessary.
Neo4j
28,094,985
12
This should be easy, I am overlooking something. I want to match a group of nodes and return all where the ID matches any of a group of given IDs. Something like this: MATCH (b:`Band`)-[r:`something`]->(u:`SomethingElse`) WHERE b.uuid IN ['1', '2', '3'] RETURN b That returns the first node that matches. I want all that match. What am I missing?
This worked. Leaving this up in case anyone else ever wants to know how to do it.
Neo4j
26,185,360
12
I have a graph with approximately nine million nodes, and twelve million relationships. For each of the nodes within the graph there is a subset of properties for each respective node which forms a unique identity for the node, by Label. The graph is being updated by various data sources which augment existing nodes within the graph, or create new nodes if the nodes don't exist. I don't want to create duplicates according to the unique set of properties within the graph during the update. For example, I have People in the graph, and their uniqueness is determined by their first name and last name. The following code is to create two distinct people: CREATE (p:Person{first:"barry",last:"smith",height:187}); CREATE (p:Person{first:"fred",last:"jones",language:"welsh"}); Later, from one of the data sources I receive the following data records (one per line): first: "fred", last: "lake", height: 201 first: "barry", last: "smith", language: "english" first: "fred", last: "jones", language: "welsh", height: 188 first: "fred", last: "jones", eyes: "brown" first: "barry", last: "smith" After updating the graph I want to have the following nodes: (:Person{first:"fred",last:"jones",language:"welsh",height:"188,eyes:"brown"}) (:Person{first:"barry",last:"smith",language"english",height:187}) (:Person{first:"fred",last"lake",height:201}) I'm trying to formulate a MERGE query which can do this kind of update. I have come up with the following approach: Start with a MERGE that uses the uniqueness properties (first and last from the example) to find or create the initial node; Then do a SET containing each property defined in the incoming record. So, for the three examples records given above: MERGE (p:Person{first:"fred",last:"lake"}) SET p.height = 201; MERGE (p:Person{first:"barry",last:"smith"}) SET p.language = "english"; MERGE (p:Person{first:"fred",last:"jones"}) SET p.language = "welsh", p.height = 188; MERGE (p:Person{first:"fred",last:"jones"}) SET p.eyes = "brown"; MERGE (p:Person{first:"barry",last:"smith"}); I've tried this out and it works, but I'm curious to know whether this is the best way (most efficient...) to ensure uniqueness in the nodes based on a set of properties, and allow additional information to be added (or not) as updates come in over time?
Just a naive approach: what if you run a MERGE and just create or update it? Given your list of records, consider each record as a map: { first: "fred", last: "lake", height: 201 } { first: "barry", last: "smith", language: "english" } { first: "fred", last: "jones", language: "welsh", height: 188 } { first: "fred", last: "jones", eyes: "brown" } { first: "barry", last: "smith" } Then write your query in a parametric way: MERGE (p:Person { first: { map }.first, last: { map }.last }) ON CREATE SET p = { map } ON MATCH SET p += { map } Description of the query: In case of creation it should create a new node using all the properties passed in the {map} In case of matching it should add new properties to the node without deleting any I've run some queries in console of the page linked above with a MERGE ON MATCH and it seems to update existing properties to new values. The queries I've run are the following: MATCH (peter { name: 'Peter' }) RETURN peter MERGE (peter { name: 'Peter' }) ON MATCH SET peter += { hungry: TRUE , position: 'Entrepreneur' } MATCH (peter { name: 'Peter' }) RETURN peter // added two new properties here MERGE (peter { name: 'Peter' }) ON MATCH SET peter += { hungry: FALSE , position: 'Entrepreneur' } MATCH (peter { name: 'Peter' }) RETURN peter // hungry is now false in here
Neo4j
25,177,788
12
I'm trying to use regular expressions in a cypher WHERE clause. I would like to match nodes in which a node's property Text contains a specific word, as a word and not part of it. MATCH (n:) WHERE n.Text =~ '\bword\b' return n; This query doesn't return anything although nodes containing the word "word" exist in my graph. Does cypher allow the use of standard regular expressions? Are there limitations in its regular expression implementation?
There were 3 problems in your query: (n:) should be (n), since you are not specifying a label. Back slashes must be escaped by a preceding back slash. The regex needs to match the entire property value (I assume that your test value was fairly long). This query should work: MATCH (n) WHERE n.Text =~ '.*\\bword\\b.*' RETURN n; See here for documentation related to Regular Expressions in Neo4j
Neo4j
23,834,692
12
I was reading a paper published by Neo4J (a while ago): http://dist.neo4j.org/neo-technology-introduction.pdf and on the 2nd to last page the Drawbacks section states that Neo4J is not good for arbitrary queries. Say I had Nodes of users with the following properties: NAME, AGE, GENDER And the following relationships: LIKE (points to Sports, Technology, etc. NODE) and FRIEND (Points to another USER). Is Neo4J not very efficient in querying something similar to: Find FRIENDS (of given node) that LIKE Sports, Tech, & Reading that were OVER_THE_AGE 21. Therefore, you must first find the FRIEND edges of USER1 and then find the LIKE edges of friends and determine if that node was called Sports and you must determine if the age property of the given friend is > 21. Is this a poor data model to begin with? And especially for graph databases? The reason for the LIKE relationship is in the event that you want to find all people who LIKE Sports. What would be the better database choice for this? Redis, Cassandra, HBase, PostgreSQL? And Why? Does anyone have any empirical data regarding this?
This is a general question about the nature of graph databases. Hopefully one of the neo4j devs will jump in here, but here is my understanding. You can think of any database as being "naturally indexed" in a certain way. In a relational database, when you look up a record in storage, generally the next record is stored right next to it in storage. We might call this a "natural index" because if what you want to do is scan through a bunch of records, the relational structure is just fundamentally set up to make that perform really well. Graph databases on the other hand are generally naturally indexed by relationships. (Neo4J devs, jump in if this needs refinement in terms of how neo4j does storage on disk). This means that in general, graph databases traverse relationships very quickly, but perform less well on mass/bulk queries. Now, we're only talking about relative performance. Here's an example of an RDBMS style query. I'd expect MySQL to blow away neo4j in performance on this query: MATCH n WHERE n.name='Abe' RETURN n; Note that this exploits no relationships at all, and forces the DB to scan ALL nodes. You could improve this by narrowing it down to a certain label, or by indexing on name, but in general, if you had a MySQL table of "people" with a "name" column, an RDBMS is going to kick ass on queries like this, and graph is going to do less well. OK, so that's the downside. What's the upside? Let's take a look at this query: MATCH n-[r:foo|bar*..5]->m RETURN m; This is an entirely different beast. The real action of the query is in matching a variable length path between n and m. How would we do this in relational? We might set up a "nodes" and "edges" table, then add a PK/FK relationship between them. You then could write an SQL query that recursively joined the two tables to traverse that "path". Believe me, I have tried this in SQL, and it requires wizard-level skill to express the "between 1 and 5 hops" part of that query. Also, RDMBS will perform like a dog on this query, because it's not terribly selective, and the recursive query is quite expensive, doing all those repetitive joins. On queries like this, neo4j is going to kick RDBMS's ass. So -- on your question about arbitrary queries -- no system in the world is good at arbitrary queries, that is to say, all queries. Systems have strengths and weaknesses. Neo4J can execute arbitrary queries, but there's no guarantee that for some class of queries, it will perform better than some alternative. But that observation is general - the same is true of MySQL, MongoDB, and anything else you choose. OK, so bottom lines, and observations: Graph databases perform well on a class of queries where RDMBS (and others) perform poorly. Graph databases aren't tuned for high performance on mass/bulk queries like the example I provided. They can do them, and you can tune their performance to improve things there, but they're never going to be as good as an RDBMS This is because of fundamentally how they're laid out, how they think about/store the data. So what should you do? If your problem consists of a lot of relationship/path traversal type problems, graph is a big win! (I.e., your data is a graph, and traversing relationships is important to you). If your problem consists of scanning large collections of objects, then the relational model is probably a better fit. Use tools in their area of strength. Don't use neo4j like a relational database, or it will perform about as well as if you tried to use a screwdriver to pound nails. :)
Neo4j
22,821,269
12
I struggle to return the node with the largest value, and process that node further. Here's how I would return a node with the largest value: START n=node(startnode) MATCH n-[:TYPE]-m RETURN m ORDER BY m.value DESC LIMIT 1 but now I am in a subquery START n=node(somenode) MATCH n-[:TYPE1]-q WITH DISTINCT q MATCH q-[:TYPE2]-m and then the ORDER BY .. LIMIT 1 obviously doesn't work anymore because I want one result for each q. How is this done? Also, once I have the m with largest value for each q I'll also need to process it: RETURN q, m.maxvalue, x.anothervalue from MATCH m-[:HAS_ONE_LINK_TO]->x So while I've been playing with collections (collect(m) ), I haven't figured a way to expand them back to "result rows" for applying that MATCH.
Untested... let me know if it works for you: START n=node(somenode) MATCH n-[:TYPE1]-q // initial query WITH DISTINCT q MATCH q-[:TYPE2]-m WITH q, max(m.value) as max // get max for q MATCH q-[:TYPE2]-m WHERE m.value = max // find the max m for each q WITH q, m MATCH m-[:HAS_ONE_LINK_TO]->x // find x from m RETURN q, m, x Edit: because of recent upvotes on this old answer... please consider a fresher query written in 3.x era using collect/unwind -- also untested (take care to not do this if the number of ms will be quite large, as they may be stored in the partial result of the query instead of being able to stream them): MATCH (n:Label)-[:TYPE1]-(q) // initial query WITH DISTINCT q MATCH (q)-[:TYPE2]-(m) WITH q, max(m.value) as max, collect(m) as ms // get max for q, collect ms UNWIND ms as m WHERE m.value = max MATCH (m)-[:HAS_ONE_LINK_TO]->(x) // find x from m RETURN q, m, x
Neo4j
17,747,114
12
Apache Giraph vs Neo4j : Are the traversal algorithms across nodes totally different in theses two graph processing systems ? If we were to traverse say a social graph using Giraph and Neo4j on data stored in single machine (not distributed) , which would perform better and Why?
Hands down Neo4j. Giraph's graph computations run as Hadoop jobs, because they are meant to work for large distributed graphs. The overhead of managing these jobs is too large to be efficient on a small scale graph running on a pseudo-distributed single machine cluster. Not only that, but Neo4j's specialty is traversals. A big reason for that is because Neo4j actually stores adjacent relationships in doubly linked lists in the filesystem. Check out this blog entry : http://digitalstain.blogspot.nl/2010/10/neo4j-internals-file-storage.html It explains the way Neo4j optimized the way they store the graph, for fast graph operations such as traversals.
Neo4j
17,477,619
12
A Markov chain is composed of a set of states which can transition to other states with a certain probability. A Markov chain can be easily represented in Neo4J by creating a node for each state, a relationship for each transition, and then annotating the transition relationships with the appropriate probability. BUT, can you simulate the Markov chain using Neo4J? For instance, can Neo4J be coerced to start in a certain state and then make transitions to the next state and the next state based upon probabilities? Can Neo4J return with a printout of the path that it took through this state space? Perhaps this is easier to understand with a simple example. Let's say I want to make a 2-gram model of English based upon the text of my company's tech blog. I spin up a script which does the following: It pulls down the text of the blog. It iterates over every pair of adjacent letters and creates a node in Neo4J. It iterates again over every 3-tuple of adjacent letters and then creates a Neo4J directed relationship between the node represented by the first two letters and the node represented by the last two letters. It initializes a counter on this relationship to 1. If the relationship already exists, then the counter is incremented. Finally, it iterates through each node, counts how many total outgoing transitions have occurred, and then creates a new annotation on each relationship of a particular node equal to count/totalcount. This is the transition probability. Now that the Neo4J graph is complete, how do I make it create a "sentence" from my 2-gram model of English? Here is what the output might look like: IN NO IST LAT WHEY CRATICT FROURE BIRS GROCID PONDENOME OF DEMONSTURES OF THE REPTAGIN IS REGOACTIONA OF CRE.
Neo4j doesn't provide the functionality you're asking for out of the box, but since you've already come as far as correctly populating your database, the traversal that you need is just a few lines of code. I've recreated your experiment here, with a few modifications. First of all, I populate the database with a single pass through the text (steps 2 and 3), but that's a minor. More importantly, I only store the number of occurrences on each relationship and the total number on the node (step 4), as I don't think there is a need to pre-calculate probabilities. The code that you're asking for then looks something like this: /** * A component that creates a random sentence by a random walk on a Markov Chain stored in Neo4j, produced by * {@link NGramDatabasePopulator}. */ public class RandomSentenceCreator { private final Random random = new Random(System.currentTimeMillis()); /** * Create a random sentence from the underlying n-gram model. Starts at a random node an follows random outgoing * relationships of type {@link Constants#REL} with a probability proportional to that transition occurrence in the * text that was processed to form the model. This happens until the desired length is achieved. In case a node with * no outgoing relationships it reached, the walk is re-started from a random node. * * @param database storing the n-gram model. * @param length desired number of characters in the random sentence. * @return random sentence. */ public String createRandomSentence(GraphDatabaseService database, int length) { Node startNode = randomNode(database); return walk(startNode, length, 0); } private String walk(Node startNode, int maxLength, int currentLength) { if (currentLength >= maxLength) { return (String) startNode.getProperty(NAME); } int totalRelationships = (int) startNode.getProperty(TOTAL, 0); if (totalRelationships == 0) { //terminal node, restart from random return walk(randomNode(startNode.getGraphDatabase()), maxLength, currentLength); } int choice = random.nextInt(totalRelationships) + 1; int total = 0; Iterator<Relationship> relationshipIterator = startNode.getRelationships(OUTGOING, REL).iterator(); Relationship toFollow = null; while (total < choice && relationshipIterator.hasNext()) { toFollow = relationshipIterator.next(); total += (int) toFollow.getProperty(PROBABILITY); } Node nextNode; if (toFollow == null) { //no relationship to follow => stay on the same node and try again nextNode = startNode; } else { nextNode = toFollow.getEndNode(); } return ((String) nextNode.getProperty(NAME)).substring(0, 1) + walk(nextNode, maxLength, currentLength + 1); } private Node randomNode(GraphDatabaseService database) { return random(GlobalGraphOperations.at(database).getAllNodes()); } }
Neo4j
16,601,236
12
I'm new to both Scala and Neo4j. I want to create a Neo4j database using Scala. Is there any resource where i can find some ready made code for creating nodes, deleting nodes, adding properties, creating indexes and etc. Thanks.
Actually there are several options it depends on (a) how you want to communicate with neo4j (Rest or not) (b) your runtime environment. When your application is ok with a REST only communication and you're ok to use ANORM to access your (data). There is a promising driver that is currently good enough to do a plenty of thing using Cypher as request language. You can find it there (AnormCypher) : https://github.com/AnormCypher/AnormCypher. The power of ANORM is a source of a lot of debate, but I think it has a lot of good feature. There is also the FaKod scala driver which is very complete, and the second version (M1 for now) will include REST capabilities as well. The power of this driver (neo4j-scala) is the clean DSL it provides to abstract traversal internals, it's pretty intuitive and well documented. On the other hand, I had started my driver a while, but didn't had time to put much effort of it (it'll change soon). The current version is still rough and tightly coupled to a play application. But this driver tries to use amap the reactivity of future (now akka based) and the json api of play. However, this way shall not be the most productive due to a lack of doc and cleaning... any help is welcome ;-). Also this is a play plugin as well then is pretty easy to configure and inject. For more information in general regarding drivers, you should go there: http://www.neo4j.org/develop/drivers
Neo4j
15,515,865
12
I am trying to retrieve a unique set of elements linked to a given graph node. I have some nodes loaded into a Neo4j graph database, which are connected using a 'TO' relationship (e.g. node 6 connects 'TO' node 7). I have been able to retrieve all paths between my start node and others linked by the 'TO' relationship using: start a = node(6) match p = (a)-[r:TO*..]->(b) return distinct EXTRACT(n in nodes(p): n); This gives me output paths that are distinct, but still have duplicate node values, e.g.: +-------------------------------------------------------+ | p | +-------------------------------------------------------+ | [Node[6]{},:TO[5] {},Node[7]{}] | | [Node[6]{},:TO[5] {},Node[7]{},:TO[9] {},Node[11]{}] | etc... How can I combine these paths into a single list containing unique path values? I have tried using COLLECT but this just results in a nested version of the above results: start a = node(6) match p = (a)-[r:TO*..]->(b) return collect(distinct p); [[Node[6]{},:TO[5] {},Node[7]{}],[Node[6]{},:TO[5] {},Node[7]{},:TO[9] {}, ... ]
I'm confused about exactly the result you want (can you give an example if this isn't right?). Do you want paths or do you want nodes? If you want nodes, then maybe you just want: start a = node(6) match (a)-[:TO*]->(b) return collect(distinct b);
Neo4j
14,345,555
12
I wonder why neo4j has a Capacity Limit on Nodes and Relationships. The limit on Nodes and Relationships is 2^35 1 which is a "little" bit more then the "normal" 2^32 integer. Common SQL Databases for example mysql stores there primary key as int(2^32) or bigint(2^64)2. Can you explain me the advantages of this decision? In my opinion this is a key decision point when choosing a database.
It is an artificial limit. They are going to remove it in the not-too-distant future, although I haven't heard any official ETA. Often enough, you run into hardware limits on a single machine before you actually hit this limit. The current option is to manually shard your graphs to different machines. Not ideal for some use cases, but it works in other cases. In the future they'll have a way to shard data automatically--no ETA on that either. Update: I've learned a bit more about neo4j storage internals. The reason the limits are what they are exactly, are because the id numbers are stored on disk as pointers in several places (node records, relationship records, etc.). To increase it by another power of 2, they'd need to increase 1 byte per node and 1 byte per relationship--it is currently packed as far as it will go without needing to use more bytes on disk. Learn more at this great blog post: http://digitalstain.blogspot.com/2010/10/neo4j-internals-file-storage.html Update 2: I've heard that in 2.1 they'll be increasing these limits to around another order of magnitude higher than they currently are.
Neo4j
12,971,786
12
I'm just getting into graph databases, and I seem to keep running into a problem deciding between using an "index node" or an "indexed property" for tracking things like "node type". Since I've no real experience thus far, I don't have any information to base the decision on and both approaches seem to be equally valid. So, the question is: What are the tradeoffs between two approaches, and how does scale (ie. number of nodes) affect the decision? For a sample scenario, lets assume there are two types of "things": User and Product, and the edges between the User nodes and the Product nodes don't matter so much, but what we care about is if we want type: User and type: Product properties on each node, or if we want each node to have an edge pointing back at a User node and a Product node, respectively. Which approach is better under which circumstances? Note: I'm looking at Neo4j and Titan in particular, but I would think that this will tend to apply more generally as well.
First, you need to ask yourself: Does the type of a vertex/node need to be indexed? I.e. do you need to retrieve vertices/nodes by their type, let's say, retrieve all 'user' vertices from the graph or do you need to answer queries that start by retrieving all vertices of a given type and then filter/process those further? If the answer to this question is yes, then I suggest you store the type as a string property that is indexed. Or, if you are developing in a jvm based language, you could define a type enum and use that as the property type for more type safety and automatic error checking. Titan supports arbitrary user defined classes/enums as property types and will compress those for a low memory footprint. However, the downside of this approach is that this won't scale because you are building a low selectivity index. What that means is that there will likely be very many vertices of type 'user' or 'product' and all those need to be associated with the index entry for 'user' or 'product' respectively. This makes maintaining and querying this index very expensive and hard to scale (imagine facebook had a 'type' index: the 'photo' entry would have billions of vertices under it). If you are not (yet) concerned with scaling, then this can work. If the answer to the question is no, then I suggest to model types as vertices/nodes in the graph. I.e. have a 'user' vertex and a 'product' vertex and an edge labeled 'type' from each user to the 'user' vertex, etc. The advantage of this approach is that you use the graph to model your data rather than having string values outside of your database represent crucial type information. As you build your application, the graph database will become its central component and last for a long time. As programming languages and developers come and go, you don't want data modeling and type information to go with them and be faced with the question: "What does SPECIAL_USER mean?" Rather, have a SPECIAL_USER vertex and add provenance information to it, i.e., who created this type, what does it represent and a short description - all in the database. One problem with this approach is that the 'user' and 'product' vertices will have a lot of edges incident on them as your application scales. In other words, you are creating supernodes which create scaling issues. This is why Titan introduced the concept of a unidirectional edge. A unidirectional edge is like a link on the web: the starting vertex points to another vertex, but that vertex is unaware of the edge. Since you don't want to traverse from the 'user' vertex to all user vertices, you aren't loosing anything but gaining in scalability and performance.
Neo4j
12,754,619
12
I have an object and I need to keep a history of all changes made to it. How would I implement this using neo4j?
As with a RDBMS, it would depend on your domain and data query requirements. Does your application require regular access to all versions of the object or usually just to the most recent, with the older versions available via the current one? An example of this could be pages on Wikipedia. As as example, let's say we have a page which is on version 3. We could then model this as follows: (pages)-[:PAGE]->(V3)-[:PREV]->(V2)-[:PREV]->(V1) ^ ^ | | category current node version of page Here, only the current version can be seen to form part of the main structure but you may wish to allow all versions to form part of that structure. In this case, you could use relationship properties to indicate the version and have all page versions link from the category node: (V1) ^ | [:PAGE(v=1)] | (pages)-[:PAGE(v=2)]->(V2) | [:PAGE(v=3)] | v (V3) Here, you can immediately traverse to a particular version of the page by simply specifying the version in which you are interested. A third option could be that you wish all older versions to be completely separate from the main structure. For this you could use multiple category nodes, one for (current_pages) and another for (old_pages). As each page is superseded by a new version, it becomes unlinked from the former category and instead linked to the latter. This would form more of an "archive" type of system where the older versions could even be moved into a separate database instance. So you have these three options, plus more that I haven't thought of! Neo4j allows you great flexibility with this sort of design and there's absolutely no "right" answer. If none of these inspire you however, post a little more information about your domain so that the answer can be more tailored for your needs. Cheers, Nige
Neo4j
12,707,538
12
Is there a way to iterate through every node in a neo4j database using py2neo? My first thought was iterating through GraphDatabaseService, but that didn't work. If there isn't a way to do it with py2neo, is there another python interface that would let me? Edit: I'm accepting @Nicholas's answer for now, but I'll update it if someone can give me a way that returns a generator.
I would suggest doing that with asynchronous Cypher, something like: from py2neo import neo4j, cypher graph_db = neo4j.GraphDatabaseService() def handle_row(row): node = row[0] # do something with `node` here cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle_row) Of course you might want to exclude the reference node or otherwise tweak the query. Nige
Neo4j
11,076,260
12