How can I perfom an update with jena fuseki? - jena

I've wrote this query that normally works
String query2 = "PREFIX publ: <http://www.ps7-wia2.com/publications/>\n" +
"PREFIX pub: <http://www.ps7-wia2.com/publications#>" +
"DELETE { publ: " + id + " pub:like ?o }\n" +
"INSERT { publ: " + id + " pub:like " + nbLikes + " }\n" +
"WHERE {publ:" + id + " pub:like ?o .}\n";
RDFConnection conn2 = RDFConnectionFactory.connect(DATABASE);
QueryExecution qExec2 = conn2.query(query2) ;
conn2.close();
qExec2.close();
And when I execute I encounter this error
org.apache.jena.query.QueryParseException: Encountered " "delete" "DELETE "" at line 2, column 52.
Was expecting one of:
"base" ...
"prefix" ...
"select" ...
"json" ...
"describe" ...
"construct" ...
"ask" ...
```

In SPARQL, query and update are parsed separately; they are separate languages which use many of the same elements but have different syntax for their functionality ("SELECT" vs "INSERT" etc).
Use update(...).

Related

Construct queries with a condition

I am using Spring Data Neo4j and I have a repository like this:
public interface MyNeo4jRepository extends Neo4jRepository<Object, Long> {
#Query("with ['X', 'Y','Z'] as list_labels, "
+ "$appsFilter as appsList\n "
+ "MATCH (apps:) where apps.n IN appsList "
+ "MATCH (a)<-[:event]-(nodes) "
+ "WHERE any(x IN labels(nodes) WHERE x IN list_labels) "
+ "CALL apoc.path.expandConfig(nodes, { "
+ "relationshipFilter: 'R1|R2>',"
+ "labelFilter: '-l1|>l2',"
+ "maxLevel: 6,"
+ "endNodes: [apps],"
+ "uniqueness: 'NODE_PATH'}) YIELD path "
+ "unwind nodes(path) as n "
...
}
I want to create this query using conditions like this:
#Query("with ['X', 'Y','Z'] as list_labels, "
+ "$appsFilter as appsList\n "
+ "MATCH (apps:) where apps.n IN appsList "
+ "MATCH (a)<-[:event]-(nodes) "
+ "WHERE any(x IN labels(nodes) WHERE x IN list_labels) "
if (condition) + "WHERE ...." else + ""
+ "CALL apoc.path.expandConfig(nodes, { "
...
Is there a way to do it in the Neo4j query or do I have to do it with Spring composable repositories?
I think what you are looking for is the CASE construct
'WHERE ....'
+
CASE
WHEN condition1 THEN 'cypherFragement1'
WHEN condition2 THEN 'cypherFragement2'
ELSE 'cypherFragementElse'
END
+
.....
Maybe you can rewrite your entire cypher via apoc.do.when or apoc.do.case functions, which provide conditional judgment.

Google Ads Scripts AWQL "CONTAINS_ANY" operator doesn't work

I'm trying to extract Search queries by certain rules and I need to get Queries that contain one of the given strings:
" WHERE " +
" Impressions > " + IMPRESSIONS_THRESHOLD +
" AND AverageCpc > " + AVERAGE_CPC_THRESHOLD +
" AND Query CONTAINS_ANY ['for sale in', 'buy'] " +
" DURING YESTERDAY ");
But I'm getting error message (tryed different variations):
One of the conditions in the query is invalid. (file Code.gs, line 19)
Although it seems like I do everything according to Formal Grammar:
String -> StringSingleQ | StringDoubleQ
StringSingleQ -> '(char)'
StringDoubleQ -> "(char)"
StringList -> [ String (, String)* ]
If I do just 1 string it works fine:
" WHERE " +
" Impressions > " + IMPRESSIONS_THRESHOLD +
" AND AverageCpc > " + AVERAGE_CPC_THRESHOLD +
" AND Query CONTAINS 'for sale in' " +
" DURING YESTERDAY ");
IIRC, the CONTAINS_ANY operator only works when you are filtering on labels. I'm not sure if this constraint is actually documented, but this article seems to at least imply it.

How to pass multiple OR and AND condition in Activate Record in Rails as a string

I'm new in Ruby on rails and I would like to fetch records based on a condition, and I'm passing the condition in a string format. Moreover, I will pass the query in multiple OR and AND conditions. However, right now, I'm stuck that how to pass the query in string format in rails
I have attached the screenshot
#data= CustomAttribute.includes(:custom_attribute_values).where(id: 18, company_id: current_user.company_id).first
The above line executed successfully and gave the output
<CustomAttribute id: 18, data_type: "string", label: "Marital status", code: "marital_status", entity_type: "member", company_id: 1, created_at: "2021-03-10 10:16:15", updated_at: "2021-03-10 10:16:27", is_active: true, is_default: false, rank: nil, is_identifier: false>
but when I executed the below line it gave me the error that
#data.custom_attribute_values.where("\""+"value_string"+"\""+"="+"\""+'Single'+"\"").size
ERROR: column "Single" does not exist
the Single is the value which I would like to count
Here is my code for the dynamic query creation
logical_operator = 'OR'
#custom_attribute = CustomAttribute.includes(:custom_attribute_values).where(id: custom_attribute_ids, company_id: current_user.company_id)
query=""
#custom_attribute.each_with_index do |attribute_object, index|
filter_object= filter_params[:filters].find {|x| x['custom_attribute_id']==attribute_object['id']}
if filter_object.present?
query += "("+ '"' +'value_'+attribute_object.data_type + '"' + ' ' + filter_object['operator'] + ' ' + "'" + filter_object['value'].to_s + "'"+ ")"
end
if index != #custom_attribute.length-1
query+=' '+logical_operator+' '
end
if index == #custom_attribute.length-1
query="'" + " ( " + query + " ) " + "'"
end
end
byebug
puts(#custom_attribute.first.custom_attribute_values.where(query).size)
Any time you're doing a lot of escaping and string addition in Ruby you're doing it wrong. If we clean up how you build your SQL:
"\""+"value_string"+"\""+"="+"\""+'Single'+"\""
things will be clearer. First, put space around your operators for readability:
"\"" + "value_string" + "\"" + "=" + "\"" + 'Single' + "\""
Next, don't use double quotes unless you need them for escape codes (such as \n) or interpolation:
'"' + 'value_string' + '"' + '=' + '"' + 'Single' + '"'
Now we see that we're adding several constant strings so there's no need to add them at all, a single string literal will do:
'"value_string" = "Single"'
Standard SQL uses double quotes for identifiers (such as table and column names) and single quotes for strings. So your query is asking for all rows where the value_string column equals the Single column and there's your error.
You want to use single quotes for the string (and %q(...) to quote the whole thing to avoid adding escapes back in):
#data.custom_attribute_values.where(
%q("value_string" = 'Single')
)
Or better, let ActiveRecord build the query:
# With a positional placeholder:
#data.custom_attribute_values.where('value_string = ?', 'Single')
# Or a named placeholder:
#data.custom_attribute_values.where('value_string = :s', s: 'Single')
# Or most idiomatic:
#data.custom_attribute_values.where(value_string: 'Single')

Creating custom rails route: undefined method `+#' for "10":String

