Cypher to Neo4JClient Distinct Collect - neo4j

I am trying to get a path from a base node to its root node as 1 row. The Cypher query looks like this:
start n = node:node_auto_index(Name = "user1") match path = (n-[r:IS_MEMBER_OF_GROUP*]->b) return last(collect(distinct path));
But when changing this over to the Neo4JClient syntax:
var k = clientConnection.Cypher
.Start(new { n = "node:node_auto_index(Name = 'user1')" })
.Match("path = (n-[r:IS_MEMBER_OF_GROUP*]->b)")
.ReturnDistinct<Node<Principles>>("last(collect(path))").Results;
It gets an error:
{"Value cannot be null.\r\nParameter name: uriString"}
When continuing on from there:
Neo4jClient encountered an exception while deserializing the response from the server. This is likely a bug in Neo4jClient.
Please open an issue at https://bitbucket.org/Readify/neo4jclient/issues/new
To get a reply, and track your issue, ensure you are logged in on BitBucket before submitting.
Include the full text of this exception, including this message, the stack trace, and all of the inner exception details.
Include the full type definition of Neo4jClient.Node`1[[IQS_Neo4j_TestGraph.Nodes.Principles, IQS Neo4j TestGraph, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Include this raw JSON, with any sensitive values replaced with non-sensitive equivalents:
{
"columns" : [ "last(collect(path))" ],
"data" : [ [ {
"start" : "http://localhost:7474/db/data/node/3907",
"nodes" : [ "http://localhost:7474/db/data/node/3907", "http://localhost:7474/db/data/node/3906", "http://localhost:7474/db/data/node/3905", "http://localhost:7474/db/data/node/3904" ],
"length" : 3,
"relationships" : [ "http://localhost:7474/db/data/relationship/4761", "http://localhost:7474/db/data/relationship/4762", "http://localhost:7474/db/data/relationship/4763" ],
"end" : "http://localhost:7474/db/data/node/3904"
} ] ]
}
How would one convert the cypher query to Neo4JClient query?

Well, the thing you are returning is a PathsResult not a Node<>, so if you change your query to be:
var k = clientConnection.Cypher
.Start(new { n = "node:node_auto_index(Name = 'user1')" })
.Match("path = (n-[r:IS_MEMBER_OF_GROUP*]->b)")
.ReturnDistinct<PathsResult>("last(collect(path))").Results; //<-- Change here
you will get results, this returns what I get from running your query against my db, if you specifically want the nodes this post: Getting PathsResults covers converting to actual nodes and relationships.
One other thing, (and this will help the query perform better as neo4j can cache the execution plans easier), is that you can change your start to make it use parameters by doing:
.Start(new { n = Node.ByIndexLookup("node_auto_index", "Name", "user1")})

Related

How to make this query more efficient in neo4j?

headers = {'Accept': 'application/json;charset=UTF-8','Content-Type':'application/json'}
data = {
"statements" : [
{
"statement" : "MATCH (n:Product) RETURN n.name, name.id",
# "parameters" : { "nproduct" : 5 }
} ]
}
r = requests.post(URL, headers = headers,json=data)
data = r.json()['results'][0]['data']
I want to extract nodes from neo4j database. If I have a large amount of Product nodes in the database, how can this query be possible to extract all nodes? The current query has to load all product nodes into memory.
Depends on how large is large. The best way to limit this is to use LIMIT and return sets of Products at a time to your application

Neocons Cypher tquery and accessing values from keys

After calling neo4j with neocons (cy/tquery conn node-query {:_nodeid _nodeid}), how do you perform accessing functions to get property values from the keys that are returned from the neo4j datastore response?
For example if this object was the response from the neo4j datastore, what neocons syntax do I use to access the value stored in key "attributes"?
[ {
"id": "letter-a",
"name": "Letter A",
"attributes": [ ... ]
}]
Currently I can only get so far as (first _response) but (get-in (first _response) [:attributes]) is giving me back nil
******************* EDIT *******************************
Here is the cypher query string I use as an argument to invoke the tquery function:
(def node-query "MATCH (n)-[attributelist:RELATIONSHIPTYPE]->(target)
RETURN n.id AS id,
n.name AS name,
COLLECT({
target : target.id
}) AS attributes;")
I don't understand what type of variable tquery returns? It looks like this object when the client displays it all the way in the browser:
[
{
"id": "node-999990a0a0a0sa0",
"name": "Node Name",
"attributes": [
{
"target": "node-id-one"
},
{
"target": "node-id-two"
},
{
"target": "node-id-two"
},
{
"target": "node-id-two"
},
{
"target": "node-id-three"
}
]
}
]
But I want to intercept what is returned from the tquery before the clojure server delivers it to the client and I want to manipulate the array value of the key "attributes" so I can run a reduce (tally) report before I deliver a rebuilt object response to the client.
{
...
"attributes" : {
"node-id-one" : 1,
"node-id-two" : 3,
"node-id-three" : 1
}
}
But I am having trouble because I do not know the syntax to access the "attributes" key from the object that is returned from the tquery
Sorry I don't understand your question. Which query did you run with tquery?
Usually you return the data you're interested in directly from the query.
e.g
MATCH (p:Person)-[:ACTED_IN]->(m)
WHERE p.name = "Tom Hanks"
RETURN m.title, m.released`
Otherwise you'd have to requery using a label+unique-property
MATCH (m:Movie)
WHERE m.title = "The Matrix"
RETURN m.title, m.released`
or node-id match.
MATCH (m:Movie)
WHERE id(m) = 123
RETURN m.title, m.released`
You usually would use parameters instead of literal values, i.e. {name}, {title}, {id}.
Update
I think for intercepting you would have to look into the neocons implementation.
Note: there is no clojure server, it's a Neo4j server with an http endpoint.
You should be able to do what you want (almost) in cypher.
MATCH (n)-[:RELATIONSHIPTYPE]->(target)
WITH n, target.id as target, count(*) as c
RETURN n.id as id, n.name as name, collect([target,c]) as targets;
Unfortunately right now there are no dynamic map-keys in Cypher, so a tuple-collection will have to do.
PS
You should use a label at least for your n (and optionally target) nodes.

