Python GAQL Negative Keyword Script: Auto-Exclude Waste

Learn how to build a Python GAQL negative keyword script to auto-exclude zero-conversion multi-word queries, store logs in BigQuery, and prevent conflicts.

By AdTurbo Team · 2026-10-20

Search query hygiene is one of the most resource-intensive operational burdens in PPC management. While standard Google Ads in-browser scripts allow advertisers to perform rudimentary checks, enterprise accounts and high-volume lead generation funnels quickly hit hard limits. Native scripts time out after 30 minutes, struggle with large arrays of query data, and lack the advanced string manipulation needed to parse subtle n-gram patterns.

To proactively eliminate wasted ad spend, engineers and technical PPC practitioners are turning to external pipelines. By combining the Google Ads Query Language (GAQL), the Python Google Ads Client Library, and data warehouses like Google BigQuery, you can build an automated engine that monitors search queries, isolates multi-word zero-conversion outliers, and systematically pushes negative keyword exclusions without human intervention.

This guide covers the technical architecture, GAQL queries, n-gram evaluation logic, conflict detection safeguards, and a complete Python implementation designed to eliminate spend bleed on long-tail queries.

---

Why Native Google Ads Scripts Fail on Complex Multi-Word Queries

Google Ads Scripts operate within an execution sandbox hosted inside the Google Ads infrastructure. While convenient for basic tasks, their limitations become apparent when dealing with deep search term optimization across multi-campaign accounts.

Execution Limits and Quotas

In-app Google Ads Scripts carry a strict execution ceiling:

• 30-Minute Timeout: Scripts automatically abort after 30 minutes. If your account processes tens of thousands of search terms per week, calculating aggregate n-gram statistics, tokenizing terms, and querying multiple levels of performance will trigger execution timeouts.

• Memory Constraints: JavaScript objects in Ads Scripts are severely memory-capped, making multi-dimensional array operations (such as tokenizing strings into bi-grams and tri-grams across 100,000 search terms) prone to silent failures or memory limit crashes.

• API Quota Restrictions: In-browser scripts share internal throttling boundaries, making it difficult to pipe historical conversion metrics into external analytics environments for sophisticated regression modeling.

The N-Gram and Long-Tail Blind Spot

A critical issue in automated budget waste is the long-tail search query. Individual long-tail queries (often 4 to 8 words long) rarely generate enough individual spend to cross traditional automated script thresholds (e.g., spend $50 with 0 conversions). Instead, 500 unique variants of an irrelevant long-tail search might each spend $3, collectively siphoning $1,500 per month undetected.

Native scripts struggle to perform iterative string tokenization across thousands of rows to recognize that a specific multi-word phrase—such as "free download pdf" or "how to do it yourself without paying"—is repeatedly appearing across these dispersed queries. Overcoming this requires an external computing layer using Python and GAQL to execute comprehensive analysis before applying exclusions.

| Capability | Native In-Platform Ads Scripts | External Python + GAQL Script |

| :--- | :--- | :--- |

| Execution Timeout | 30 minutes hard limit | Unlimited (runs on VM, Cloud Run, Lambda) |

| Data Capacity | Low (browser-level memory allocation) | High (handles millions of rows via streaming) |

| Data Storage | Google Sheets or script properties | Google BigQuery, PostgreSQL, S3 |

| Tokenization & N-Grams | Slow, prone to call-stack overflow | Highly efficient via Python (collections, nltk) |

| Conflict Safeguards | Basic keyword match checks | Cross-checks exact, phrase, and historic winners |

For teams managing complex accounts without the technical capacity to run custom infrastructure, exploring full-cycle google ads automation provides a turnkey way to handle algorithmic bid and keyword adjustments.

---

Understanding GAQL and Search Query Metric Extraction

The Google Ads API relies on GAQL (Google Ads Query Language), an SQL-like declarative language used to pull performance entities and metrics. When building a script to isolate multi-word zero-conversion queries, the core resource is the searchtermview.

The Anatomy of searchtermview

