Item queries for single entities
Use item queries to fetch single entities efficiently in Optimizely Graph.
Efficient caching lets you deliver content quickly and improves the overall user experience. When fetching single entities in Optimizely Graph, you can significantly enhance cache hit ratios by strategically using item
queries instead of items
in GraphQL.
Understand the cache challenge
GraphQL's flexibility can lead to queries that fetch lists of items using items
. While useful in many scenarios, this approach can reduce caching efficiency. Even if a query returns only a single item, using items
requires refreshing the entire list's cache when any item changes. This broad cache invalidation lowers performance compared to more targeted caching.
Benefit of item
item
The item
query lets you implement precision caching by focusing on a single item using its unique identifier. When an item changes, only its cache entry updates instead of refreshing the entire list's cache. This improves caching efficiency and boosts performance.
Example of an item
query
item
queryThe following code sample demonstrates an item
query that retrieves a single item based on its RelativePath
:
query GetItem($relativePath: String) {
Content(where: { RelativePath: { eq: $relativePath } }) {
item { Name RelativePath }
}
}
Optimize cache with item
item
- Improve cache hit ratio with
item
– Usingitem
queries improves cache efficiency by enabling more precise caching. Instead of refreshing the entire list, the cache updates only the specific item. This increases the likelihood of receiving up-to-date data for frequently accessed items. - Unique identifier-driven queries – Use
item
only when retrieving a single item based on unique identifiers such as the following:- Relative paths
- URLs
- Segments
- Code
- Any other uniquely identifiable field for the desired item.
- ID-based caching and purging – The GraphQL server caches the result of your
item
query using the returnedid
of the fetched item. This approach ensures the system only purges the cached result when that specific item is republished with changes. As a result, if other items are updated, your cacheditem
result remains valid, maximizing cache hits.
Updated 1 day ago