Google Custom Search Engine and Google Site Search In 30 Seconds

23
Nov
2009

Google Custom Search Engine and Google Site Search In 30 Seconds

A project I’ve been working on recently required a search feature. After a quick look around I thought I’d give a hosted solution a try – using Google Site Search. After almost a full day of banging my head against the wall – here’s what I discovered… I) The only difference between Site Search and Google Custom Search – is that you pay for Site Search and you get on-demand indexing – so you’re guaranteed (in theory) to have all of the pages in your site indexed. II) Once you’ve paid for Site Search – the control panel is effectively the Custom Search Engine Search control panel – with the on-demand option present. III) There are three ‘levels’ of control you have over the results on your site. Here’s a quick tour of each – assuming you’ve read just enough of the docs

(Here’s a link to the Google AJAX Search API) to know that you need to link to the jsapi JavaScript library – load the search api via: google.load('search', '1'); and then declare your OnLoad function .Note – for all three options it’s a good idea to have the following style sheet at the top of all your test pages – since you get some ‘freebie’ and fast styling as a result. http://www.google.com/cse/style/look/default.css

1) google.search.CustomSearchControl – with just two lines of code – you can have a custom search page up and running (well not quite two lines – but these are the most important two).

var customSearchControl = new google.search.CustomSearchControl('013652945859801643433:fdsfsqjnea4');
customSearchControl.draw('targetDiv');

The parameter to the CustomSearchControl is the CSE id for the custom search engine you’ve created – and calling ‘draw’ will render the completed form and search results area to the page. The CustomSearch control has a built in ‘searcher’ based on the settings from your CSE control panel. CustomSearchControl is however a little difficult to customize. I found it hard to turn off the default ‘search’ form and place the results where I wanted them. You can add additional searchers – like images and video search via:

customSearchControl.addSearcher(new google.search.ImageSearch(), options);

The main point to note here – is that CustomSearchControl is ‘driven’ by the CSE control panel – including filter options, look and feel etc. all based on the search engine unique ID that you’ll also find in the CSE control panel. This is custom search with training-wheels on.  

2) google.search.SearchControl – is the next level down in abstraction – and here’s the ‘Hello World’ example from the docs. With SearchControl – you have to add searchers to the control and then you can tell the control to ‘draw’ itself – just like with the CustomSearchControl. However it’s a little easier to customize. For example:

this.control = new google.search.SearchControl();
// set up for CSE result sets
this.control.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
 
// configure search control
var options = new google.search.SearcherOptions();
options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
options.setRoot(resultsDiv)
 
var searcher = new google.search.WebSearch();
searcher.setSiteRestriction("01365294584480dsadad3:ffsfsfseqjnea4");
searcher.setUserDefinedLabel("Search Results");
searcher.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
 
this.control.addSearcher(searcher, options);
 
this.control.draw();

Note the options.setRoot(resultsDiv) highlighted line. This does two things – 1) It sends the output of the search to the ‘resultsDiv’ and 2) it turns off the submit form – which means you can now control the input to search – from your own form – placed anywhere on the page as long as you handle the OnSubmit event and call this.control.execute(‘formInputValue’); Again if you link to http://www.google.com/cse/style/look/default.css – you’ll get some instant results that look ok.  

3) google.search.Search – is the lowest level abstraction – the raw searcher class – and although you still get some good stuff here, you will have to take care of rendering the results to the page. In this case you will need to handle the input and output for every class of searcher you use – Web, Local, Image or Video – all of which are derived from google.search.Search. For example…

// Our searcher instance.
var searcher = new google.search.WebSearch();
 
searcher.setSiteRestriction("013652945859801616623:ecbgsqjnea4");
searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searcher.setUserDefinedLabel("QCC Search Results");
searcher.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searcher.setSearchCompleteCallback(this, searchComplete, null);
 
var searchForm = document.getElementById("search");
if (searchForm.q.value) {
    searcher.execute(searchForm.q.value);
}

Here's a link to a complete example of a raw search with output being handled by the developer (which is in another area of the Google docs – the Code Playground). While there’s more plumbing required here – you’re still off to a good start. Unlike the sample above for raw handling of the results – you can use the .html property of the result object in the results array – which will tie up again nicely with the linked style sheet - and you’ll have a ‘Goggle-like’ – good-to-go search experience in your site. Like this…

function searchComplete() {
    // Check that we got results
    if (searcher.results && searcher.results.length > 0) {
        // Grab our content div, clear it.
        var resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = '';
        // Loop through our results, printing them to the page.
        var results = searcher.results;
        for (var i = 0; i < results.length; i++) {
            // For each result write it's title and image to the screen
            var result = results[i];
            resultsDiv.appendChild(result.html);
        }
 
        // Now add the paging links so the user can see more results.
        addPaginationLinks(searcher);
    }
}

And that's it. There is documentation available for all of this – but it’s in various locations. The first examples you will see if you come to search via the CSE control panel – will be the CustomSearchControl. The hard part was the ‘orientation’ exercise that I had to go through to understand what the heck I was using, where it fit in the bigger picture of the search API, and how I could create a more customized search experience. The docs are a bit all over the shop in this case – and so it took me nearly a day to write some POC tests and properly understand the relationship between google.search.CustomSearchControl, google.search.SearchControl and good.search.Search. Hope this post helps to reduce the pain for anyone else that’s new to Google Search and would like to implement a tailored search experience.

Category: 

Comments

hello, very usefull article for a beginner! As you have wrote.. "There is documentation available for all of this – but it’s in various locations." google docs confused me, isn't clean and doesn't immediatly center my goals :) i'm trying to write a search engine with google cse for personal usage and i'm going crazy :D ... my first idea was: "ok let's go to create it with cse...surely i will able to full customize the search results layout" ... i've found half solution to my issue by editing the css... but now i would customize the layout of results by adding some stuff on it (eg a share and a bookmark button/link near the resulted link). you have explained how get search results and print it in the 3th part of your article (the google.search.Search one) ... but i can't get it working ... i suppose that the best idea to solve my issues is..get all the results and compose and show it as i want! isn't it? can you give me a full example? (the entire example.html with html/and the js implementation of this search engine?) it should be simple for you..hope on it..and in your answer :) sorry for my poor english... feel free to mail me if u can/wants i very appreciate your work ;) bye

Hi Giuseppe There are some pretty good full examples in the documentation - just in various locations (I've included one link above to a full example of a raw search.Search approach). I will however update the post with a Zip file that can be downloaded with samples of just a Websearch - against a CSE - using the three main classes described above - hopefully within the next day or two.