Search a date range
Solution
You can search for query results in a range of dates using an index and a user-defined function.
The solution has several steps:
-
Update your GraphQL schema
This example needs the following types:
graphqlCopied!type Todo { title: String! completed: Boolean completedDate: Date! } type Query { todosByDateRange(fromDate: Date!, toDate: Date!): [Todo!] @resolver(name: "todosByDateRange") }
This involves editing the GraphQL schema definition, wherever you have stored it, and then uploading the new schema in the Fauna Dashboard.
When you import the above schema, the GraphQL API automatically creates a collection named
Todo
and a UDF namedtodosByDateRange
.For more information about importing GraphQL schemas, see the GraphQL quick start. -
Create some documents to search
graphqlCopied!mutation { Todo1: createTodo( data:{ title: "Walk the dog" completed: true completedDate: "2022-01-10" }) { _id }, Todo2: createTodo( data:{ title: "Feed the cat" completed: true completedDate: "2022-01-12" }) { _id }, Todo3: createTodo( data:{ title: "Wash the car" completed: false completedDate: "2022-01-26" }) { _id } }
-
Create an index to search by date range
{ ref: Index("todos_by_completed_date"), ts: 1643836096660000, active: true, serialized: true, name: 'todos_by_completed_date', source: Collection("Todo"), values: [ { field: [ 'data', 'completedDate' ] }, { field: [ 'ref' ] } ], partitions: 8 }
-
Update the sub function
todosByDateRange
Our schema defined a query called
todosByDateRange
, which, due to the@resolver
directive directive, caused the GraphQL API to create a UDF with that name. However, the GraphQL API doesn’t know what should happen. We need to update the function to provide the appropriate operations:{ ref: Function("todosByDateRange"), ts: 1646419021630000, name: 'todosByDateRange', body: Query(Lambda(["fromDate", "toDate"], Map(Select(["data"], Paginate(Range(Match(Index("todos_sorted_by_completed_date")), Var("fromDate"), Var("toDate")))), Lambda(["date", "ref"], Get(Var("ref")))))) }
-
Call the resolver
graphqlCopied!query getTodos { todosByDateRange( fromDate: "2022-01-01", toDate: "2022-01-15" ) { title completed completedDate } }
The query generates the following results:
{ "data": { "todosByDateRange": [ { "title": "Walk the dog", "completed": true, "completedDate": "2022-01-10" }, { "title": "Feed the cat", "completed": true, "completedDate": "2022-01-12" } ] } }
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!