The searchtermview resource represents historical search terms that triggered your ads, provided they cleared Google's privacy thresholds. Unlike the keywordview, which reports metrics aggregated at your targeted keyword level, searchtermview reveals the actual user intent.

To construct an automated pruning workflow, your GAQL query must pull query text along with performance metrics (clicks, impressions, cost, conversions) and structural metadata (campaign ID, ad group ID, match type).

sql

SELECT

campaign.id,

campaign.name,

adgroup.id,

adgroup.name,

searchtermview.searchterm,

searchtermview.status,

metrics.clicks,

metrics.impressions,

metrics.costmicros,

metrics.conversions,

metrics.conversionsvalue,

segments.date

FROM searchtermview

WHERE segments.date DURING LAST30DAYS

AND metrics.clicks 2

AND campaign.status = 'ENABLED'

AND adgroup.status = 'ENABLED'

ORDER BY metrics.costmicros DESC

GAQL Field Nuances and Pitfalls

When working with GAQL, keep these nuances in mind:

1. metrics.costmicros Conversion: Cost is always returned in micros (millionths of the account currency). A return value of 15000000 equates to $15.00. Failing to divide by 1,000,000 inside your Python evaluation logic will distort cost calculations.

2. searchtermview.status: This returns values like ADDED, EXCLUDED, or NONE. You should generally filter for queries where status = 'NONE' so your script does not waste compute cycles checking queries that have already been converted to targeted keywords or blocked as negatives.

3. Privacy Masking: Google restricts reporting on low-volume search queries. Queries that do not meet privacy thresholds will not appear in searchtermview, even though their cumulative cost is included at the campaign and ad group summary levels. For a deeper breakdown of how to identify spend discrepancies in these logs, read our search terms report guide.

---

Architectural Setup: Google Ads API, Python Client, and BigQuery

To automate negative keywords with BigQuery and GAQL, you need a decoupled architecture that executes queries, processes logic in Python, commits audit trails to BigQuery, and pushes mutations back to Google Ads.

[Google Ads API]

│ (1) GAQL Search Query Stream

▼

[Python Execution Environment (Cloud Run / Local CLI)]

│

├─► (2) N-Gram & Threshold Engine (Identifies Waste)

│

├─► (3) BigQuery Data Warehouse (Audit Logs & Historical Tracking)

│

▼ (4) Negative Keyword Mutate Operation

[Google Ads API]

Prerequisites and Authentication

Before running the script, ensure you have:

1. A Google Cloud Platform (GCP) project with the Google Ads API and BigQuery API enabled.

2. A Google Ads Developer Token (Basic or Standard access).

3. OAuth 2.0 Client ID and Secret credentials authorized via your Google Ads manager (MCC) or individual account.

4. A google-ads.yaml configuration file placed in your execution root directory or specified via an environment variable.

yaml

developertoken: "YOURDEVTOKEN"

clientid: "YOURCLIENTID.apps.googleusercontent.com"

clientsecret: "YOURCLIENTSECRET"

refreshtoken: "YOURREFRESHTOKEN"

logincustomerid: "YOURMCCCUSTOMERIDNODASHES"

useprotoplus: true

Setting Up BigQuery for Historical Auditing

Writing negative exclusions without an immutable audit trail is risky. If a script makes an overly broad exclusion, your account can lose significant traffic overnight. By routing exclusions through Google BigQuery before mutations execute, you maintain historical accountability.

Create a BigQuery dataset named adnegativeautomations with an exclusion log table:

sql

CREATE TABLE yourproject.adnegativeautomations.exclusionlog (

executiontimestamp TIMESTAMP,

customerid STRING,

campaignid INT64,

adgroupid INT64,

searchterm STRING,

exclusiontype STRING,

matchtype STRING,

clicks INT64,

cost FLOAT64,

conversions FLOAT64,

exclusionreason STRING

);

With storage configured, review how to find negative keywords to confirm your operational criteria align with your strategic business goals.

---

Developing the Python GAQL Negative Keyword Script (Step-by-Step)

Below is a modular, production-ready Python script that fetches search queries, evaluates zero-conversion multi-word thresholds, cross-references against positive keywords, and adds negatives.

Step 1: Environment Setup

