Neo4j Java OGM select with lock - java

I am trying to select a path with locking the last node in that path using Java OGM for Neo4j.
To do that in cypher I have written the following query:
String q = "Match path = (p:Root) - [*1..100]-(m:Leaf) WHERE m.State = 'Non-Processed' WITH m,p,path ORDER BY length(path) Limit 1 SET m.State = 'Processing' RETURN path"
It selects the necessary path with locking the last leaf(by changing its State property).
However, when I try to execute this query:
session.query(Path.class, q, propertyMap)
I get a java.lang.RuntimeException: query() only allows read only cypher. To make modifications use execute()
What is the proper way to do this?

You're probably using an older version of neo4j-ogm which had the restriction on session.query(). Please upgrade to neo4j-ogm 1.1.4

Found a (probably not the best) solution.
String uid = UUID.randomUUID().toString();
String lockQuery = "Match path = (p:Root) - [*1..100]-(m:Leaf)"
+ "WHERE m.State = 'Non-Processed' "
+ "WITH m,p,path ORDER BY length(path) Limit 1 SET m.lock = " + uid
session.execute(lockQuery);
String getQuery = "Match path = (p:Root) - [*1..100]-(m:Leaf)"
+ "WHERE m.lock = " + uid + "RETURN path";
Path path = session.query(Path.class, getQuery, new Hashmap<String, Object>());
Will this work?

Related

Group by inside otherwise clause, spark java