Neo4j and json creating multiple nodes with multiple params

I tried many things but of no use.
I have already raised a question on stackoverflow earlier but I am still facing the same issue.
Here is the link to old stackoverflow question
creating multiple nodes with properties in json in neo4j
Let me try out explaining with a small example
This is the query I want to execute
{
"params" : {
"props" : [
{
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
]
},
"query" : "MATCH (n:Router) where n.NodeId = {props}.NodeId RETURN n"}
For simplicity I have added only 1 props array otherwise there are around 5000 props. Now I want to execute the query above but it fails.
I tried using (props.NodeId}, {props[NodeID]} but everything fails.
Is it possbile to access a individual property in neo4j?
My prog is in c++ and I am using jsoncpp and curl to fire my queries.
If you do {props}.nodeId in the query then the props parameter must be a map, but you pass in an array. Do
"props" : {
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
You can use an array of maps for parameter either with a simple CREATE statement.
CREATE ({props})
or if you loop through the array to access the individual maps
FOREACH (prop IN {props} |
MERGE (i:Interface {nodeId:prop.nodeId})
ON CREATE SET i = prop
)
Does this query string work for you?
"MATCH (n:Router) RETURN [p IN {props} WHERE n.NodeId = p.NodeId | n];"

Can you use parameters in a multi-index lookup cypher query passed over the REST API?

I want to perform a Cypher query similar to:
START n=node:myindex('value:"hello" OR value:"world"') return n
Using the REST API, something like this works:
POST http://localhost:7474/db/data/cypher {"query" : "start n = node:myindex('value=hello OR value=world') return n"}
(from here on in, I'm going to strip the POST <url> bit and just past the JSON)
What I'd like to do is parameterize the query so - ideally:
{
"query" : "start n = node:myindex('value={p0} OR value={p1}') return n",
"params" : { "p0" : "hello", "p1" : "world"}
}
But that gives me:
400 Bad Request
{
"exception" : "BadInputException",
"fullname" : "org.neo4j.server.rest.repr.BadInputException",
"stacktrace" : [ "org.neo4j.server.rest.repr.RepresentationExceptionHandlingIterable.exceptionOnHasNext(RepresentationExceptionHandlingIterable.java:50)", "org.neo4j.helpers.collection.ExceptionHandlingIterable$1.hasNext(ExceptionHandlingIterable.java:60)", "org.neo4j.helpers.collection.IteratorWrapper.hasNext(IteratorWrapper.java:42)", "org.neo4j.server.rest.repr.ListRepresentation.serialize(ListRepresentation.java:58)", "org.neo4j.server.rest.repr.Serializer.serialize(Serializer.java:75)", "org.neo4j.server.rest.repr.MappingSerializer.putList(MappingSerializer.java:61)", "org.neo4j.server.rest.repr.CypherResultRepresentation.serialize(CypherResultRepresentation.java:57)", "org.neo4j.server.rest.repr.MappingRepresentation.serialize(MappingRepresentation.java:42)", "org.neo4j.server.rest.repr.OutputFormat.assemble(OutputFormat.java:179)", "org.neo4j.server.rest.repr.OutputFormat.formatRepresentation(OutputFormat.java:131)", "org.neo4j.server.rest.repr.OutputFormat.response(OutputFormat.java:117)", "org.neo4j.server.rest.repr.OutputFormat.ok(OutputFormat.java:55)", "org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:95)", "java.lang.reflect.Method.invoke(Unknown Source)" ],
"cause" : {
"exception" : "NullPointerException",
"stacktrace" : [ "org.apache.lucene.util.SimpleStringInterner.intern(SimpleStringInterner.java:54)", "org.apache.lucene.util.StringHelper.intern(StringHelper.java:39)", "org.apache.lucene.index.Term.<init>(Term.java:38)", "org.apache.lucene.queryParser.QueryParser.getFieldQuery(QueryParser.java:643)", "org.apache.lucene.queryParser.QueryParser.Term(QueryParser.java:1436)", "org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1319)", "org.apache.lucene.queryParser.QueryParser.Query(QueryParser.java:1245)", "org.apache.lucene.queryParser.QueryParser.TopLevelQuery(QueryParser.java:1234)", "org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:206)", "org.neo4j.index.impl.lucene.IndexType.query(IndexType.java:300)", "org.neo4j.index.impl.lucene.LuceneIndex.query(LuceneIndex.java:227)", "org.neo4j.index.impl.lucene.LuceneIndex.query(LuceneIndex.java:238)", "org.neo4j.cypher.internal.spi.gdsimpl.GDSBackedQueryContext$$anon$1.indexQuery(GDSBackedQueryContext.scala:87)", "org.neo4j.cypher.internal.executionplan.builders.IndexQueryBuilder$$anonfun$getNodeGetter$2.apply(IndexQueryBuilder.scala:83)", "org.neo4j.cypher.internal.executionplan.builders.IndexQueryBuilder$$anonfun$getNodeGetter$2.apply(IndexQueryBuilder.scala:81)", "org.neo4j.cypher.internal.pipes.StartPipe$$anonfun$internalCreateResults$1.apply(StartPipe.scala:36)", "org.neo4j.cypher.internal.pipes.StartPipe$$anonfun$internalCreateResults$1.apply(StartPipe.scala:35)", "scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371)", "org.neo4j.cypher.internal.ClosingIterator$$anonfun$hasNext$1.apply$mcZ$sp(ClosingIterator.scala:36)", "org.neo4j.cypher.internal.ClosingIterator$$anonfun$hasNext$1.apply(ClosingIterator.scala:35)", "org.neo4j.cypher.internal.ClosingIterator$$anonfun$hasNext$1.apply(ClosingIterator.scala:35)", "org.neo4j.cypher.internal.ClosingIterator.failIfThrows(ClosingIterator.scala:86)", "org.neo4j.cypher.internal.ClosingIterator.hasNext(ClosingIterator.scala:35)", "org.neo4j.cypher.PipeExecutionResult.hasNext(PipeExecutionResult.scala:133)", "scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)", "scala.collection.convert.Wrappers$IteratorWrapper.hasNext(Wrappers.scala:29)", "org.neo4j.helpers.collection.ExceptionHandlingIterable$1.hasNext(ExceptionHandlingIterable.java:58)", "org.neo4j.helpers.collection.IteratorWrapper.hasNext(IteratorWrapper.java:42)", "org.neo4j.server.rest.repr.ListRepresentation.serialize(ListRepresentation.java:58)", "org.neo4j.server.rest.repr.Serializer.serialize(Serializer.java:75)", "org.neo4j.server.rest.repr.MappingSerializer.putList(MappingSerializer.java:61)", "org.neo4j.server.rest.repr.CypherResultRepresentation.serialize(CypherResultRepresentation.java:57)", "org.neo4j.server.rest.repr.MappingRepresentation.serialize(MappingRepresentation.java:42)", "org.neo4j.server.rest.repr.OutputFormat.assemble(OutputFormat.java:179)", "org.neo4j.server.rest.repr.OutputFormat.formatRepresentation(OutputFormat.java:131)", "org.neo4j.server.rest.repr.OutputFormat.response(OutputFormat.java:117)", "org.neo4j.server.rest.repr.OutputFormat.ok(OutputFormat.java:55)", "org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:95)", "java.lang.reflect.Method.invoke(Unknown Source)" ],
"fullname" : "java.lang.NullPointerException"
}
}
Is there anyway to achieve this goal?
EDIT
For reference if I pass in:
{
"query" : "start n = node:myindex('value=hello OR value=world') return n"
}
I get back results, I'm presuming the problem lies with the ' surrounding the index query.
It's not possible to parameterize parts of index query. In this case you have to use the whole index query as single parameter as Thomas pointed out in the 2nd snippet of Index parameterization in Cypher REST query

neo4jclient ill formed cypher request sent to server

Trying to execute the following cypher query (which executes ok from neoclipse)
START a=node(*) MATCH a-[:Knows]->p WHERE (p.Firstname! = "Steve" ) RETURN p
from neo4jclient with the following statement
protected void Populate()
{
var client = new GraphClient(new Uri("http://altdev:7474/db/data"));
client.Connect();
var query = client.Cypher
.Start(new RawCypherStartBit("all", "node(*)"))
.Match("all-[:Knows]->p")
.Where((Person p) => p.Firstname == "Steve")
.Return<Node<Person>>("Person");
var people = query.Results;
}
the client throws an exception, as follows
The query was: START all=node(*)
MATCH all-[:Knows]->p
WHERE (p.Firstname! = {p0})
RETURN Person
The response status was: 400 Bad Request
The response from Neo4j (which might include useful detail!) was: {
"message" : "Unknown identifier `Person`.",
"exception" : "SyntaxException",
"fullname" : "org.neo4j.cypher.SyntaxException",
"stacktrace" : [ "org.neo4j.cypher.internal.symbols.SymbolTable.evaluateType(SymbolTable.scala:59)", "org.neo4j.cypher.internal.commands.expressions.Identifier.evaluateType(Identifier.scala:47)", "org.neo4j.cypher.internal.commands.expressions.Expression.throwIfSymbolsMissing(Expression.scala:52)", "org.neo4j.cypher.internal.pipes.ColumnFilterPipe$$anonfun$throwIfSymbolsMissing$1.apply(ColumnFilterPipe.scala:61)", "org.neo4j.cypher.internal.pipes.ColumnFilterPipe$$anonfun$throwIfSymbolsMissing$1.apply(ColumnFilterPipe.scala:61)", "scala.collection.immutable.List.foreach(List.scala:309)", "org.neo4j.cypher.internal.pipes.ColumnFilterPipe.throwIfSymbolsMissing(ColumnFilterPipe.scala:61)", "org.neo4j.cypher.internal.pipes.PipeWithSource.<init>(Pipe.scala:63)", "org.neo4j.cypher.internal.pipes.ColumnFilterPipe.<init>(ColumnFilterPipe.scala:30)", "org.neo4j.cypher.internal.executionplan.builders.ColumnFilterBuilder.handleReturnClause(ColumnFilterBuilder.scala:60)", "org.neo4j.cypher.internal.executionplan.builders.ColumnFilterBuilder.apply(ColumnFilterBuilder.scala:38)", "org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl.prepareExecutionPlan(ExecutionPlanImpl.scala:54)", "org.neo4j.cypher.internal.executionplan.ExecutionPlanImpl.<init>(ExecutionPlanImpl.scala:36)", "org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)", "org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)", "org.neo4j.cypher.internal.LRUCache.getOrElseUpdate(LRUCache.scala:37)", "org.neo4j.cypher.ExecutionEngine.prepare(ExecutionEngine.scala:80)", "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:616)", "org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112)" ]
}
As you can see, essentially the queries are the same. And the nodes I'm trying to get are of _type "Person"
TIA
Marcelo
In your MATCH clause you use the identity p:
.Match("all-[:Knows]->p") // becomes MATCH all-[:Knows]->p
In your RETURN clause you change to using the identity Person:
.Return<Node<Person>>("Person"); // becomes RETURN person
You need to pick one and be consistent.
Integrating some other clean up too, your full query should be:
var query = client.Cypher
.Start(new { all = All.Nodes })
.Match("all-[:Knows]->p")
.Where((Person p) => p.Firstname == "Steve")
.Return<Person>("p");
It's down to the way you are creating the Cypher code, specifically what you are returning:
var query = client.Cypher
.Start(new RawCypherStartBit("all", "node(*)"))
.Match("all-[:Knows]->p")
.Where((Person p) => p.Firstname == "Steve")
.Return<Node<Person>>("p"); // <-- THIS LINE SHOULD SAY 'P' NOT 'Person'
The return statement requires the name to be the same as the node you have defined. So you use: all-[:knows]->p where you define p. Now you need to return it.
(Which is what Peter is saying in his answer :))
You are trying to return a Person node that is not assigned to anything in the query.

Resources