Query DSL has castToNum() but is there anything to convert LocalDateTime(job_date_time) to Date ?
SELECT user_logon as logon, cast(job_date_time as date) as
dateTime,SUM(total_pages) as total
from job_history group by user_logon, cast(job_date_time as date) order by
dateTime desc
Java Approach
JPAQuery<JobHistory> queryBuilder = new JPAQuery<>(entityManager);
QJobHistory jobHistory = QJobHistory.jobHistory;
queryBuilder.select(jobHistory.userLogon.as("logon"),jobHistory.jobDateTime.as("dateTime"),jobHistory.totalPages.sum().as("total"))
.from(jobHistory)
.groupBy(jobHistory.userLogon)
.groupBy(jobHistory.jobDateTime)
.orderBy(Expressions.stringPath("totalPages").desc());
queryBuilder.fetchAll();
How can I cast this expression to date?
jobHistory.jobDateTime.as("dateTime")
And this expression to date?
.groupBy(jobHistory.jobDateTime)
What I tried
Expressions.asDate(jobHistory.jobDateTime).as("dateTime");
Worked for me .
Expressions
.dateTimeTemplate(java.sql.Date.class,"cast(job_date_time as date)")
.as("dateTime");
Related
I am a newbie to MongoDB and having a hard time querying documents with simple filtering. I would like to ask if what is the equivalent of CAST(datetime AS DATE) of mysql in MongoDB?
here's my code.
"inspection": {"hourbeg": "2020-11-23 10:12:20"}
Bson filters = Filters.and(new BasicDBObject("center.code", code),
new BasicDBObject("inspection.hourbeg", transactionDate));
Bson sorts = Sorts.descending("printedOn");
List<Document> vehicles = collection.find()
.sort(sorts)
.filter(filters)
.into(new ArrayList<Document>());
Im still trying to understand this Aggregate in MongoDB.
Never mind guys, I was able to solve my problem using this method. Might be useful for others as well.
String startDate = transactionDate.toString()+" 00:00:00";
String endDate = transactionDate.plusDays(1).toString()+" 00:00:00";
Bson gt = Filters.gt("inspection.hourbeg", startDate);
Bson lt = Filters.lt("inspection.hourbeg", endDate);
Bson andDate = Filters.and(gt, lt);
Bson filters = Filters.and(new BasicDBObject("center.code", code),
andDate);
Bson sorts = Sorts.descending("printedOn");
List<Document> vehicles = collection.find()
.sort(sorts)
.filter(filters)
.into(new ArrayList<Document>());
I want to send this request
http://localhost:8080/{url}?start=2020-04-20&end=2020-04-24&status=success&status=failed
In Transaction model
private java.sql.Timestamp addedOn;
I am trying to create a dynamic query for multiple filters following this blog:
https://attacomsian.com/blog/spring-data-jpa-specifications
Specs.java file toPredicate method
if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
predicates.add(builder.greaterThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
predicates.add(builder.lessThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
}
Here is my Controller code
Timestamp start = new Timestamp(dateFormat.parse(request.getParameter("start")).getTime());
Timestamp end = new Timestamp(dateFormat.parse(request.getParameter("end")).getTime());
Specs txnSpecs = new Specs();
txnSpecs.add(new SearchCriteria("addedon", start, SearchOperation.GREATER_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("addedon", end, SearchOperation.LESS_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("status", Arrays.asList(request_params.get("status")), SearchOperation.IN));
List<Transaction> txnList = transactionRepository.findAll(txnSpecs);
return txnList;
But when I make request I get:
nested exception is java.lang.IllegalArgumentException: Parameter value [2020-04-20] did not match expected type [java.util.Date (n/a)]]
Do I need to convert the Date value before I send it as param for the SQL query? Or I need to use other types of Date?
Do I need to convert the Date value before I send it as param for the SQL query?
No, the opposite is true, you must keep it a Date but you convert it to a String by calling criteria.getValue().toString().
Check if your dateFormat are correct to pattern of your value: yyyy-MM-dd :
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
How to Get the difference between the two date values in Mongo criteria and return value must be the difference of two date(i.e 10.01.2015 firs date and 20.01.2015 is second date) I need the value as 10 ? can any one help me how to get this in java using spring framework critieria?)
From this article What's new in Spring Data MongoDB 1.4 M1, you can use the andExpression to get the difference between the two date values:
.andExpression("endDateTime - startDateTime").as("duration")
As an example (untested):
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<Trip> agg = newAggregation(Trip.class,
match(Criteria.where("userId").is("54e5cead3ab5c1dd97422d86")),
project("endDateTime", "startDateTime")
.andExpression("endDateTime - startDateTime").as("duration")
);
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();
In Mongo shell, you can do the following:
db.collection.aggregate( {$match:{ your-match } },
{ $group : {
_id : "$userId",
duration : { $subtract:["$endDateTime", "$startDateTime"]}},
} } );
using spring boot reactive: This will give you duration in mili seconds like 864000000
List<AggregationOperation> operations = new ArrayList<>();
operations.add(project().andExclude("_id")
.and(ArithmeticOperators.valueOf("duration")
.subtract("startDateTime"))
.as("endDateTime"));
operations.add(groupOperation);
//response
reactiveMongoTemplate.aggregate(newAggregation(operations), "collName",
Class.class);
Rather than using minus operation inside projection, I will suggest you to use ArithmaticOperation.Subtract inside projection pipeline.
ProjectionOperation projectionOperation=Aggregation.project().and(Subtract.valueOf(Date.from(Instant.now())).subtract("fieldname"));
I am trying to convert the following query:
{ "cd" : { "$lte" : ISODate("2013-06-30T09:12:29Z") , "$gte" : ISODate("2013-06-11T09:12:29Z")}}
To use with MongoTemplate and Query.
At the moment i am doing and approach like:
Query query = new Query();
query.addCriteria(Criteria.where("cd").lte(request.getTo()).gte(request.getFrom()));
mongoTemplate.find(query,MyDesiredEntity.class)
But the query above returns no results when the first one returns around 15 which it should(request.getTo and request.getFrom are java.util.Date).
Is there a way to achieve this with org.springframework.data.mongodb.core.query.Query
I got this to work by reversing the lte and gte calls. I wrote a test to show it working:
#Test
public void shouldBeAbleToQueryBetweenTwoDates() throws Exception {
// setup
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
MongoTemplate mongoTemplate = new MongoTemplate(new Mongo(), "TheDatabase");
DBCollection collection = mongoTemplate.getCollection("myObject");
// cleanup
collection.drop();
// date that should match
Date expectedDate = dateFormat.parse("2013-06-12T00:00:00Z");
collection.insert(new BasicDBObject("cd", expectedDate));
// date that should not match (it's last year)
collection.insert(new BasicDBObject("cd", dateFormat.parse("2012-06-12T00:00:00Z")));
// create and execute the query
final Date to = dateFormat.parse("2013-06-30T09:12:29Z");
final Date from = dateFormat.parse("2013-06-11T09:12:29Z");
Query query = new Query();
query.addCriteria(Criteria.where("cd").gte(from).lte(to));
// check it returned what we expected
List<MyObject> basicDBObjects = mongoTemplate.find(query, MyObject.class);
Assert.assertEquals(1, basicDBObjects.size());
Assert.assertEquals(expectedDate, basicDBObjects.get(0).cd);
}
Notes:
This is TestNG not JUnit
I'm using SimpleDateFormat just to make testing of dates easier and (maybe) more readable
The main thing to note is:
query.addCriteria(Criteria.where("cd").gte(from).lte(to));
Before I reversed the order of the lte and gte the query was returning nothing.
I am wondering how I can search between by dates in Hibernate Search using Range-Query or is there any filter I have to implement.Following is my field in Record Entity
/**
* When the analysis started.
*/
#Temporal(TemporalType.TIMESTAMP)
#Field(index = Index.UN_TOKENIZED)
#DateBridge(resolution = Resolution.MILLISECOND)
private Date startTS;
My requirment is to find the records analysed between a two dates eg. 11/11/2011 to 11/11/2012.I am confused how to do this.
You should use a range query using from and to.
query = monthQb
.range()
.onField( "startTS" ).ignoreFieldBridge()
.from( DateTools.dateToString( from, DateTools.Resolution.MILLISECOND ) )
.to( DateTools.dateToString( to, DateTools.Resolution.MILLISECOND ) ).excludeLimit()
.createQuery();
The ignoreFieldBridge is needed since you create the string based search string yourself using DateTools.