Install the necessary dependencies in your virtual environment:

bash

pip install google-ads google-cloud-bigquery pydantic

Step 2: The Core Python Script

Save the following script as autoexcludewaste.py. It establishes the API client, streams data via GAQL, computes string tokens, and executes the negative mutation.

python

import sys

from datetime import datetime

from google.ads.googleads.client import GoogleAdsClient

from google.ads.googleads.errors import GoogleAdsException

from google.cloud import bigquery

CONFIGURATION PARAMETERS

CUSTOMERID = "1234567890" Replace with target 10-digit ID

MINWORDS = 3 Only target queries with = 3 words

MINSPENDTHRESHOLD = 35.0 Spend threshold with zero conversions

LOOKBACKDAYS = 30

DRYRUN = True Set to False to apply live mutations

def fetchsearchterms(client, customerid: str):

"""Fetches search terms with zero conversions above cost thresholds."""

gaservice = client.getservice("GoogleAdsService")

query = f"""

SELECT

campaign.id,

campaign.name,

adgroup.id,

adgroup.name,

searchtermview.searchterm,

metrics.clicks,

metrics.costmicros,

metrics.conversions

FROM searchtermview

WHERE segments.date DURING LAST{LOOKBACKDAYS}DAYS

AND metrics.conversions = 0

AND campaign.status = 'ENABLED'

AND adgroup.status = 'ENABLED'

"""

searchrequest = client.gettype("SearchGoogleAdsStreamRequest")

searchrequest.customerid = customerid

searchrequest.query = query

stream = gaservice.searchstream(searchrequest)

candidates = []

for batch in stream:

for row in batch.results:

cost = row.metrics.costmicros / 1000000.0

term = row.searchtermview.searchterm.strip()

wordcount = len(term.split())

if wordcount = MINWORDS and cost = MINSPENDTHRESHOLD:

candidates.append({

"campaignid": row.campaign.id,

"campaignname": row.campaign.name,

"adgroupid": row.adgroup.id,

"adgroupname": row.adgroup.name,

"searchterm": term,

"clicks": row.metrics.clicks,

"cost": cost,

"conversions": row.metrics.conversions

})

return candidates

def applynegativekeywords(client, customerid: str, candidates: list):

"""Pushes excluded queries as Exact negatives to the specific Ad Group."""

if not candidates:

print("No candidates identified for exclusion.")

return

adgroupcriterionservice = client.getservice("AdGroupCriterionService")

operations = []

for item in candidates:

operation = client.gettype("AdGroupCriterionOperation")

criterion = operation.create

criterion.adgroup = client.getservice("AdGroupService").adgrouppath(

customerid, item["adgroupid"]

)

criterion.negative = True

criterion.keyword.text = item["searchterm"]

criterion.keyword.matchtype = client.enums.KeywordMatchTypeEnum.EXACT

operations.append(operation)

if DRYRUN:

print(f"[DRY RUN] Would have added {len(operations)} negative keywords.")

for item in candidates:

print(f" - AdGroup {item['adgroupid']}: '{item['searchterm']}' (Cost: ${item['cost']:.2f})")

return

try:

response = adgroupcriterionservice.mutateadgroupcriteria(

customerid=customerid,

operations=operations

)

print(f"Successfully applied {len(response.results)} negative criteria.")

except GoogleAdsException as ex:

print(f"Google Ads Failure: {ex.error.message}")

for err in ex.failure.errors:

print(f" Error: {err.message}")

def main():

client = GoogleAdsClient.loadfromstorage()

print(f"Fetching zero-conversion long-tail queries for account {CUSTOMERID}...")

candidates = fetchsearchterms(client, CUSTOMERID)

print(f"Found {len(candidates)} queries meeting exclusion criteria.")

applynegativekeywords(client, CUSTOMERID, candidates)

if name == "main":

main()

This script focuses on high-confidence, non-converting queries by pulling long-tail terms (= 3 words) with zero conversions that have exceeded your target spend threshold.

---

How to Auto Exclude Zero Conversion Long Tail Queries Safely