I have this process in SparkJava (IntelliJ app) where I have a problem that I don`t know how to resolve yet. First I declare the dataset:
private static final String CONTRA1 = "contra1";
query = "select contra1, ..., eadfinal, , ..., data_date" + FROM + dbSchema + TBLNAME " + WHERE fech = '" + fechjmCto2 + "' AND s1emp=49";
Dataset<Row> jmCto2 = sql.sql(query);
Then I have the calculations, I analyze some fields to assign some literal values. My problem is in the aggegate function:
Dataset<Row> contrCapOk1 = contrCapOk.join(jmCto2,
contrCapOk.col(CONTRA1).equalTo(jmCto2.col(CONTRA1)),LEFT)
.select(contrCapOk.col("*"),
jmCto2.col("ind"),
functions.when(jmCto2.col(CONTRA1).isNull(),functions.lit(NUEVES))
.when(jmCto2.col("ind").equalTo("N"),functions.lit(UNOS))
.otherwise(jmCto2.groupBy(CONTRA1).agg(functions.sum(jmCto2.col("eadfinal")))).as("EAD"),
What I want is to make the sum in the otherwise part. But when I execute the cluster give me this message in the log.
User class threw exception: java.lang.RuntimeException: Unsupported literal type class org.apache.spark.sql.Dataset [contra1: int, sum(eadfinal): decimal(33,6)]
in the line 211, the otherwise line.
Do you know what the problem could be?.
Thanks.
You cannot use groupBy and aggregation function in a column clause. To do what you want to do, you have to use a window.
For you case, you can define the following window:
import org.apache.spark.sql.expressions.Window;
import org.apache.spark.sql.expressions.WindowSpec;
...
WindowSpec window = Window
.partitionBy(CONTRA1)
.rangeBetween(Window.unboundedPreceding(), Window.unboundedFollowing());
Where
partitionBy is the equivalent of groupBy for aggregation
rangeBetween determine which rows of the partition will be used by aggregation function, here we take all rows
And then you use this window when calling your aggregation function, as follow:
import org.apache.spark.sql.functions;
...
Dataset<Row> contrCapOk1 = contrCapOk.join(
jmCto2,
contrCapOk.col(CONTRA1).equalTo(jmCto2.col(CONTRA1)),
LEFT
)
.select(
contrCapOk.col("*"),
jmCto2.col("ind"),
functions.when(jmCto2.col(CONTRA1).isNull(), functions.lit(NUEVES))
.when(jmCto2.col("ind").equalTo("N"), functions.lit(UNOS))
.otherwise(functions.sum(jmCto2.col("eadfinal")).over(window))
.as("EAD")
)

How can I find a ProductVariant by his variantKey?

In my project I am now needing to obtain the variant of the product from the variantKey, but I have not found any method in the JVM SDK to do it.
I tried to do it using the ProductByKeyGet method, but I only get the product if the value corresponds to the root key of the product, but if the value corresponds to the variantKey it does not return anything to me.
Does anyone know any way to get the variant from its VariantKey?
Thanks in advance.
Miguel de la Hoz
Today we released version 1.29.0 of our JVM SDK - where we added the missing support for querying product variants by key (see https://github.com/commercetools/commercetools-jvm-sdk/issues/1679).
With this version you can then write the query in a typesafe fashion:
String myKey = "foo";
ProductProjectionType projectionType = ProductProjectionType.CURRENT;
ProductProjectionQuery query =
ProductProjectionQuery.of(projectionType)
.withPredicates(product -> product.allVariants()
.where(variant -> variant.key().is(myKey)));
Hope this helps!
For that you will need to use the Product Projection endpoint, where you can query for products which have either a variant "OR" master variant with the key you desire. Through the JVM SDK, you can achieve that by doing the following:
Build a QueryPredicate<EmbeddedProductVariantQueryModel> for the key you desire :
final String myKey = "foo";
final QueryPredicate<EmbeddedProductVariantQueryModel> queryPredicate =
QueryPredicate.of("key=\"" + myKey + "\"");
Build a Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> to query for the master variant:
final Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> mvPredicateFunction = productQueryModel ->
productQueryModel.masterVariant().where(queryPredicate);
Build a Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> to query for the rest of the variants:
final Function<ProductProjectionQueryModel, QueryPredicate<ProductProjection>> variantsPredicateFunction = productQueryModel ->
productQueryModel.variants().where(queryPredicate);
Combine both predicates with a semantic OR operator to build the ProductProjectionQuery (in this case on the staged projection):
final ProductProjectionQuery query = ProductProjectionQuery.ofStaged()
.withPredicates(productQueryModel -> mvPredicateFunction
.apply(productQueryModel)
.or(variantsPredicateFunction.apply(productQueryModel)));
Execute the request:
final PagedQueryResult<ProductProjection> requestStage = sphereClient.executeBlocking(query);
Since variant keys are unique, you should be expecting to yield one resulting product projection, if any:
final Optional<ProductProjection> optionalProductProjection = requestStage.head();
Traverse all (including the master variant) variants of the resultant product projection to fetch the matching variant with such key:
final Optional<ProductVariant> optionalVariant = optionalProductProjection.flatMap(
productProjection -> productProjection.getAllVariants().stream()
.filter(productVariant -> myKey.equals(productVariant.getKey()))
.findFirst());
Update:
Steps 1-4 can also be simplified to:
final String myKey = "foo";
final QueryPredicate<ProductProjection> productProjectionQueryPredicate = QueryPredicate
.of("masterVariant(key = \"" + myKey + "\") OR variants(key = \"" + myKey + "\")");
final ProductProjectionQuery query = ProductProjectionQuery.ofStaged().withPredicates(
productProjectionQueryPredicate);

Restfb - Using the Batch Request API

This is my FQL. What it does is it receives the post based on post_id, and also returns if post was made by user or page. User or page is returned based on id of the one who posted the post, which is returned by first FQLQuery.
StringBuilder fqlQuery = new StringBuilder();
fqlQuery.append("SELECT "
+ FacebookGraphApi.FQL_STREAM_SELECT
+ " FROM stream WHERE post_id=\"");
fqlQuery.append(rmtId);
fqlQuery.append("\"");
HashMap<String, String> querys = new HashMap<String, String>();
querys.put("messages", fqlQuery.toString());
querys.put(
"users",
"SELECT "
+ FacebookGraphApi.FQL_USER_SELECT
+ " FROM user WHERE uid IN (SELECT actor_id FROM #messages)");
querys.put(
"pages",
"SELECT "
+ FacebookGraphApi.FQL_PAGE_SELECT
+ " FROM page WHERE page_id IN (SELECT actor_id FROM #messages)");
Now what i would like to do is the same using RESTFB Batch Request API
BatchRequest firstRequest = new BatchRequestBuilder(rmtId)).build();
BatchRequest secondRequest = new BatchRequestBuilder(poster_id).build();
List<BatchResponse> batchResponses =
facebookClient.executeBatch(firstRequest,secondRequest);
These are 2 batches that executes, first one returns the post, and it contains "from", that contains poster_id of the one who posted, but i dont know how to put that poster_id from first batch to second batch so it would return poster information.
Any help would be appreciated, thanks.
Just to post the answer,
first request should contain a name method on which u depend on the other request, and search on second request that depends on first ids like this.
?ids={result=name-of-method:$.data.id}

Hibernate error node to be traverse cannot be null

Hi guys i have a question regarding this annoying error. Below it's my code
String updateDefaultBU = "update ClientUserVO set defaultBUnit = :yes where id = (select max(cu1.id) from ClientUserVO cu1 where cu1.user.id = :userId and cu1.defaultBUnit = :no)";
updateDefaultBU = " and not exists (select cu2.id from ClientUserVO cu2 where cu2.user.id = :userId and cu2.defaultBUnit = :yes) ";
Query updateQuery = session.createQuery(updateDefaultBU);
updateQuery.setString("yes", "Y");
updateQuery.setString("no", "N");
updateQuery.setLong("userId", userID);
I don't seem to understand where does it find a not that could not be traversed, also this error is very general and it could happen for various reasons, could you tell me what i am doing wrong?
Thanks
In your second assignment of updateDefaultBU you are changing the content of the variable completely and not concatenating with the first assignment (as I assume you want to do).
It is possible that you get the error because you run updateQuery.setString("no", "N") but the second assignment has no :no value in it.
Try changing the second line to updateDefaultBU.concat(" <your string> ")
Also have you tried to debug to see exactly where the error is happening?

Passing parameters to YQL using Java

I am using the following code:
String zip = "75227";
String str = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
"food%20pantries%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
Document doc = Jsoup.connect(str).get();
and it is producing the results I want by replacing the zip code value. I would like to also change the location. I tried doing the same I did with the zip code by doing this:
String zip = "32207";
String service = "food pantry";
String testOne = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
service + "%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
When used this way the variable "service" gave me an error.
I initially tried to use the yql table like this:
String search = "http://query.yahooapis.com/v1/public/yql?q=";
String table = "select Title, Address, City, State, Phone, Distance from local.search where " +
"query=\"food pantries\" and zip=\"75227\" and (category=\"96927050\" or category=" +
"\"96934498\") | sort(field=\"Distance\")";
String searchText = search + table;
UPDATE:
Here is the error I am getting:
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=505, URL=http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22food pantry%22%20and%20zip%3D%2232207%22%20and%20(category%3D%2296927050%22%20or%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:418)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148)
at org.jsoup.examples.HtmlToPlainText.main(HtmlToPlainText.java:86)
However, this did not work either. Any ideas on how I can do this search and provide the service and zip code as variables?
Have you tried replacing String service = "food pantry"; with String service = "food%20pantry"; ?
EDIT:
and it is "food pantry" or "food pantries"... ?

Categories