Introduction to Groq
Groq is a versatile querying language designed to handle complex data queries with ease. Whether you’re working with structured data or seeking to enhance your application’s performance, Groq offers an array of powerful APIs that simplify the data querying process.
Groq API Examples
Here, we’ll explore a variety of Groq APIs and provide practical code snippets to illustrate their usage.
Basic Query
{ "allFilms": *[_type == "film"] { title, releaseYear } }
This query fetches all film records, displaying their title and release year.
Filter by Condition
{ "recentFilms": *[_type == "film" && releaseYear > 2000] { title, releaseYear } }
This query filters films released after the year 2000.
Sort Results
{ "sortedFilms": *[_type == "film"] | order(releaseYear desc) { title, releaseYear } }
This query sorts films by release year in descending order.
Projection
{ "filmTitles": *[_type == "film"].title }
This query projects only the titles of the films.
Pagination
{ "paginatedFilms": *[_type == "film"] [0...10] { title, releaseYear } }
This query fetches the first 10 film records.
References
{ "directorFilms": *[_type == "director"][0] { name, "films": *[_type == "film" && references(^._id)] { title } } }
This query finds films directed by the first director in the dataset.
Combining Queries
{ "filmData": { "recentFilms": *[_type == "film" && releaseYear > 2000] { title }, "allDirectors": *[_type == "director"].name } }
This query combines multiple queries to fetch recent films and all directors.
Application Example
Let’s build a simple web app that utilizes the above Groq APIs to display film data.
<html> <head> <title>Groq Film Database</title> </head> <body> <h1>Welcome to the Groq Film Database</h1> <div id="film-list"></div> <script> async function fetchFilms() { const query = `{ "allFilms": *[_type == "film"] { title, releaseYear } }`; const response = await fetch('https://api.yourdata.com/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const data = await response.json(); displayFilms(data.allFilms); } function displayFilms(films) { const filmList = document.getElementById('film-list'); films.forEach(film => { const filmItem = document.createElement('div'); filmItem.textContent = `${film.title} (${film.releaseYear})`; filmList.appendChild(filmItem); }); } fetchFilms(); </script> </body> </html>
The above code defines a simple HTML structure and JavaScript to fetch and display film data using Groq.