I am making a custom rails route as:
match '/setFavoriteRestaurant/:user_id/:restaurant_id/:campaignSetFav_id/:metro_id/:time_period', to: 'requests#setFavoriteRestaurant', via: 'get'
with controller action:
def setFavoriteRestaurant
setFavorite = "INSERT INTO androidchatterdatabase.users_favorite_restaurants(usersId,restaurantId,campaignIdSetFav,metroId,timePeriod,favoritedDt)
VALUES(" + params[:user_id].to_s + ","
+ params[:restaurant_id].to_s + ","
+ params[:campaignSetFav_id].to_s + ","
+ params[:metro_id].to_s + ","
+ params[:time_period].to_s + ",
NOW());"
ActiveRecord::Base.connection.execute(setFavorite)
end
Yet when testing in the browser with: http://localhost:3000/setFavoriteRestaurant/1/2/3/5/4
it returns an odd error as: undefined method +#' for "2":String
Why is this the case when other methods, setup exactly the same are fine to run?
This has to do with how you broke up the lines. Ruby doesn't know that the VALUES(" + line and the + params[:restaurant_id] are part of the same thing. This is because the VALUES( + line is complete. Move the + to the end of the line so that Ruby will know to expect the next line to be a continuation.
setFavorite = "INSERT INTO androidchatterdatabase.users_favorite_restaurants(usersId,restaurantId,campaignIdSetFav,metroId,timePeriod,favoritedDt)" +
"VALUES(" + params[:user_id].to_s + "," +
params[:restaurant_id].to_s + "," +
params[:campaignSetFav_id].to_s + "," +
params[:metro_id].to_s + "," +
params[:time_period].to_s + ",NOW());"
Also, note that I moved some other things around to avoid new lines and extra spaces.
I'm not sure why you prefer raw SQL here, but you should consider going through Rails. Seems like you're opening yourself up to SQL injection. At the very least, you could have some constraints in the route to match only integers.
Ruby has a couple of ways to quote multi line strings:
1) Here it is with ruby's heredoc syntax:
def some_action
setFavorite = <<-"END_OF_INSERT"
INSERT INTO androidchatterdatabase.users_favorite_restaurants(
usersId,
restaurantId,
campaignIdSetFav,
metroId,
timePeriod,
favoritedDt
)
VALUES(
"#{params[:user_id]}",
"#{params[:restaurant_id]}",
"#{params[:campaignSetFav_id]}",
"#{params[:metro_id]}",
"#{params[:time_period]}",
NOW()
);
END_OF_INSERT
end
Explanation:
setFavorite = <<-"END_OF_INSERT"
- => Terminator does not have to be at the start of the line.
"" => This is a double quoted string--do interpolation.
2) Here it is with %Q{}:
setFavorite = %Q{
INSERT INTO androidchatterdatabase.users_favorite_restaurants(
usersId,
restaurantId,
campaignIdSetFav,
metroId,
timePeriod,
favoritedDt
)
VALUES(
"#{params[:user_id]}",
"#{params[:restaurant_id]}",
"#{params[:campaignSetFav_id]}",
"#{params[:metro_id]}",
"#{params[:time_period]}",
NOW()
);
}
However, your SQL statement is still vulnerable to sql injection attacks. Check your db adapter for how to do parameter substitutions.

