Replace the Google Custom Search JSON API
Google is turning off the Custom Search JSON API. Its overview page says: “Existing Custom Search JSON API customers have until January 1, 2027 to transition to an alternative solution.” The API is not available for new customers.
This guide moves a site search from the Custom Search JSON API to the Relevan search API. You load the pages of your site into a Relevan index, change the search request, and read the new response.
Quick reference
The field names come from step 1. A sitemap source and the script write the same fields, and the script also writes site. The full tables are in step 2.
| Custom Search JSON API | Relevan |
|---|---|
GET /customsearch/v1 | POST https://api.relevan.dev/v1/{orgId}/indexes/{indexName}/search with a JSON body |
key | The x-api-key header |
cx | {indexName} in the path |
q | query |
num | size |
start | from, which is start - 1 |
siteSearch | With the script: filters: [{ "field": "site", "value": "docs.example.com" }]. A sitemap source writes no host field, so give each host its own index. |
sort | No sort. Relevan orders results by relevance. For a date range, use a range filter on lastmod. |
items[].title | results[].document.title |
items[].link | results[].document.url |
items[].snippet | No excerpt yet. Show results[].document.description. |
searchInformation.totalResults | searchContext.totalHits |
queries.nextPage | A next page exists when from + size is less than searchContext.totalHits and is not more than 500. |
Relevan does not return an excerpt of the matched text yet. Until it does, show description in the place of snippet. Step 1 fills description from the <meta name="description"> of the page. When a page has no such tag, the script uses the first 300 characters of the text of the page. A sitemap source uses the <meta name="description"> tag first, then the og:description tag, and leaves description empty when the page has neither tag. If your index has no description, show the start of body.
What is different
Relevan searches only the documents that you load into your index. It does not search the open web. It fetches only the pages of a sitemap that you add. If your app uses the Custom Search JSON API to search the whole web, Relevan does not replace it.
For a search over your own site, you get these changes:
- You choose the fields of each page, and you can filter on them.
- Each result has an
explanationof why it matched. - You can send click and conversion feedback for each search. Relevan uses the feedback to train the ranking of your index offline, not on each click.
1. Load your site into an index
You have two ways to load the pages of your site:
- A sitemap source. You verify your domain with a DNS TXT record and add the URL of your sitemap. Relevan fetches each page, writes it to your index, and syncs again about once a day. Index a website from its sitemap gives the steps.
- The script below. It reads the
sitemap.xmlof your site, fetches each page, and uploads its title, URL, description, and text to the bulk document endpoint. Use it when you cannot add a DNS record, or to run the load from your own server.
A sitemap source writes the same fields as the script, except site.
To use the script, you need:
- Python 3.10 or later, and the Relevan client:
pip install relevan. - A write API key from the console, in the
RELEVAN_API_KEYenvironment variable. A read key gets 403 when it creates an index.
Save the script as sitemap_to_relevan.py:
"""Load the pages of a sitemap.xml into a Relevan index.
Usage: python sitemap_to_relevan.py https://example.com/sitemap.xml site-pages
"""
import hashlib
import sys
import time
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from urllib.parse import urlparse
from relevan import Client, RelevanAPIError
SITEMAP_NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
SKIP_TAGS = {"script", "style", "noscript", "nav", "header", "footer", "aside", "svg"}
MAX_BODY_CHARS = 20_000
BATCH_SIZE = 100
def fetch(url):
request = urllib.request.Request(
url, headers={"User-Agent": "relevan-sitemap-loader"}
)
with urllib.request.urlopen(request, timeout=30) as response:
return response.read()
def sitemap_entries(sitemap_url):
"""Each (url, lastmod) in the sitemap. A sitemap index is read recursively."""
root = ET.fromstring(fetch(sitemap_url))
if root.tag.endswith("sitemapindex"):
for loc in root.findall("sm:sitemap/sm:loc", SITEMAP_NS):
yield from sitemap_entries(loc.text.strip())
return
for entry in root.findall("sm:url", SITEMAP_NS):
lastmod = entry.findtext("sm:lastmod", namespaces=SITEMAP_NS)
yield entry.findtext("sm:loc", namespaces=SITEMAP_NS).strip(), lastmod
class PageParser(HTMLParser):
def __init__(self):
super().__init__()
self.title = ""
self.description = ""
self.lang = ""
self.text = []
self.main_text = []
self._skip_depth = 0
self._main_depth = 0
self._in_title = False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "html":
self.lang = (attrs.get("lang") or "").split("-")[0].lower()
elif tag in SKIP_TAGS:
self._skip_depth += 1
elif tag == "main":
self._main_depth += 1
elif tag == "title" and not self._skip_depth and not self.title:
self._in_title = True
elif tag == "meta" and attrs.get("name") == "description":
self.description = attrs.get("content") or ""
def handle_endtag(self, tag):
if tag in SKIP_TAGS and self._skip_depth:
self._skip_depth -= 1
elif tag == "main" and self._main_depth:
self._main_depth -= 1
elif tag == "title":
self._in_title = False
def handle_data(self, data):
if self._in_title:
self.title += data
elif not self._skip_depth and data.strip():
self.text.append(data.strip())
if self._main_depth:
self.main_text.append(data.strip())
def page_document(url, lastmod):
parser = PageParser()
parser.feed(fetch(url).decode("utf-8", errors="replace"))
# Keep only the <main> element when the page has one, to leave out menus.
body = " ".join(parser.main_text or parser.text)[:MAX_BODY_CHARS]
parts = urlparse(url)
content = {
"title": parser.title.strip() or url,
"url": url,
"site": parts.hostname,
"description": parser.description.strip() or body[:300],
"body": body,
}
section = parts.path.strip("/").split("/")[0]
optional = {"section": section, "lang": parser.lang, "lastmod": lastmod}
content.update({name: value for name, value in optional.items() if value})
# A document id allows only letters, digits, "_", ".", ":", and "-", so a
# URL cannot be the id. A hash of the URL is stable across runs.
return hashlib.sha256(url.encode()).hexdigest()[:32], content
def create_index(client, org_id, index_name):
try:
client.indexes.create(org_id, name=index_name)
except RelevanAPIError as error:
if error.status_code != 409:
raise
return
client.mappings.create(
org_id,
index_name,
fields={
"title": {"use": ["searchable", "autocompletable"], "kind": "text"},
"description": {"use": ["searchable"], "kind": "text"},
"body": {"use": ["searchable"], "kind": "text"},
"url": {"use": ["filterable"], "kind": "id"},
"site": {"use": ["filterable"], "kind": "id"},
"section": {"use": ["filterable"], "kind": "id"},
"lang": {"use": ["filterable"], "kind": "id"},
"lastmod": {"use": ["filterable"], "kind": "date"},
},
)
def main(sitemap_url, index_name):
client = Client()
org_id = client.organizations.list()[0].id
create_index(client, org_id, index_name)
batch = []
for url, lastmod in sitemap_entries(sitemap_url):
try:
batch.append(page_document(url, lastmod))
except (OSError, ValueError) as error:
print(f"skip {url}: {error}", file=sys.stderr)
continue
print(f"read {url}")
if len(batch) == BATCH_SIZE:
client.documents.bulk_ingest(org_id, index_name, documents=batch)
batch = []
time.sleep(0.5)
if batch:
client.documents.bulk_ingest(org_id, index_name, documents=batch)
print(f"uploaded the pages of {sitemap_url} to {index_name}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])Run it with the URL of your sitemap and the name of a new index:
python sitemap_to_relevan.py https://www.example.com/sitemap.xml site-pagesThe script makes one document for each page:
| Field | Value |
|---|---|
title | The <title> of the page |
url | The URL from the sitemap |
site | The host name, for example docs.example.com |
section | The first segment of the path, for example blog for /blog/launch |
description | The <meta name="description"> of the page, or the first 300 characters of its text |
body | The text of the <main> element, or of the full page, up to 20,000 characters |
lang | The lang attribute of the <html> element, for example en |
lastmod | The <lastmod> date from the sitemap |
The document id is a hash of the URL, so a second run updates each page in place. The script does not delete a page that left the sitemap. Delete it with the document endpoint, or create a new index.
Relevan builds the index in the background. Before you search, wait until the index status is ready and readyToSearch is true. Get your data in shows the request.
A page that needs JavaScript to show its text gives an empty body. For such a site, export the content from your CMS or database, and upload it with the same bulk endpoint.
2. Change the search request
With your coding agent
After step 1, you can give this prompt to your coding agent, such as Claude Code, Copilot CLI, or Codex. Replace site-pages with the name of your index.
Migrate this codebase's Google Custom Search JSON API calls to Relevan.
Endpoint and auth:
- Replace each GET https://www.googleapis.com/customsearch/v1 request with
POST https://api.relevan.dev/v1/{orgId}/indexes/site-pages/search and a JSON body.
- Send the API key in the x-api-key header. Read the key from the RELEVAN_API_KEY
environment variable on the server. Never send the key to the browser.
- Get {orgId} once from GET https://api.relevan.dev/v1/organizations (the "id" of the
first item), and keep it in configuration as RELEVAN_ORG_ID.
- Remove the Google key and cx parameters and their configuration.
Request mapping:
- q -> query
- num -> size (1 to 100)
- start (starts at 1) -> from = start - 1 (a maximum of 500)
- siteSearch=<host> -> filters: [{ "field": "site", "value": "<host>" }] when the index
has a site field. An index from a sitemap source has no site field, and it holds the
pages of each host that its sitemap lists. Remove siteSearch only when the sitemap
lists one host. Otherwise, stop and ask me.
- lr=lang_<code> -> filters: [{ "field": "lang", "value": "<code>" }]
- sort=date:r:<YYYYMMDD>:<YYYYMMDD> -> filters: [{ "field": "lastmod", "gte": "<YYYY-MM-DD>", "lte": "<YYYY-MM-DD>" }]
- Any other sort: remove it. Relevan orders results by relevance.
- exactTerms -> add the phrase to query in double quotes.
- excludeTerms -> add each word to query with a minus sign, for example -password.
Response mapping:
- items -> results
- items[].title -> results[].document.title
- items[].link -> results[].document.url
- items[].displayLink -> results[].document.site, or the host of results[].document.url
- items[].snippet and htmlSnippet -> results[].document.description. Relevan returns
no excerpt yet. If description is empty, use the first 200 characters of
results[].document.body.
- searchInformation.totalResults (a string) -> searchContext.totalHits (a number)
- searchInformation.searchTime (seconds) -> took (milliseconds)
- queries.nextPage -> a next page exists when from + size is less than
searchContext.totalHits and from + size is not more than 500.
Keep the existing results UI unchanged. Convert the Relevan response to the shape
that the UI reads now, in one function. Keep searchContext.queryId of each search
next to its results, for click feedback later. For Python code, you can use the
relevan client (pip install relevan): client.search.search(org_id, index_name,
query=..., size=..., offset=..., filters=[...]), where offset is from. Update the
tests that mock the Google response, and run the tests.By hand
The Custom Search JSON API takes a GET request with query parameters. Relevan takes a POST request with a JSON body. Your API key goes in the x-api-key header, and the index name goes in the path in place of cx.
Custom Search JSON API:
curl "https://www.googleapis.com/customsearch/v1?key=$GOOGLE_API_KEY&cx=$SEARCH_ENGINE_ID&q=reset+password&num=10&start=11&siteSearch=docs.example.com"Relevan:
curl -X POST https://api.relevan.dev/v1/{orgId}/indexes/site-pages/search \
-H "x-api-key: $RELEVAN_API_KEY" \
-H "content-type: application/json" \
-d '{
"query": "reset password",
"size": 10,
"from": 10,
"filters": [{ "field": "site", "value": "docs.example.com" }]
}'The same search in Python. Custom Search JSON API:
import os
import requests
response = requests.get(
"https://www.googleapis.com/customsearch/v1",
params={
"key": os.environ["GOOGLE_API_KEY"],
"cx": os.environ["SEARCH_ENGINE_ID"],
"q": "reset password",
"num": 10,
"start": 11,
"siteSearch": "docs.example.com",
},
)
for item in response.json().get("items", []):
print(item["title"], item["link"], item["snippet"])Relevan:
from relevan import Client
from relevan.resources.search import SearchFilterType0
client = Client()
org = client.organizations.list()[0]
results = client.search.search(
org.id,
"site-pages",
query="reset password",
size=10,
offset=10,
filters=[SearchFilterType0(field="site", value="docs.example.com")],
)
for hit in results.results:
print(hit.document["title"], hit.document["url"], hit.document["description"])Request parameters
| Custom Search JSON API | Relevan |
|---|---|
key | The x-api-key header. Use a read key for search. |
cx | The index name in the path: /v1/{orgId}/indexes/{indexName}/search |
q | query |
num (1 to 10) | size (1 to 100, default 10) |
start (starts at 1) | from (starts at 0, a maximum of 500). Use from = start - 1. The Python client calls it offset. |
siteSearch with siteSearchFilter=i | A filter on site: { "field": "site", "value": "docs.example.com" }. A sitemap source writes no site, and it indexes each host under the verified domain that the sitemap lists. To search one host, give each host its own index. For a path such as example.com/blog, filter on section. |
siteSearch with siteSearchFilter=e | No equivalent. A filter can only include values. Leave the pages out of the index, or use an in filter with the values to keep. |
lr, hl | A filter on lang: { "field": "lang", "value": "fr" }. Text analysis supports english and none. |
dateRestrict, sort=date:r:... | A range filter on lastmod: { "field": "lastmod", "gte": "2026-11-01" } |
sort=date | No equivalent. Relevan orders results by relevance only. |
exactTerms | Put the phrase in quotes in query, for example reset "two-factor code". Each result must contain a quoted phrase. |
excludeTerms | Put a minus sign before the word in query, for example reset -password. No result contains password in a searchable field. |
orTerms | Add the words to query. A result does not have to match each word. To give a word more weight, use boost, for example { "reset": 2 }. |
searchType=image | No equivalent. Relevan searches the documents that you upload. |
safe, gl, cr | No equivalent. You choose the pages in the index. To filter on another property, add it as a field. |
Response fields
| Custom Search JSON API | Relevan |
|---|---|
items[] | results[] |
items[].title | results[].document.title |
items[].link | results[].document.url |
items[].displayLink | results[].document.site, or the host of results[].document.url |
items[].snippet, htmlSnippet | No generated snippet. Show results[].document.description. results[].matchedTerms lists the words that matched, so you can mark them in the text. |
items[].pagemap | No equivalent. Add each value that you need, such as an image URL, as a field of the document. Each field comes back in results[].document. |
searchInformation.totalResults | searchContext.totalHits (a number, not a string) |
searchInformation.searchTime | took (milliseconds, not seconds) |
queries.nextPage | No equivalent. A next page exists when from + size is less than searchContext.totalHits and is not more than 500, the maximum from. |
spelling.correctedQuery | No equivalent. When a query finds no document, Relevan tries a less strict query, which allows typos in a short query. searchContext.fallback is then present. |
| (none) | results[].explanation: why the result matched. searchContext.queryId: the id that the feedback request needs. |
Custom Search JSON API response, shortened:
{
"searchInformation": { "searchTime": 0.21, "totalResults": "42" },
"items": [
{
"title": "Reset your password - Example Docs",
"link": "https://docs.example.com/account/reset-password",
"displayLink": "docs.example.com",
"snippet": "To reset your password, open Settings and select ...",
"pagemap": { "metatags": [{ "og:image": "https://docs.example.com/og.png" }] }
}
]
}Relevan response, shortened. It comes from a test index of the 17 pages of docs.relevan.dev, for the query send click feedback:
{
"results": [
{
"id": "<the hash of the URL>",
"score": 2.335301,
"document": {
"url": "https://docs.relevan.dev/guides/get-your-data-in",
"body": "Get your data in This guide takes you from a new organization to your first sear ...",
"lang": "en",
"site": "docs.relevan.dev",
"title": "Get your data in",
"section": "guides",
"description": "Search that understands your customers"
},
"explanation": "Matched: \"send\", \"sent\", \"feedback\", \"click\", \"clicks\" in body (2.34). Total score: 2.335",
"matchedFields": ["body"],
"matchedTerms": ["send", "sent", "feedback", "click", "clicks"]
}
],
"searchContext": {
"queryUsed": "send click feedback",
"totalHits": 12,
"matchedTerms": ["send", "sent", "feedback", "click", "clicks", "end"],
"topContributingFields": ["body"],
"titleField": "title",
"scoringSummary": "Highest retrieval score 2.335. Matched: \"send\", \"sent\", \"feedback\", \"click\", \"clicks\" in body (2.34). Total score: 2.335",
"suggestions": "All query terms contributed to at least one match. Fields searched: [body, description, title].",
"searchableFields": ["body", "description", "title"],
"sessionId": "9b4b1308-7748-48f0-b50d-1bbffe18a7eb",
"queryId": "Root=1-6b05b1d2-122e85424fe0c7a37c665eda"
},
"took": 191
}3. Send feedback
When a user clicks a result, send a click event from your server with the queryId of the search and the document id. Send feedback in the Getting started guide shows the request.
Cost
The Custom Search JSON API gives 100 queries a day free. Each further 1,000 queries cost $5, up to 10,000 queries a day. Relevan sells monthly plans with a fixed number of searches.
| Searches a month | Custom Search JSON API (estimate) | Relevan plan |
|---|---|---|
| 3,000 | $0 | Free: $0, 10,000 searches |
| 10,000 | $34.95 | Free: $0, 10,000 searches |
| 50,000 | $235 | Hobby: $20, 50,000 searches |
| 250,000 | $1,234.95 | Small Business: $79, 250,000 searches |
| 1,000,000 | Not possible (10,000 a day limit) | Growth: $299, 1,000,000 searches |
The Custom Search JSON API column assumes the same number of queries each day of a 30-day month. For example, 50,000 searches are about 1,667 a day. 100 of them are free, so 1,567 a day are billed: 47,000 in the month, at $5 for each 1,000.
Each Relevan plan also limits the storage of your documents: 100 MiB on Free, 300 MiB on Hobby, 1 GiB on Small Business, and 2 GiB on Growth. A plan has no overage charge. When an organization uses all the searches of its plan, a search gets 402 until the first day of the next month (UTC). See pricing for each plan.
Prices are as of November 2026. Check Google’s overview page for the current Custom Search JSON API terms.
Questions
Email hello@relevan.dev with the questions about your migration.