Spring Neo4j Pass Node Property as Parameter - java

I am trying to pass a property as a parameter.
I have tried this:
String get_interest="MATCH(user:User{id:{id}})-[watched:WATCHED]->(movie:Movie{title:{title}}) " +
"MATCH(movie)-[:BELONGS_TO]->(category:Category) " +
"MATCH(category)<-[:BELONGS_TO]-(similarMovie:Movie) " +
"WHERE NOT EXISTS((user) -[:WATCHED]->(similarMovie))" +
"RETURN similarMovie Limit 20";
But it fails with this error:
"error": "Internal Server Error",
"message": "Cypher execution failed with code 'Neo.ClientError.Statement.SyntaxError': Invalid input '{': expected \"+\" or \"-\" (line 1, column 24 (offset: 23))
I have tried this and it worked:
String get_interest="MATCH(user:User{id:\"02331\"})-[watched:WATCHED]->(movie:Movie{title:\"The Mask\"}) " +
"MATCH(movie)-[:BELONGS_TO]->(category:Category) " +
"MATCH(category)<-[:BELONGS_TO]-(similarMovie:Movie) " +
"WHERE NOT EXISTS((user) -[:WATCHED]->(similarMovie))" +
"RETURN similarMovie Limit 20";
But I want to pass other User ids and titles.
This is my Repository
#Query(get_interest)
Collection<Movie> getMovieByInterest(#Param("id") String id,
#Param("title") String title);

Params are bound as variables. Variables are interpolated with dollar:
"MATCH(user:User{id:$id})-[watched:WATCHED]->(movie:Movie{title:$title})"

Related

Spring Data MongoDB $where is not allowed in this context

I'm trying to make a Mongo criteria where the search value must be equal to FIELD1 + "-" + FIELD2:
What I've tried:
Criteria.where("$where").is("this." + SOFTWARE_NAME + " + '-' + this." + SOFTWARE_VERSION " == '" + value + "'");
But when I run a query with that criteria then I'm getting this exception:
org.springframework.data.mongodb.UncategorizedMongoDbException:
Command failed with error 2 (BadValue): '$where is not allowed in this
context' on server hostname:17091. The full
response is {"operationTime": {"$timestamp": {"t": 1614185267, "i":
1}}, "ok": 0.0, "errmsg": "$where is not allowed in this context",
"code": 2, "codeName": "BadValue"
Even if I change the criteria to "this." + SOFTWARE_NAME + " == this." + SOFTWARE_NAME still the same exception is returned. I've seen many answers with a criteria that uses where("$where") so why it doesn't work for me?
When I run that query in Mongo directly:
{"$where" : "this.softwareName + '-' + this.softwareVersion == 'software-1.0.2'"}
then everything works perfectly fine.
EDIT
The query in the logs looks like this:
"loggerName":"org.springframework.data.mongodb.core.MongoTemplate","message":"Executing
count: { "$where" : "this.softwareName + '-' + this.softwareVersion
== 'software-1.0.2'"} in collection ...

Error converting Flink CEP table in Dataset<Row> object

I've created an BatchTableEnviroment in Apache Flink and created a Table object where I loaded data in. Now I want to search for some patterns. I'm doing this with the Detecting patterns in Tables CEP library. The task of the query below is to find the longest period of a mGroup for which the avgResult did not go below a certain threshold. Where a mGroup is a Integer value like 100, 200, 300 etc. Avgresult is double value. When I compile the query part I dont get any error. I get the error when I convert the Table to a DataSet<row>. Below the query u can see the error message.
ExecutionEnvironment fbEnv = ExecutionEnvironment.getExecutionEnvironment();
BatchTableEnvironment tableEnv = BatchTableEnvironment.create(fbEnv);
Table trendTable = tableEnv.sqlQuery(
" SELECT * " +
" FROM tableAvg " +
" MATCH_RECOGNIZE(" +
" PARTITION BY mType " +
" ORDER BY mGroup " +
" MEASURES " +
" FIRST(A.mGroup) as startGr, " +
" LAST(A.mGroup) as endGr, " +
" A.avgResult as avgRes" +
" ONE ROW PER MATCH " +
" AFTER MATCH SKIP PAST LAST ROW " +
" PATTERN (A+ B) " +
" DEFINE " +
" A AS A.avgResult < 50 " +
") "
);
tableEnv.registerTable("TrendTable", trendTable);
DataSet<Row> result = tableEnv.toDataSet(trendTable, Row.class);
/////////////////////ERROR MESSAGE BELOW
Exception in thread "main" org.apache.flink.table.api.TableException: Cannot generate a valid execution plan for the given query:
FlinkLogicalMatch(partition=[[$1]], order=[[2]], outputFields=[[mType, startGr, endGr, avgRes]], allRows=[false], after=[FLAG(SKIP PAST LAST ROW)], pattern=[(PATTERN_QUANTIFIER(_UTF-16LE'A', 1, -1, false), _UTF-16LE'B')], isStrictStarts=[false], isStrictEnds=[false], subsets=[[]], patternDefinitions=[[<(PREV(A.$0, 0), 50)]], inputFields=[[sumResult, mType, EXPR$2]])
FlinkLogicalSort(sort0=[$2], dir0=[ASC])
FlinkLogicalCalc(expr#0..5=[{inputs}], expr#6=[/($t2, $t3)], expr#7=[99], expr#8=[>($t5, $t7)], sumResult=[$t6], mType=[$t1], EXPR$2=[$t4], $condition=[$t8])
FlinkLogicalAggregate(group=[{0, 1}], agg#0=[SUM($2)], agg#1=[SUM($3)], agg#2=[MAX($4)], agg#3=[COUNT()])
FlinkLogicalCalc(expr#0..2=[{inputs}], expr#3=[1], expr#4=[-($t0, $t3)], expr#5=[100], expr#6=[/($t4, $t5)], expr#7=[1.0:DECIMAL(2, 1)], $f0=[$t6], mType=[$t1], mValue=[$t2], $f3=[$t7], mID=[$t0])
FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, H]], fields=[mID, dateTime, mValue, unixDateTime, mType], source=[CsvTableSource(read fields: mID, mType, mValue)])
This exception indicates that the query uses an unsupported SQL feature.
Please check the documentation for the set of currently supported SQL features.
at org.apache.flink.table.plan.Optimizer.runVolcanoPlanner(Optimizer.scala:245)
at org.apache.flink.table.plan.Optimizer.optimizePhysicalPlan(Optimizer.scala:170)
at org.apache.flink.table.plan.BatchOptimizer.optimize(BatchOptimizer.scala:57)
at org.apache.flink.table.api.internal.BatchTableEnvImpl.translate(BatchTableEnvImpl.scala:280)
at org.apache.flink.table.api.java.internal.BatchTableEnvironmentImpl.toDataSet(BatchTableEnvironmentImpl.scala:71)
at StreamTableEnv.main(StreamTableEnv.java:169)
The CEP library and MATCH_RECOGNIZE only work on top of the streaming API (and not batch), meaning that you need to use a StreamTableEnvironment rather than a BatchTableEnviroment.

How to set the multiple attributes of objectClass for UnboundID & OpenLDAP via Java 7

I'm not sure how to properly pass the multiple attributes needed for an OpenLDAP insert via UnboundID. I have omitted the objectClass attributes & received a "no objectClass" error. I have also tried comma-separated & the bracket/array route like below & received the "value #0 invalid per syntax" error.
String[] ldifLines = {"dn: ou=users,dc=sub,dc=domain,dc=com", "cn: " + uid, "userPassword: " + pw, "description: user", "uidNumber: " + lclDT, "gidNumber: 504", "uid: " + uid, "homeDirectory: " + File.separator + "home" + File.separator + this.getStrippedUser(), "objectClass: {posixAccount, top}"};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
So, the question is, how do I successfully pass these objectClass attributes in the string array included above? Again, I have tried: "objectClass: top, posixAccount" as well. Thanks in advance!
It uses an LDIF representation, so if an attribute has multiple values, then the attribute appears multiple times. Like:
String[] ldifLines =
{
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser(),
};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
Also, the LDAP SDK allows you to use a shortcut and just do it in a single call without the need to create the array or the AddRequest object, like:
LDAPResult ldapResult = lclLC.add(
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser());

`rtserver-id` turns to `rtserver - id` in java string

I have this code:
public void foo (){
String script =
"var aLocation = {};" +
"var aOffer = {};" +
"var aAdData = " +
"{ " +
"location: aLocation, " +
"offer: aOffer " +
" };" +
"var aClientEnv = " +
" { " +
" sessionid: \"\", " +
" cookie: \"\", " +
" rtserver-id: 1, " +
" lon: 34.847, " +
" lat: 32.123, " +
" venue: \"\", " +
" venue_context: \"\", " +
" source: \"\"," + // One of the following (string) values: ADS_PIN_INFO,
// ADS_0SPEED_INFO, ADS_LINE_SEARCH_INFO,
// ADS_ARROW_NEARBY_INFO, ADS_CATEGORY_AUTOCOMPLETE_INFO,
// ADS_HISTORY_LIST_INFO
// (this field is also called "channel")
" locale: \"\"" + // ISO639-1 language code (2-5 characters), supported formats:
" };" +
"W.setOffer(aAdData, aClientEnv);";
javascriptExecutor.executeScript(script);
}
I have two q:
when I debug and copy script value I see a member rtserver - id instead of rtserver-id
how can it be? the code throws an exception because of this.
Even if i remove this rtserver-id member (and there is not exception thrown)
I evaluate aLocation in this browser console and get "variable not defined". How can this be?
rtserver-id isn't a valid identifier - so if you want it as a field/property name, you need to quote it. You can see this in a Chrome Javascript console, with no need for any Java involved:
> var aClientEnv = { sessionId: "", rtserver-id: 1 };
Uncaught SyntaxError: Unexpected token -
> var aClientEnv = { sessionId: "", "rtserver-id": 1 };
undefined
> aClientEnv
Object {sessionId: "", rtserver-id: 1}
Basically I don't think anything's adding spaces - you've just got an invalid script. You can easily add the quotes in your Java code:
" \"rtserver-id\": 1, " +

parameters in lucene queries in neo4j repositories with SDN?

I need to be able to search for substrings in a text field, via a parameterised repository method, in neo4j 1.9.5
Ideally I want to be able to call
getInteractionsByTermAndDateRange(String term,
long startMillis, long endMillis
and get back every WRInteraction where the 'content' field contains 'term', with the pubMillis value within the specified range( 'content' is specified as a FULLTEXT index in the WRInteraction object declaration)
First attempt:
#Query("START n=node:WRInteraction('content:*{0}*') " + " WHERE "
+ " n.pubMillis >= {1} AND n.pubMillis <= {2}" + " RETURN "
+ " n")
Iterable<WRInteraction> getInteractionsByTermAndDateRange(String term,
long startMillis, long endMillis);
This throws
Caused by: org.apache.lucene.queryParser.ParseException: Cannot parse 'content:*{0}*':
Encountered " "}" "} "" at line 1, column 11.
Was expecting one of:
"TO" ...
<RANGEEX_QUOTED> ...
<RANGEEX_GOOP> ...
at org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:211) ~[lucene-core-3.6.2.jar:3.6.2 1423725 - rmuir - 2012-12-18 19:45:40]
at org.neo4j.index.impl.lucene.IndexType.query(IndexType.java:300) ~[neo4j-lucene-index-1.9.5.jar:1.9.5]
Second try -- pass the whole lucene query via the parameter:
#Query("START n=node:WRInteraction('content:{0}') " + " WHERE "
+ " n.pubMillis >= {1} AND n.pubMillis <= {2}" + " RETURN "
+ " n")
doesn't fare any better... what's the pattern I should be using here? The key requirement is to be able to pass a substring to a repository method as a parameter, and return any WRInteractions where that substring is present int he 'content' field. Should be easy, right?
Thanks
You need to specify the lucene query as a whole.
#Query("START n=node:WRInteraction({0}) WHERE n.pubMillis >= {1} AND n.pubMillis <= {2} RETURN n")
Iterable<WRInteraction> getInteractionsByTermAndDateRange(String query,
long startMillis, long endMillis);
Call this method like:
repository.getInteractionsByTermAndDateRange("content:*" + term + "*", 0, 0);

Categories

Resources