Pellet doesn't include my SWRL rules

I build an ontology which uses SWRL rules to inference. When I do a SQWRL querying in Protege it works fine. The problem is, when i want to use Pellet with Jena, it seems like Pellet doesn't include the SWRL rules in the querying. I include Pellet like this:
InputStream in = new FileInputStream(new File("D:\\Fakultet\\WeatherHealthcast1.owl"));
Model model = ModelFactory.createDefaultModel();
model.read(in, null);
OntModel ontology = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, model);
// Create a new query
String queryString =
"PREFIX WeatherHealthcast: <http://www.semanticweb.org/ontologies/2011/2/WeatherHealthcast.owl#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"SELECT ?disease " +
"WHERE { " +
" ?person rdf:type WeatherHealthcast:Person." +
" ?person foaf:firstName ?fn." +
" ?person foaf:lastName ?ln." +
" FILTER regex(str(?fn), \"Viktor\")." +
" FILTER regex(str(?ln), \"Taneski\")." +
" ?disease rdf:type WeatherHealthcast:Disease. " +
" ?person WeatherHealthcast:suffersFrom ?disease." +
"}";
Query query = QueryFactory.create(queryString);
// Execute the query and obtain results
QueryExecution qe = QueryExecutionFactory.create(query, ontology);
ResultSet resultSet = qe.execSelect();
System.out.println("TEST");
while (resultSet.hasNext())
{
QuerySolution result = resultSet.next();
RDFNode disease = result.get("disease");
Resource resource = disease.asResource();
System.out.println(" { Suffers from: " + resource.getLocalName() + " . }");
}
I also tried this:
Reasoner r = PelletReasonerFactory.theInstance().create();
InfModel inferenceModel = ModelFactory.createInfModel(r, model);
but no progress. Any ideas? I need this for my diploma thesis. Thanks
As far as I know, pellet cannot support SQWRL. On the other hand, it supports SWRL but with some restrictions (see http://clarkparsia.com/pellet/faq/rules).
I might be late but I think you should switch to owl full in order to get all your rules included in the reasoning.

Resources