Select documents from Fauna collection between two dates AND that satisfy another criteria - faunadb

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

Related

How to modify value in column typeorm

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.

Sequelize Query - Count associated tables and count all for pagination

this is my first question on stackoverflow, never used it before but this issue is making me tear my hair out.
I'm building an infinite scroll component for a react app I'm working on a I'm trying to make a Postgres DB query work.
I have 2 tables - Challenges, and UserChallenges.
Challenges have many User Challenges.
I need to get a subsection of Challenges (from start to end) with each Challenge having a count of the number of "participants" (number of associated UserChallenges), and also a count of all challenges.
Something like this:
{
rows: [Challenge, Challenge, Challenge],
count: n
}
Where each challenge includes the total number of userChallenges as "participants" and count is a count of all challenges.
Here is the query:
let json_query = {
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("user_challenges.id")), "participants"]]
},
include: [{
model: UserChallenge, attributes: []
}],
order: [['timestamp', 'DESC']],
offset: start,
limit: end
}
The start and end quantities are the start and end of the pagination.
I'm running this query as follows:
var challengeInstances = await Challenge.findAndCountAll(json_query)
This results in the following error:
name: 'SequelizeDatabaseError',
parent: error: missing FROM-clause entry for table "user_challenges"
and this is the sql it's saying it's running:
`SELECT "challenge".* FROM (SELECT "challenge"."id", "challenge".*, COUNT("user_challenges"."id"), "challenge"."participants" FROM "challenges" AS "challenge" GROUP BY "challenge"."id" ORDER BY "challenge"."end_date" DESC LIMIT '4' OFFSET '0') AS "challenge" LEFT OUTER JOIN "user_challenges" AS "user_challenges" ON "challenge"."id" = "user_challenges"."challenge_id" ORDER BY "challenge"."end_date" DESC;`,
Sequelize or raw queries are both good.
Do let me know if you need any more information and thank you so so much.
you can use sequelize literal like this & remove object from attributes just paste this code for attributes .
attributes: [
[
sequelize.literal(`(
SELECT COUNT(id)
FROM user_challenges
WHERE
// your condition of foreign key like (user_challenges.participants_id = participants.id)
)`),
'numberOfParticipants'
]
]

Retrieve the count of each record (id) with a condition within CosmosDB

I have a container within CosmosDB that houses items. I am needing to find out the count of how many records I have within my container with the conditions of: Source and Date
This is a sample JSON schema in which each of my records/items holds. Each record has a unique id and acts as a single count.
{
"id": "1111111111122222222233333333",
"feedback": {
"Source": "test"
"Date": "1980-10-15T00:04:34Z",
"Ser": "test",
"Count_Of_Comments": "1",
"Count_Of_Votes": "1"
}
The container within CosmosDB looks like something like this:
Goal:
**I wish to return, the numb*er of id records (or the count) based on the Source and the Date.
This is what I have tried (below), however this does not seem to work and I am wondering if I am missing something here. Any help or suggestions are appreciated.
SELECT VALUE COUNT(c.id), c.Source, c.Date
FROM C
Where Source == "test", AND Date == "1980-10-15T00:04:34Z"
As David comments,there are some syntax errors.Please try this sql:
SELECT value COUNT(c.id) FROM c Where c.feedback.Source = "test" AND c.feedback.Date = "1980-10-15T00:04:34Z"
If you need Source and Date,you can try this:
SELECT COUNT(c.id) AS Count,max(c.feedback.Source) as Source,max(c.feedback.Date) as Date
FROM c
Where c.feedback.Source = "test" AND c.feedback.Date = "1980-10-15T00:04:34Z"
By the way,both COUNT(c.id) AND COUNT(1) can achieve your goal in your situation.More detail about SQL Query,you can refer to this documentation.
Hope this can help you.

Laravel query builder for Charts.js

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.

Rails - Date Query using group by and count

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.