Materialize image assets in a Portable Text query
The image type holds your user-defined fields alongside four built-in ones: asset, media, hotspot, and crop. The asset field is a reference to the actual asset document. Quite often you need to access the asset document to make decisions based on the size, name, type, or metadata of the image, or to get the full URL to the image.
Join the asset document with GROQ
You can join these references when you fetch the documents containing a Portable Text field. Let's say you have a document type named article with a body field containing an array of blocks. The following query materializes the asset reference on every image block in that array:
*[_type == "article"]{
_id,
title,
body[]{
...,
_type == "image" => {
asset->{
_id,
url,
originalFilename,
mimeType,
size,
"dimensions": metadata.dimensions
}
}
}
}[0...5][
{
"_id": "0055468a-ebdc-459a-8a4a-e7e40e9da1ee",
"title": "How form paths work",
"body": [
{
"_key": "7eacf4391d53",
"_type": "block",
"style": "normal",
"markDefs": [],
"children": [
{
"_key": "8507e5919f950",
"_type": "span",
"marks": [],
"text": "A form path provides a unique and stable address for a value in a Sanity document."
}
]
},
{
"_key": "3ca672dd47d1",
"_type": "image",
"alt": "Alice and Bob both try to move an array member.",
"caption": "Click to view a larger image",
"asset": {
"_id": "image-804354b8fd7fad8e9a4afced96e6bdeb142ca649-1600x704-png",
"url": "https://cdn.sanity.io/images/3do82whm/next/804354b8fd7fad8e9a4afced96e6bdeb142ca649-1600x704.png",
"originalFilename": "How form paths work - Figure 1 - 1600x704.png",
"mimeType": "image/png",
"size": 171366,
"dimensions": {
"_type": "sanity.imageDimensions",
"aspectRatio": 2.272727272727273,
"height": 704,
"width": 1600
}
}
}
]
}
]Let's break it down:
- Fetch all documents of type
article:*[_type == "article"] - Include the document's own fields so each result is identifiable:
_id, title - For each item in the
bodyarray:body[] - Return all the properties of each block:
... - For image blocks only, replace the
assetreference with the fields you need from the document it points to:_type == "image" => {asset->{...}} - Return only the first five documents matched:
[0...5]
Scoping the join to image blocks matters. An unscoped asset-> adds an "asset": null property to every text block in the array. A bare asset-> also returns the whole asset document, including the color palette and a base64 metadata.lqip preview string, so project only the fields you need.
Learn more about GROQ
GROQ is the recommended way to query content in the Content Lake. Find out how GROQ queries work, or see Sanity's GraphQL API for a schema-typed alternative.