In spring-date-jpa, when my specification contains query.distinct(true) i see that the count(Specification) method, the count query is incorrect.
The generated SQL looks like this :
select distinctcount(*) ...
Instead of
select count(distinct(*)) ...
In that post:spring-source-forum
The workaround was to mofify the source code of spring-data-jpa.
Is there any other solution?
I have found another workaround:
Subquery<Class1> sq = query.subquery(Class1.class);
Root<Class1> spouseEmp = sq.from(Class1.class);
sq.select(spouseEmp);
sq.where(builder.equal(spouseEmp.get("class2"),class2.get("class2")));
predicate.getExpressions().add(builder.exists(sq));
CriteriaBuilder has a countDistinct that should get you want you want. I know this question is years old but I've been hunting for this answer for sometime. I was running into a similar issue where query.distinct(true) was not working as expected when used with count. In my example I was using a Specification. Posting this answer to raise awareness for countDistinct
public TypedQuery<Long> getCountQuery(Specification<T> spec) {
CriteriaBuilder builder = this.em.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<?> root = applySpecificationToCriteria(spec, query);
query.select(builder.countDistinct(root));
return this.em.createQuery(query);
}
Related
I need to create LeaderboardEntry if it is not exists. It should be updated with the new value (current + new) if exists. I want to achieve this with a single query. How can I do that?
Current code looking like this: (2 queries)
reward_amount = 50
LeaderboardEntry.objects.get_or_create(player=player)
LeaderboardEntry.objects.filter(player=player).update(golds=F('golds') + reward_amount)
PS: Default value of "golds" is 0.
you can have one query hit less with the defaults :
reward_amount = 50
leader_board, created = LeaderboardEntry.objects.get_or_create(
player=player,
defaults={
"golds": reward_amount,
}
)
if not created:
leader_board.golds += reward_amount
leader_board.save(update_fields=["golds"])
I think your problem is the get_or_create() method so it return back a tuple with two values, (object, created) so you have to recieve them in your code as following:
reward_amount = 50
entry, __ = LeaderboardEntry.objects.get_or_create(player=player)
entry.golds += reward_amount
entry.save()
It will work better than your actual code, just will avoid make two queries.
Of course the save() method will hit again your database.
You can solve this with update_or_create:
LeaderboardEntry.objects.update_or_create(
player=player,
defaults={
'golds': F('golds') + reward_amount
}
)
EDIT:
Sorry, F expressions in update_or_create are not yet supported.
Using Binance Futures API I am trying to get a proper form of my position regarding cryptocurrencies.
Using the code
from binance_f import RequestClient
request_client = RequestClient(api_key= my_key, secret_key=my_secet_key)
result = request_client.get_position()
I get the following result
[{"symbol":"BTCUSDT","positionAmt":"0.000","entryPrice":"0.00000","markPrice":"5455.13008723","unRealizedProfit":"0.00000000","liquidationPrice":"0","leverage":"20","maxNotionalValue":"5000000","marginType":"cross","isolatedMargin":"0.00000000","isAutoAddMargin":"false"}]
The type command indicates it is a list, however adding at the end of the code print(result) yields:
[<binance_f.model.position.Position object at 0x1135cb670>]
Which is baffling because it seems not to be the list (in fact, debugging it indicates object of type Position). Using PrintMix.print_data(result) yields:
data number 0 :
entryPrice:0.0
isAutoAddMargin:True
isolatedMargin:0.0
json_parse:<function Position.json_parse at 0x1165af820>
leverage:20.0
liquidationPrice:0.0
marginType:cross
markPrice:5442.28502271
maxNotionalValue:5000000.0
positionAmt:0.0
symbol:BTCUSDT
unrealizedProfit:0.0
Now it seems like a JSON format... But it is a list. I am confused - any ideas how I can convert result to a proper DataFrame? So that columns are Symbol, PositionAmt, entryPrice, etc.
Thanks!
Your main question remains as you wrote on the header you should not be confused. In your case you have a list of Position object, you can see the structure of Position in the GitHub of this library
Anyway to answer the question please use the following:
df = pd.DataFrame([t.__dict__ for t in result])
For more options and information please read the great answers on this question
Good Luck!
you can use that
df = pd.DataFrame([t.__dict__ for t in result])
klines=df.values.tolist()
open = [float(entry[1]) for entry in klines]
high = [float(entry[2]) for entry in klines]
low = [float(entry[3]) for entry in klines]
close = [float(entry[4]) for entry in klines]
I'm trying to get Taxonomy data by particular node.
How can I get Taxonomy Term Id by using Node object ?
Drupal ver. 8.3.6
You could do something like that:
$termId = $node->get('field_yourfield')->target_id;
Then you can load the term with
Term::load($termId);
Hope this helps.
If you want to get Taxonomy Term data you can use this code:
$node->get('field_yourfield')->referencedEntities();
Hope it will be useful for you.
PS: If you need just Term's id you can use this:
$node->get('field_yourfield')->getValue();
You will get something like this:
[0 => ['target_id' => 23], 1 => ['target_id'] => 25]
In example my field has 2 referenced taxonomy terms.
Thanks!
#Kevin Wenger's comment helped me. I'm totally basing this answer on his comment.
In your code, when you have access to a fully loaded \Drupal\node\Entity\Node you can access all the (deeply) nested properties.
In this example, I've got a node which has a taxonomy term field "field_site". The "field_site" term itself has a plain text field "field_site_url_base". In order to get the value of the "field_site_url_base", I can use the following:
$site_base_url = $node->get('field_site')->entity->field_site_url_base->value;
How to extract multiple term IDs easily if you know a little Laravel (specifically Collections):
Setup: composer require tightenco/collect to make Collections available in Drupal.
// see #Wau's answer for this first bit...
// remember: if you want the whole Term object, use ->referencedEntities()
$field_value = $node->get('field_yourfield')->getValue();
// then use collections to avoid loops etc.
$targets = collect($field_value)->pluck('target_id')->toArray();
// $targets = [1,2,3...]
or maybe you'd like the term IDs comma-separated? (I used this for programmatically passing contextual filter arguments to a view, which requires , (OR) or + (AND) to specify multiple values.)
$targets = collect($field_value)->implode('target_id', ',');
// $targets = "1,2,3"
I have the following regular expression pattern that matches fully qualified Microsoft SQL Server table names ([dbName].[schemaName].[tableName]), where the schema name is optional:
val tableNamePattern = """\[(\w+)\](?:\.\[(\w+)\])?\.\[(\w+)\]""".r
I am using it like this:
val tableNamePattern(database, schema, tableName) = fullyQualifiedTableName
When the schema name is missing (e.g.: [dbName].[tableName]), the schema value gets set to null.
Is there a Scala idiomatic way to set it to None instead, and to Some(schema) when the schemaName is provided?
Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems.
-- Jamie Zawinski
I'm going to copy the code from the accepted answer on the linked question, and without giving credit too. Here it is:
object Optional {
def unapply[T](a: T) = if (null == a) Some(None) else Some(Some(a))
}
val tableNamePattern(database, Optional(schema), tablename) = fullyQualifiedTableName
PS: I just today wondered on twitter whether creating special-case extractors was as common as they were suggested. :)
I want to create a Doctrine Query: (Doctrine 2.3)
SELECT * FROM `car` WHERE `plate` like '%' AND (`datetime` BETWEEN '2013-03-13 22:20:18' AND '2013-03-13 22:20:20') OR (`datetime` BETWEEN '2013-03-13 15:10:18' AND '2013-03-13 15:10:16')
I tried the following but its not working:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->andWhere(
qry->expr()->between(
'e.datetime',
':dateFrom',
':dateTo'
)
)
->setParameter('dateFrom', $fromdate)
->setParameter('dateTo', $todate);
$qry->orWhere(
$qry->expr()->between(
'e.datetime',
':dateFrom',
':dateTo'
)
)
->setParameter('dateFrom1', $fromdate1)
->setParameter('dateTo1', $todate1);
OutPut of above query:
SELECT e FROM user e WHERE (e.plate like :plate AND (e.datetime BETWEEN :dateFrom AND :dateTo)) OR (e.datetime BETWEEN :dateFrom AND :dateTo)
I want to check two dates in same column how can I check? Is the syntax correct?
Currently It is like this:
(Plate AND (Date)) OR Date)
Case 1
But it should come like the following for good output.
(Plate) AND ((Date) OR (Date))
Case 2
In other case it should come like this:
((Plate) or (Plate)) AND ((Date) OR (Date))
Can some one help me I am not an expert in Doctrine I am a learner!
After some search and advice from many individual I finally found some logic and understood the expression in Doctrine. Below I have given all the expression with an example. Code to be tested.
$ex1 = $qry->expr()->like('e.user', "'".$user."'");
$ex2 = $qry->expr()->orX(
$qry->expr()->between('e.datetime', "'".$datetimefrom."'", "'".$datetimeto."'")
);
$ex3 = $qry->expr()->in('e.country', $country);
$final_expression = $qry->expr()->andX($ex1,$ex2,$ex3);
You can also refer the below issue and solution which helped me to solve the above Question by me.
REF Multiple Query in Doctrine with NAND,NOR,NOT,AND Operators