Permute a Query

Run all permutations of query keywords and phrases to squeeze the last drop of results from the Google index.

Google, ah, Google. Search engine of over eight billion pages and zillions of possible results. If you’re a search engine geek like I am, few things are more entertaining than trying various tweaks with your Google search to see what exactly makes a difference to the results.

It’s amazing what makes a difference. For example, you wouldn’t think that word order would make much of an impact, but it does. In fact, buried in Google’s documentation is the admission that the word order of a query will impact search results.

While that’s an interesting thought, who has time to generate and run every possible iteration of a multiword query? Google API to the rescue! This hack takes a query of up to four keywords or “quoted phrases” (as well as supporting special syntaxes) and runs all possible permutations, showing result counts by permutation and the top results for each permutation.

The Code

Save the following code as a CGI script ["How to Run the Hacks” in the Preface] named order_matters.cgi in your web site’s cgi-bin directory. As you type in the script, be sure to replace insert key here with your Google API key.

Tip

You’ll need to have the Algorithm::Permute Perl module for this program to work correctly (http://search.cpan.org/search?query=algorithm%3A%3Apermute&mode=all).

#!/usr/local/bin/perl # order_matters.cgi # Queries Google for every possible permutation ...

Get Google Hacks, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.