Automating keyword exclusions without adequate safeguards can inadvertently block valuable conversion paths. When configuring your script to auto-exclude zero-conversion long-tail queries, implement strict filtering logic before mutating criteria.

1. Match Type Selection for Exclusions

When excluding multi-word terms, your match type strategy is critical:

• Exact Match Exclusions ([query]): The safest automated exclusion method. If a user queries "cheap industrial air compressor manual pdf", adding it as an exact negative prevents spend on that exact search string without blocking queries like "cheap industrial air compressor".

• Phrase Match Exclusions ("phrase"): Useful for n-gram phrases (e.g., "free download"), but risky when applied to full search terms. If an automated script adds a 5-word query as a Phrase match negative, it may inadvertently block high-intent variations containing the same word sequence.

For most automated scripts, Exact match exclusions are the recommended approach for full queries. For broad n-gram lists, consult curated negative keywords examples and apply them via account-level shared lists rather than ad group-level mutations.

2. Multi-Attribution and Conversion Lag Safeguards

Never evaluate search queries within a 72-hour window of the current date. Conversion reporting lag—particularly for lead generation or considered B2B purchases—can take several days to finalize.

If a user clicks an ad on Monday and converts on Thursday, running a daily script that evaluates performance through Tuesday will register that Monday query as having zero conversions. Always configure your GAQL queries to exclude recent days using date segment boundaries:

sql

WHERE segments.date BETWEEN '2026-02-01' AND '2026-02-25'

3. Account-Level Historical Whitelists

Before flagging any query for negative exclusion, verify that the string has never converted historically. A query might have spent $40 with zero conversions over the last 30 days, but generated five high-value conversions during the previous quarter.

Use BigQuery to cross-reference search terms against lifetime performance records before confirming an exclusion:

python

def ishistoricalconverter(bqclient, searchterm: str) - bool:

query = f"""

SELECT SUM(conversions) as totalconversions

FROM yourproject.adnegativeautomations.lifetimesearchterms

WHERE searchterm = @term

"""

jobconfig = bigquery.QueryJobConfig(

queryparameters=[bigquery.ScalarQueryParameter("term", "STRING", searchterm)]

)

result = bqclient.query(query, jobconfig=jobconfig).result()

for row in result:

if row.totalconversions and row.totalconversions 0:

return True

return False

---

Handling Negative Keyword Conflicts and Shared Lists via API

One of the most disruptive errors in Google Ads management is a negative keyword conflict—where an automated negative exclusion prevents a targeted, high-performing keyword from serving. Native Ads Scripts offer basic conflict checkers, but the Google Ads API allows you to validate candidate exclusions against your active keyword inventory in real time.

Detecting Conflicts Programmatically

Before submitting a mutation, query the adgroupcriterion resource to confirm that your proposed negative does not match an existing enabled keyword within that same ad group or campaign.

python

def checkforconflict(client, customerid: str, campaignid: int, negativetext: str) - bool:

gaservice = client.getservice("GoogleAdsService")

Check active keywords in the campaign

query = f"""

SELECT

adgroupcriterion.keyword.text,

adgroupcriterion.keyword.matchtype

FROM adgroupcriterion

WHERE campaign.id = {campaignid}

AND adgroupcriterion.status = 'ENABLED'

AND adgroupcriterion.negative = FALSE

"""

response = gaservice.search(customerid=customerid, query=query)

for row in response:

activekw = row.adgroupcriterion.keyword.text.lower().strip()

Direct conflict on exact matches

if activekw == negativetext.lower().strip():

return True

return False

Campaign vs. Shared Negative Lists

Applying negative keywords at scale requires choosing the right organizational level:

1. Ad Group Criteria (AdGroupCriterion): Use this for precise query pruning. If a search term is relevant to Ad Group B but bled spend in Ad Group A, apply it as an exact negative exclusively in Ad Group A.

2. Shared Negative Lists (SharedCriterion): Use this for universally irrelevant root tokens (e.g., "torrent", "cracked", "internship"). Your Python pipeline can append these broad tokens to a centralized shared library list attached across all campaigns.

python

def addtosharednegativelist(client, customerid: str, sharedsetid: str, negativeterm: str):

