Implement a sitemap for images/video hybrid strategy: partitioning and freshness.
- User
Implement a sitemap for images/video hybrid strategy: partitioning and freshness.
Assistant
Implement a sitemap for images/video hybrid strategy: partitioning and freshness.
The user wants to implement a sitemap strategy for a website that hosts both images and videos. The specific requirements mentioned are:
Key Concepts:
<image:image> tags.<video:video> tags.Step-by-Step Implementation Plan:
Structure the Sitemap Index: This is the entry point. It needs to list the child sitemaps.
Partitioning Strategy:
<url> entry should contain both <image:image> and <video:video> tags. However, for large sites, we partition by ranges of IDs or dates.sitemap_pages.xml (Standard)sitemap_images.xml (Pages heavy on images?)sitemap_videos.xml (Pages heavy on videos?)Freshness Strategy:
lastmod is crucial.sitemap_latest.xml) that only contains URLs changed in the last 48 hours. This allows search engines to ping just this small file frequently.Implementation (Code/Logic):
Refining the Strategy:
sitemap_1.xml, sitemap_2.xml) or Content Type if the pages are distinct (e.g., /videos/ vs /photos/).lastmod updated.Drafting the Content:
<url> looks with both <image> and <video> tags.Specifics for Images/Video:
<loc>, <caption>, <title>, <geo_location>, <license>.<loc>, <thumbnail_loc>, <title>, <description>, <content_loc>, <duration>, <expiration_date>.Self-Correction/Edge Case: What if a site has millions of pages?
Final Output Structure:
Let's double-check the "Hybrid Strategy" term. It usually refers to having media on pages.
If the user has distinct pages for images (e.g., a gallery view) and distinct pages for videos, they should split sitemaps by content type for easier debugging.
If a page has both (e.g., a blog post with a video and thumbnails), they must be in the same <url> tag.
I will assume a scenario where a page can contain both, but for partitioning, we might want to separate high-value video pages from simple image galleries if they are distinct URL structures. However, the most robust generic strategy is splitting by ID/Time to ensure even distribution, except for the "Freshness" bucket.
Plan:
sitemap_fresh.xml (High priority, frequently updated).sitemap_archive_1.xml, sitemap_archive_2.xml (Static, rarely changed).Let's write the response. Implementing a sitemap strategy for a hybrid Image/Video site requires balancing file size limits (partitioning) with crawl efficiency (freshness).
Here is a comprehensive implementation guide using a Dynamic Delta Strategy. This approach separates your stable archival content from your rapidly changing fresh content.
Search engines (like Google) impose a strict limit of 50MB uncompressed and 50,000 URLs per sitemap file. Videos and Images add significant byte-weight to XML files, so you will hit the size limit much faster than with text-only sitemaps.
We will implement three layers:
For pages that contain both images and videos, do not create separate sitemaps for the same URL. Combine them into a single <url> entry to consolidate ranking signals.
Example: Single URL with Hybrid Content
<url>
<loc>https://example.com/media/sunset-timelapse</loc>
<lastmod>2023-10-27T10:00:00+00:00</lastmod>
<!-- Image Data -->
<image:image>
<image:loc>https://example.com/img/sunset.jpg</image:loc>
<image:title>Sunset over the ocean</image:title>
<image:caption>A time-lapse capture of a sunset</image:caption>
</image:image>
<!-- Video Data -->
<video:video>
<video:thumbnail_loc>https://example.com/thumbs/sunset.jpg</video:thumbnail_loc>
<video:title>Sunset Time-lapse 4K</video:title>
<video:description>Watch the sun go down in 4k resolution.</video:description>
<video:content_loc>https://example.com/video/sunset.mp4</video:content_loc>
<video:player_loc allow_embed="yes">https://example.com/player/sunset</video:player_loc>
<video:duration>600</video:duration>
<video:publication_date>2023-10-27T10:00:00+00:00</video:publication_date>
</video:video>
</url>
This script demonstrates how to generate a Sitemap Index that points to partitioned sitemaps.
It creates two types of partitions:
fresh.xml: Contains the last 48 hours of content (High Freshness).archive_X.xml: Contains older content sharded by ID or Date (Partitioning).To make this strategy effective, apply these rules:
If your sitemap_archive grows large, do not rely on a single file. Split it.
sitemap_2022_01.xml, sitemap_2022_02.xml.sitemap_1_1000.xml, sitemap_1001_2000.xml.When you generate the sitemap_fresh.xml (ideally via a cron job or CI/CD pipeline upon new content publication), ping search engines to alert them immediately.
http://www.google.com/ping?sitemap=https://example.com/sitemap_index.xmllastmod Discipline<lastmod> reflects the actual change time of the media content or the page text. Do not update this timestamp if only a CSS file changed.<lastmod> in the index file tells the crawler "Has this partition changed since I last looked?" Update this accurately so crawlers skip downloading large archive files if they haven't changed.Point your robots.txt to the index file, not the partitions.
Sitemap: https://example.com/sitemaps/sitemap_index.xml
sitemap_fresh.xml.sitemap_archive_X.xml.sitemap_index.xml with current timestamps for the modified partitions.sitemap_fresh.xml has a new timestamp, downloads it (high priority), but ignores sitemap_archive_X.xml (saving bandwidth).import os
from datetime import datetime, timedelta
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom
# Configuration
SITE_URL = "https://example.com"
OUTPUT_DIR = "sitemaps"
FRESHNESS_THRESHOLD_HOURS = 48
# Mock Data Function
def get_media_items():
# In production, replace this with a DB call
# Returns a list of dicts with page_url, image_url, video_url, and timestamp
return [
{
"id": 1,
"page_url": f"{SITE_URL}/media/old-video",
"image_url": f"{SITE_URL}/img/old.jpg",
"video_url": f"{SITE_URL}/vid/old.mp4",
"lastmod": datetime.now() - timedelta(days=10) # Old content
},
{
"id": 2,
"page_url": f"{SITE_URL}/media/new-video",
"image_url": f"{SITE_URL}/img/new.jpg",
"video_url": f"{SITE_URL}/vid/new.mp4",
"lastmod": datetime.now() - timedelta(hours=1) # Fresh content
}
]
def prettify(elem):
"""Return a pretty-printed XML string."""
rough_string = tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ", encoding="UTF-8")
def build_sitemap(filename, items):
urlset = Element('urlset')
urlset.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
urlset.set("xmlns:image", "http://www.google.com/schemas/sitemap-image/1.1")
urlset.set("xmlns:video", "http://www.google.com/schemas/sitemap-video/1.1")
for item in items:
url = SubElement(urlset, "url")
SubElement(url, "loc").text = item['page_url']
SubElement(url, "lastmod").text = item['lastmod'].isoformat()
# Add Image
img = SubElement(url, "image:image")
SubElement(img, "image:loc").text = item['image_url']
# Add Video
vid = SubElement(url, "video:video")
SubElement(vid, "video:thumbnail_loc").text = item['image_url'] # Assuming thumb matches image
SubElement(vid, "video:title").text = f"Video {item['id']}"
SubElement(vid, "video:content_loc").text = item['video_url']
SubElement(vid, "video:publication_date").text = item['lastmod'].isoformat()
with open(os.path.join(OUTPUT_DIR, filename), "wb") as f:
f.write(prettify(urlset))
print(f"Generated {filename} with {len(items)} items.")
def build_index(sitemap_files):
sitemapindex = Element('sitemapindex')
sitemapindex.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for fname in sitemap_files:
sitemap = SubElement(sitemapindex, "sitemap")
SubElement(sitemap, "loc").text = f"{SITE_URL}/sitemaps/{fname}"
# The lastmod of the index file helps crawlers know if they need to re-download the partition
SubElement(sitemap, "lastmod").text = datetime.now().isoformat()
with open(os.path.join(OUTPUT_DIR, "sitemap_index.xml"), "wb") as f:
f.write(prettify(sitemapindex))
print("Generated sitemap_index.xml")
def generate_strategy():
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
all_items = get_media_items()
fresh_items = []
archive_items = []
cutoff = datetime.now() - timedelta(hours=FRESHNESS_THRESHOLD_HOURS)
# 1. Partition by Freshness
for item in all_items:
if item['lastmod'] > cutoff:
fresh_items.append(item)
else:
archive_items.append(item)
sitemap_files = []
# 2. Generate Fresh Sitemap (High Priority, frequently crawled)
if fresh_items:
fname = "sitemap_fresh.xml"
build_sitemap(fname, fresh_items)
sitemap_files.append(fname)
# 3. Generate Archive Partitions (Sharding by size or ID)
# In a real scenario, you split this if len > 50,000 or size > 50MB
if archive_items:
fname = "sitemap_archive_1.xml"
build_sitemap(fname, archive_items)
sitemap_files.append(fname)
# 4. Build Master Index
build_index(sitemap_files)
if __name__ == "__main__":
generate_strategy()