How to get all documents created in the last hour?
I found Paginate() parameter ts, but it only returns documents created earlier, not after.
That's strange, this code:
Paginate(Documents(Collection("fweets")), {
events: true,
after: Time("2020-05-22T19:12:07.121247Z")
})
should return the events after the given timestamp, do you encounter an issue trying to run such code?
The events from that result will include create and delete events. An alternative way is to create an index on 'ts' but this will also give you documents that were updated after the given timestamp.
Paginate(
Range(
Match(Index("fweets_after_ts")),
ToMicros(Time("2020-05-22T19:12:07.121247Z")),
null
)
)
A popular approach is to get the events of these created/updated docs then by running Pagiante with events again on top of that result. Which you can do by wrapping it in a map + paginate with events: true.
Map(Paginate(
Range(
Match(Index("fweets_after_ts")),
ToMicros(Time("2020-05-22T19:12:07.121247Z")),
null
)
),
Lambda(['ts', 'ref'], Paginate(Var('ref'), {events: true, after: Time("2020-05-22T19:12:07.121247Z")}))
)
Related
I have 2 tables contractPoint and contractPointHistory
ContractPointHistory
ContractPoint
I would like to get contractPoint where point will be subtracted by pointChange. For example: ContractPoint -> id: 3, point: 5
ContractPointHistory has contractPointId: 3 and pointChange: -5. So after manipulating point in contractPoint should be 0
I wrote this code, but it works just for getRawMany(), not for getMany()
const contractPoints = await getRepository(ContractPoint).createQueryBuilder('contractPoint')
.addSelect('"contractPoint".point + COALESCE((SELECT SUM(cpHistory.point_change) FROM contract_point_history AS cpHistory WHERE cpHistory.contract_point_id = contractPoint.id), 0) AS points')
.andWhere('EXTRACT(YEAR FROM contractPoint.validFrom) = :year', { year })
.andWhere('contractPoint.contractId = :contractId', { contractId })
.orderBy('contractPoint.grantedAt', OrderByDirection.Desc)
.getMany();
The method getMany can be used to select all attributes of an entity. However, if one wants to select some specific attributes of an entity then one needs to use getRawMany.
As per the documentation -
There are two types of results you can get using select query builder:
entities or raw results. Most of the time, you need to select real
entities from your database, for example, users. For this purpose, you
use getOne and getMany. But sometimes you need to select some specific
data, let's say the sum of all user photos. This data is not an
entity, it's called raw data. To get raw data, you use getRawOne and
getRawMany
From this, we can conclude that the query which you want to generate can not be made using getMany method.
In my back-end I'm using KnexJS with PostgreSQL and I have to build a Knex function using its SQL builder without the raw SQL.
It is the first time for me to use KnexJS and I got few issues.
What I have to build is as shown in the SQL example
UPDATE
feed
SET
status = 'SOME_STATUS'
WHERE
created_at <= 'SOME_TIMESTAMP'
AND conversation_id = 'ID';
This SQL is updating the table feed all columns with status and where two conditions are met.
In Knex what I tried as example code of my idea
answerPendingMessages(feeds) {
return this.tx(tableName).where({
conversationId,
createdAt <= timestamp // This not idea how to do in Knex ???
}).update({
status: 'ANSWERED'
})
}
In this above function my concern is how to actually convert the where part as one of the consitions is createdAt <= 'TIMESTAMP'
I understood that I can use where with an object but cannot understand how to include the <=
Also I should update the updatedAt column with the new timestamp but also that blocked me at the moment.
Te result in the end should that all columns which met the conditions are updated status to some some status and also a new updatedAt timestamp.
I'm not sure if there is a specific way with Knex to do so
This answer is to provide my goal for my previous question.
The script I'm showing is not doing anything and I don't know know to make it to work.
answerPendingMessages(feeds) {
if (isEmpty(feeds)) return Promise.resolve([]);
const { conversationId, createdAt } = feeds;
return this.tx(tableName)
.where(
columns.conversationId === conversationId,
columns.createdAt <= createdAt
)
.update({
[columns.status]: 'ANSWERED',
[columns.updatedAt]: new Date(),
});
}
What should happen here is that to update a table where I have two conditions but one of then is 'smaller than or equals' relation.
As the output of this should be that all rows where the 2 conditions are met are update status column.
Right now the script is not failing either success piratically nothing is happening.
I am able to use the following code to retrieve documents from a Fauna collection that have a date which falls between start and end dates:
Paginate(Range(Match(Index("orders_by_date")) , start, end))
Is it possible to add another criteria to this statement to retrieve not only, in this case, orders between two dates but also have the field status = "completed".
Thank you
You can create an index that way:
CreateIndex(
{
name:'orders_by_date_status',
source:Collection("orders"),
terms: [{field:['data','status']}],
values:[{field:['data','order_date']},{field:['ref']}]
}
)
and query your collection with a query like this:
Paginate(
Range(
Match('orders_by_date_status','completed'),
[Date("2020-03-20")],
[Date("2020-06-20")]
)
)
to get back something like this:
{
data: [
[Date("2020-05-20"), Ref(Collection("orders"), "285246145700037121")],
[Date("2020-06-20"), Ref(Collection("orders"), "285246152717107713")]
]
}
Hope this answers your question.
Luigi
I have logic querying a MSSQL Server database view and I've been searching for a solutions along with trying different techniques. Of course I don't expect a full solution where this is two parts (query builder & frontend javascript/chart) but any helpful direction would greatly appreciated. Here I'm getting the count of Leads on a particular day grouped by the date created and source of the leads. I'm trying build this the Laravel way so to speak, and display in charts.js. I'm thinking I might need to make two different database calls/queries. One count and one for the group by source text.
Thank you for your help for a solutions or an helpful direction I can take.
I have already done total leads for another chart but this project has some extra sugar to it.
SELECT count([LeadID]) as numleads,[LeadSource],cast(leadcreated as date) as
`enter code here`createddate
FROM [myDatabase].[dbo].[viewAllLeads]
where companyid=001
group by cast(leadcreated as date),[LeadSource]
order by createddate
Chart.js set up:
- Top links (horizontal) the groupby info by LeadSource
- Left, y-axis - the count of the leads
- Bottom x-axis - the date lead was created
It should actually be straight forward, but you need to be aware that using DB::raw() is necessary. To begin with, here your query a little bit nicer formatted:
SELECT
[LeadSource],
CAST([leadcreated] as date) as createddate,
COUNT([LeadID]) as numleads
FROM [dbo].[viewAllLeads]
WHERE [companyid] = '001'
GROUP BY [LeadSource], CAST([leadcreated] as date)
ORDER BY [createddate]
And converted to an Eloquent query:
DB::table('viewAllLeads') // the query builder doesn't care if it's a table or view
->select([
'LeadSource',
DB::raw('CAST(leadcreated as date) as createddate'),
DB::raw('COUNT(LeadID) as numleads')
])
->where('companyid', '001')
->groupBy('LeadSource', DB::raw('CAST(leadcreated as date)'))
->orderBy('createddate')
->get();
This will return a Illuminate\Support\Collection containing stdClass objects of the following form:
object(stdClass)#1 (3) {
["LeadSource"] => string(3) "ABC"
["createddate"] => string(10) "2019-08-05"
["numleads"] => int(15)
}
$leads = Lead::where('companyid', $companyid)->get()->groupBy(function ($item) {
return $item->created_at->format('Y-m-d');
})->sortBy(function ($item) {
return $item->created_at->format('x');
});
if you use dd($leads) you can see the data structure.
I'm trying to get the number of calls by commercial week. I've written the sql:
select strftime('%W', date_time_origination) as week, count(*)
from calls
group by week;
I then tried to run this in rails, firstly using this:
calls_by_week = Call.select("strftime('%W',date_time_origination) as week, count(*) as total_number_of_calls").group("week")
This returned a collection of objects with the correct data but repeated multiple times (json representation):
[{ "total_number_of_calls": 5435, "week": 39 },.....]
Given that it should have returned one object, I tried changing the rails query structure:
calls_by_week = Call.select("strftime('%W', date_time_origination) as week").group("strftime('%W', date_time_origination)").count
This time, the query returned one hash, minus the named params:
{ "31": 3123, "32": 1231,... }
I'd like to have the data, in json, presented as follows:
{ "week": 31, "total_number_of_calls": 12412,.....}
Is there a way of eliminating the duplication produced by the first query?
First: if you use Call.select(...) rails will try to instanciate Call objects. What you want are not Call objects, just hashes. You can use Call.connection.execute("SELECT .... blah blah").to_enum.to_a and use the resulting array of arrays.
But to convert your result to hash form, use
returned_hash = { "31": 3123, "32": 1231,... }
what_you_want = returned_hash.collect do |k,v|
{"week" => k.to_i, "total_number_of_calls" => v.to_i}
end
Another way is to use .uniq applied to the query, it will still build Call objects, but at least they will not have repeated data.