sharedcriterionservice = client.getservice("SharedCriterionService")

operation = client.gettype("SharedCriterionOperation")

criterion = operation.create

criterion.sharedset = client.getservice("SharedSetService").sharedsetpath(customerid, sharedsetid)

criterion.keyword.text = negativeterm

criterion.keyword.matchtype = client.enums.KeywordMatchTypeEnum.BROAD

sharedcriterionservice.mutatesharedcriteria(customerid=customerid, operations=[operation])

Regularly reviewing negative lists alongside a structured PPC audit checklist helps ensure your shared lists do not accumulate unintended traffic blocks.

---

Production Deployment: Automating with BigQuery, Cron, or Cloud Functions

Running scripts locally on an ad-hoc basis limits their value. To fully automate negative keywords with BigQuery and GAQL, deploy your Python workflow to run on a set schedule in the cloud.

Deployment Architectures

Three primary methods exist for scheduling this script:

1. Google Cloud Run Jobs: The ideal serverless approach for multi-account processing. Package your Python script into a Docker container, configure the necessary IAM permissions, and invoke it on a weekly or daily schedule using Google Cloud Scheduler.

2. Google Cloud Functions: Well-suited for single-account execution routines that finish within the standard 9-minute execution window.

3. Scheduled VM with Cron: A straightforward Linux VM (Compute Engine instance) running a systemd timer or crontab schedule.

bash

Example Crontab entry: Runs every Monday at 03:00 UTC

0 3 1 /usr/bin/python3 /opt/googleadsscripts/autoexcludewaste.py /var/log/adexclusions.log 2&1

Automated BigQuery Logging Pipeline

Whenever the script processes an exclusion, write the payload directly to BigQuery for record-keeping. This provides a clear audit trail if an exclusion ever needs to be reviewed or reversed.

python

def logexclusionstobigquery(bqclient, records: list):

if not records:

return

tableid = "yourproject.adnegativeautomations.exclusionlog"

rowstoinsert = []

now = datetime.utcnow().isoformat()

for item in records:

rowstoinsert.append({

"executiontimestamp": now,

"customerid": CUSTOMERID,

"campaignid": item["campaignid"],

"adgroupid": item["adgroupid"],

"searchterm": item["searchterm"],

"exclusiontype": "ADGROUPEXACT",

"matchtype": "EXACT",

"clicks": item["clicks"],

"cost": item["cost"],

"conversions": item["conversions"],

"exclusionreason": f"Spend ${MINSPENDTHRESHOLD} with zero conversions"

})

errors = bqclient.insertrowsjson(tableid, rowstoinsert)

if errors:

print(f"BigQuery ingestion errors encountered: {errors}")

else:

print(f"Logged {len(rowstoinsert)} exclusions to BigQuery.")

Advanced: Autonomous Optimization Alternative

While custom Python pipelines offer deep control, maintaining custom API infrastructure, handling Google Ads API version deprecations, and managing OAuth refreshes requires ongoing engineering support.

For teams that want automated negative keyword management without custom code, dedicated solutions like AdTurbo provide automated search term analysis, keyword pruning, and conflict detection out of the box—monitoring your accounts continuously to eliminate wasted spend before it accumulates.

---

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• How to Find Negative Keywords in Google Ads (Step by Step)

• Negative Keywords: 100+ Examples and Lists for Google Ads

---

Frequently Asked Questions

Can this Python script automatically remove broad match keywords?

No, the script is configured to evaluate search terms from the search terms report and add non-converting multi-word queries as exact match negative criteria. It does not pause or remove the underlying keywords you are deliberately bidding on in your campaigns.

How often should an automated negative keyword script run?

Running the script weekly or bi-weekly is ideal for most accounts. Running it daily can lead to premature exclusions caused by conversion reporting lag, while running it less than once a month allows non-converting queries to consume excess budget unchecked.

What happens if the Google Ads API updates its version?

Google deprecates API versions roughly once per year. When an API version is phased out, you must update the google-ads package in your Python environment and verify that all GAQL fields in your script remain valid under the newest API version schema.