Spring Data MongoDB $where is not allowed in this context - java

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 ...

Related

Spring Neo4j Pass Node Property as Parameter

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})"

Java MyBatis How to find SUM of the Cases WHEN value is IN the list passing the list as a parameter to the mapper's method

In my Mapper Class I have a method with the example query:
"<script>......"
“GROUP BY acct, call, score HAVING sum(case when code in(\n" +
"'PTP' \n" +
"'RPCNPTP', \n" +
"'LM3P', \n" +
"'OM_SF',\n" +
"'OM_SS',\n" +
"'OM_UNV',\n" +
"'OM_WR') then 1 else 0 end) <= intnsy ")
"</script> "
List<Object> getData();
This query works just fine. But the actual list of Strings contains about 70 different strings and it's not a good idea to keep them in the query.
I need to pass that list as a parameter to the method and create a loop. Like this:
"<script>......"
“GROUP BY acct, call, score HAVING sum(case when code in(\n" +
"<foreach item='code' collection='myCodes' separator=',' open='(' close=')'>" +
" (" +
" #{code} " +
" )" +
" </foreach> " +
") then 1 else 0 end) <= intnsy " +
"</script> ")
List<Object> getData(#Param("myCodes") List<String> myCodes);
But i'm not able to make it work. The error is:
org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 933; The content of elements must consist of well-formed character data or markup.
Obviously I'm missing something simple here, but unfortunately have nobody else in my team to ask Please point me to the right direction.
Thank you.
It seems like there is special characters you have to treat in the list of strings.
For example, You have to escape the character < , because mybatis takes it as an unopened tag, &lt will work.
this line:
") then 1 else 0 end) <= intnsy "
changed '<' to '<'
") then 1 else 0 end) <= intnsy "
now the query works as intended

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.

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);

Adding a " to a string in code

I'm writing some code for web services for my Android app which uses JSON. The url should look like this
url = url + "?maddr=" + mailAddr + "&pwd=FB&lect=" + """ + lectName + """ + "&fb=Test";
This is because the Lectname may be two or more words. However the compiler wont accept """, is there a character I can precede the " with to get the compiler to accept it into my string?
Try " \" ". You have to escape the "
http://en.wikipedia.org/wiki/Escape_character
You need this in (nearly) every programming language.

Categories

Resources