How do you use parameters with neo4j? - neo4j

I am looking at the documentation for neo4j and I see that I can use parameters when I create objects. Specifically when I look at this page I see the code:
{
"props" : {
"position" : "Developer",
"name" : "Andres"
}
}
Query.
CREATE ({ props })
Yet when I use the web interface to access my neo4j database on my local machine I do not know how to specify the parameter. Simply copy/pasting that JSON object yields an error. I see on the page that
Exactly how to submit them depends on the driver in use.
but how does one use them on that command line/web interface?

Cypher supports queries with parameters which are submitted as JSON. For example, the following is the REST API usage. For the Java embedded API please refer to the following documentation: http://docs.neo4j.org/chunked/milestone/tutorials-cypher-parameters-java.html
MATCH (x { name: { startName }})-[r]-(friend)
WHERE friend.name = { name }
RETURN TYPE(r)
Example request
POST http://localhost:7474/db/data/cypher
Accept: application/json; charset=UTF-8
Content-Type: application/json
{
"query" : "MATCH (x {name: {startName}})-[r]-(friend) WHERE friend.name = {name} RETURN TYPE(r)",
"params" : {
"startName" : "I",
"name" : "you"
}
}
Example response
200: OK
Content-Type: application/json; charset=UTF-8
{
"columns" : [ "TYPE(r)" ],
"data" : [ [ "know" ] ]
}
Parameters are not currently supported in regular Cypher statements in the Neo4j 2.0 browser. However, you can use the :POST syntax to achieve this.
Refer to the documentation for more information on Cypher queries via REST API.
http://docs.neo4j.org/chunked/milestone/rest-api-cypher.html
Update:
The following query allows you to accomplish this in the browser, although it is not an ideal experience:
:POST /db/data/transaction/commit {
"statements": [
{
"statement": "MATCH (u:User {name:{username}}) RETURN u.name as username",
"parameters": {
"username": "my name"
}
}
]
}

The syntax to define params in the browser's command line is :params followed by the variable you would like to define, just type in :params and you will get a sense of how this command works from the resulting prompts.
For the case of HTTP API, in the latest version (v3.5 as of this writing), use the following syntax, copied from https://neo4j.com/docs/http-api/current/http-api-actions/execute-multiple-statements/:
{
"statements" : [ {
"statement" : "CREATE (n) RETURN id(n)"
}, {
"statement" : "CREATE (n {props}) RETURN n",
"parameters" : {
"props" : {
"name" : "My Node"
}
}
} ]
}

Related

Nested query GraphQL : Syntax error - iOS

I am working with Apollo GraphQL and have to call nested query .But while call the Query in .graphql file it showing
Syntax error : Expected Name, found {
Let me know how to call Nested query of GraphQL.
I have to call getAllproduct{....} query with the specified parameters.Here the FilterInput having the parameter as location with another pattern of query , so I don't know how to call this nested query.Anyone please help me to find out the solution.Thanks...
If an argument is an Input Object Type (as opposed to a Scalar), you can include the fields of the Input Object Type by using curly brackets.
query MyProductsQuery {
allProducts(
pageNumber: "someString"
filter: {
title: "someOtherString"
yearFrom: 1900
location: {
city: "yetAnotherString"
state: "FL"
}
}
) {
id
# other product fields
}
}
Of course, hardcoding those values in a .graphql file is not very helpful. You probably want to be able to swap those values out programatically. So here's what that same query looks like with variables:
query MyProductsQuery($pageNumber: String, $filter: FilterInput) {
allProducts(pageNumber: $pageNumber, filter: $filter) {
id
# other product fields
}
}
Your variables are passed in separately from your query and unlike your query, are not a GraphQL document. They are just JSON:
{
"pageNumber": "someString",
"filter": {
"title": "someOtherString",
"yearFrom": 1900,
"location": {
"city": "yetAnotherString",
"state": "FL"
}
}
}

watson discovery query -- result set not as expected

I would like to query the discovery service 'news collection' and I am using this query command.
discovery.query({ environment_id: ‘my env id’,
collection_id: ‘my coll id’,
“count”: 10,
“return”: “title,enrichedTitle.text”,
“query”: “dieter zetsche”,
“aggregations”: [ “term(docSentiment.type:2)“]
}, function(err, response) { …
I am expecting the following response structure
{
“matching_results”: 7607,
“aggregations”: [
{...}
],
“passages”: [],
“results”: [
{...}
]
}
but I get only the response without the ‘aggregation’ -- any recommendation???
like this
{"matching_results":7603,
"results":[
{"id":"....
Please note that the JSON object name for Sentiment Analysis has been changed from docSentiment to sentiment
More details here: https://www.ibm.com/watson/developercloud/doc/discovery/migrate-nlu.html#overview-of-major-changes

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.

ElasticSearch writing query for priority search

I am new to elastisearch and I just set it up and tried default search. I am using elasticsearch rails gem. I need to write custom query with priority search (some fields in table are more important then others, etc. title, updated_at in last 6 months...). I tried to find explanation or tutorial for how to do this but nothing seems understandable. Can anyone help me with this, soon better.
Never having used the ruby/elasticsearch integration, it doesn't seem too hard... The docs here show that you'd want to do something like this:
client.search index: 'my-index', body: { query: { match: { title: 'test' } } }
To do a basic search.
The ES documentation here shows how to do a field boosted query:
{
"multi_match" : {
"query" : "this is a test",
"fields" : [ "subject^3", "message" ]
}
}
Putting it all together, you'd do something like this:
client.search index: 'my-index', body: { query: { multi_match : {
query : "this is a test",
fields : [ "subject^3", "message" ]
} } }
That will allow you to search/boost on fields -- in the above case, the subject field is given 3 times the score of the message field.
There is a very good blog post about how to do advanced scoring. Part of it shows an example of adjusting the score based on a date:
...
"filter": {
"exists": {
"field": "date"
}
},
"script": "(0.08 / ((3.16*pow(10,-11)) * abs(now - doc['date'].date.getMillis()) + 0.05)) + 1.0"
...
I have done in php, Never used the gem from Ruby on rails. Here you can give the priority for the fields using the caret (^) notation.
Example:- Suppose if we have fields namely name, email, message and address in table and the priority should be given for the name and message then you can write as below
> { "multi_match" : {
> "query" : "this is a test",
> "fields" : [ "name^3", "message^2".... ] } }
Here name has 3 times higher priority than other fields and message has got 2 times higher priority than other fields.

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

Resources