Query optimization for slow datetime comparisons in Sanity.io
15 replies
Last updated: Jul 10, 2020
T
Hey! Me and my team is having issues with slow queries towards Sanity. We discovered that when querying this one takes 3000ms
This one takes 20ms
Do you have any idea why the datetime comparisons are that slow? Or any suggestion how we could optimise our query?
*[ !(_id in path("drafts.**")) && (_type=='campaignLandingPage' || _type=='landingPage') && (!defined(launchAt) || launchAt < now()) && (!defined(endAt) || endAt > now()) ]
*[ !(_id in path("drafts.**")) && (_type=='campaignLandingPage' || _type=='landingPage') ]
Jul 10, 2020, 9:59 AM
M
it was slow for me too a few minutes ago but it passed
Jul 10, 2020, 10:00 AM
T
I don't think this is related to current issues. We've been having these problems for at least a week
Jul 10, 2020, 10:02 AM
P
Hi User, could you try wrapping
launchAtand
endAtin
dateTime()to check if this makes things more speedy?
*[ !(_id in path("drafts.**")) && (_type=='campaignLandingPage' || _type=='landingPage') && (!defined(launchAt) || dateTime(launchAt) < now()) && (!defined(endAt) || dateTime(endAt) > now()) ]
Jul 10, 2020, 10:14 AM
T
Hmm, getting some new issues with dateTime for null value, but it seems to be faster š
Jul 10, 2020, 10:21 AM
T
It didn't work with the comparison to now() without also wrapping it in
dateTime(now())just for reference
Jul 10, 2020, 10:27 AM
P
Thanks, that makes sense, sorry for the confusion š
Jul 10, 2020, 10:28 AM
P
Forgot that
now()returns a string. Are you seeing any better results?
Jul 10, 2020, 10:29 AM
T
Yeah, but I can't seem to get the query to work 100%. Still getting
No function dateTime() defined for arguments (null)
Jul 10, 2020, 10:30 AM
P
This clause doesn't seem to work
(defined(launchAt) && dateTime(launchAt) < dateTime(now())))
Jul 10, 2020, 10:31 AM
P
Still complains about getting launchAt null š
Jul 10, 2020, 10:31 AM
B
&& (!defined(launchAt) || (defined(launchAt) && dateTime(launchAt) < dateTime(now())))
Jul 10, 2020, 10:31 AM
P
Feels like that should cover all bases, right?
Jul 10, 2020, 10:31 AM
T
Also tried
With the same results
*[ !(_id in path("drafts.**")) && (_type=='campaignLandingPage' || _type=='landingPage') && select(!defined(launchAt) => false, dateTime(launchAt) < dateTime(now())) ]
Jul 10, 2020, 10:41 AM
T
Was able to fix this with
and now we have fast queries again, thanks a lot!
*[ !(_id in path("drafts.**")) && (_type=='campaignLandingPage' || _type=='landingPage') && dateTime(select(!defined(launchAt) => now(), launchAt)) <= dateTime(now()) && dateTime(select(!defined(endAt) => now(), endAt)) >= dateTime(now()) ]
user M
Jul 10, 2020, 11:16 AM
P
Great work fixing the query itself. Appreciate you sharing the solution here, thanks User!
Jul 10, 2020, 11:58 AM
Sanityā build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.