I am in progress of migration a JPA/MySQL application to mongodb using morphia. I have some queries like
AND DATE(NOW()) > (DATE(created) + 2)
or
AND ( TIMESTAMPDIFF(MINUTE,kickoff,now()) > 1 )
or
AND DATE(ending) = DATE(NOW())
Is there anything similar in morphia or mongodb?
From your question I understand that you ask for a way to create date queries in MongoDB and how would your write that query in Morphia
The Cookbook for date queries can be found here.
As pointed in the above post, you should use a range query for this.
In MongoDB's shell, for your first query, you would write it like this:
// hope I got the date part right XD
db.posts.find({created: {$lt: new Date().getDate() - 2}});
For range queries morphia has 2 ways:
using the filter method
using directly the comparator methods.
So the first query would become something like this:
myObjDao.createQuery().field("created").lessThan(new Date(System.currentTimeMillis() - 2 * 24 * 3600 * 1000 )).fetch();
Related
It sounded like a simple problem, but I found no easy solution online.
I am trying to replicate the current ORDER BY in Hibernate, without succes:
SELECT * FROM IPEM.DEMANDE
WHERE INIT_DATE >= TO_TIMESTAMP('23/04/2021', 'dd/MM/yyyy') AND INIT_DATE <=
TO_TIMESTAMP('29/04/2021', 'dd/MM/yyyy')
ORDER BY TO_TIMESTAMP(LIMIT_DATE, 'dd/MM/yyyy'), TO_TIMESTAMP(INIT_DATE , 'dd/MM/yyyy') ASC <<< this line
Why ? Because I have this kind of data in my database:
05/05/2021 00:00:00 - 23/04/2021 00:00:00
05/05/2021 00:00:00 - 28/04/2021 00:00:00 << this should be 3rd
05/05/2021 02:00:00 - 24/04/2021 00:00:00 << this should be 2nd
The hours mess up the sorting. I'm trying to ignore them/format the date before loading my entries. A way I found to do so is applying TO_TIMESTAMP to ORDER_BY. It works well in SQL, but when going to Hibernate, it is not that simple.
Actually, my code looks like this:
criteria.addOrder(Order.asc(fieldName));
I tried some trivial solution, which obviously did not work:
criteria.addOrder(Order.asc("TO_TIMESTAMP(" + fieldName + ", 'dd/MM/yyyy')");
For which I had the following error (limitDate is the Java name, LIMIT_DATE the corresponding column):
org.hibernate.QueryException: could not resolve property: TO_TIMESTAMP(limitDate, 'dd/MM/yyyy')
How can I apply TO_TIMESTAMP to the members of my ORDER BY ? (No worries, we assume here all the members are dates, both in Java and in the SQL Table).
That's not possible, but you can subclass Order and override the org.hibernate.criterion.Order#toSqlString method to implement whatever logic you need. Anyway, you should move away from the legacy Criteria API to the JPA Criteria API. There you could use criteriaQuery.orderBy(criteriaBuilder.function("TO_TIMESTAMP", root.get(fieldName), criteriaBuilder.literal("dd/MM/yyyy")))
I am trying to create a dataflow pipeline template, which required me to read data from bigquery. So what i need is to make my query dynamic using like Instant.now() but it seems the query is locked when creating the template
Some Code HERE
Some Code HERE
Some Code HERE
pipeline.apply("ReadFromBigQuery",
BigQueryIO.read(new DataTransformer(MyCustomObject.getQuery()))
.fromQuery(spec.getQuery())
.usingStandardSql()
.withQueryLocation("US")
.withoutValidation()
).apply("do Something 1",
Combine.globally(new CombineIterableAccumulatorFn<MyCustomObject2>())
).apply("do Something 2",
ParDo.of(new SendToKenshoo(param, param2)
);
My query is like this
SELECT * FROM `my-project-id.my-dataset.my-view` where PARTITIONTIME between TIMESTAMP('#currentDate') and TIMESTAMP('#tomorrowDate')
need to replace that #currentDate and #tomorrowDate using Instant.now() or any time function
please give me some example
note : i need to change the date on the code instead on query level like this
SELECT * FROM `my-project-id.my-dataset.my-view` where PARTITIONTIME between DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY) and CURRENT_DATE()
I'm not sure how you're sending those parameters to the query (via value provider, etc). However, I wouldn't recommend using templates for that because you need dynamic inputs. If you want to do that, I would use Flex Templates: https://cloud.google.com/dataflow/docs/guides/templates/using-flex-templates
I have the following native query:
... lockTimestamp + :delay SECOND) < CURRENT_TIMESTAMP
That I want to translate to Spring Data Jpa. The thing is that I get an error if I use it like this. I'm wondering if there is a direct translation to Spring Data Jpa or if not, I need to use something like this:
... lockTimestamp < :limitDate
Where limitDate is another Param in the Query calculated like:
DateUtils.addSeconds(new Date(), -delay)
I have two fields in my ES index: min_duration and max_duration. I want to create a query to find all the documents for input duration such that :
min_duration<=duration<=max_duration
For example if duration is 30 seconds then I should get all docs having min_duration less than eq to duration and duration less than eq to max_duration.
I am using ES Java API and seems like range filter is the way to go. I have constructed the range filter as follows:
val filter = FilterBuilders.andFilter( FilterBuilders.rangeFilter("min_duration").lte(duration),FilterBuilders.rangeFilter("max_duration").gte(duration))
Though it still not seems to work for me. Is it the correct way to build this type of query or am I missing something?
Thanks.
Try doing it with bool query. Wrap your two range clauses inside it like
QueryBuilder qb = boolQuery()
.must(rangeQuery("max_duration").gte(duration))
.must(rangeQuery("min_duration").lte(duration));
Does this help?
I would like to use Date() function in hibernate criteria, since one field is timestamp.
My sql would be:
"select * from feed where DATE(date) = DATE(NOW()) + INTERVAL 5 DAY"
When I try in criteria:
critera.add(Restrictions.eq("DATE(date)", "DATE(NOW()) + INTERVAL 5 DAY"));
I get:
could not resolve property: DATE(date) of: com.mycomapany.model.Feed
I have there in feed a field by the name date.
What is the problem? I am using MySQL
The best solution is to use the criteria api which you started to use.
Calendar c = Calendar.getInstance(LOCALIZATION);
//Add 5 Days
c.add(Calendar.DATE, 5);
criteria.add(Expression.ge("dateColumn",c.getTime());
You could probably find a way to make this work, but in my opinion, this is the wrong way to approach it.
One of the major features of Hibernate is the abstraction of the database-vendor-specific features, via the Hibernate Dialect.
You are attempting to access MySQL features directly, but through the vendor-neutral interface, thus your difficulty. Hibernate could have support for date intervals , but does not - see https://hibernate.onjira.com/browse/HHH-2434
So, the options seem to be:
Calculate the date ranges in your code, rather than in the HQL
Do what you need to do in SQL rather than HQL
Create a custom Hibernate Dialect, as in Performing Date/Time Math In HQL?
Using Joda Time:
public List<Feed> findByDaysFromToday(int daysFromToday) {
return em.createQuery(
"SELECT f FROM Feed f WHERE f.date BETWEEN :start AND :end")
.setParameter("start",
new LocalDate()
.toDateMidnight()
.toDate(),
TemporalType.DATE)
.setParameter("end",
new LocalDate().plusDays(daysFromToday)
.toDateMidnight()
.toDateTime()
.minusMillis(1)
.toDateTime()
.toDate(),
TemporalType.DATE)
.getResultList();
}