Sunday, May 6, 2012

Creating Google-like instant search using Solr and JQuery

We have a company database with over 8 million records indexed in to Solr. Having used Solr before I was aware of the speed with which it could do queries even with such large datasets.

I built a simple Search Interface in to our company database by indexing the data in Solr and using javascript.


1:  <style>  
2:  .loc {  
3:       color:gray;  
4:       font-style:italic;  
5:       font-size:11px;  
6:  }  
7:  </style>  
8:  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>  
9:  <script type='text/javascript'>  
10:  $(document).ready(function() {  
11:    // put all your jQuery goodness in here.  
12:    $('#searchbox').bind('keyup', function(e){  
13:     if($("#token").val().length > 0) {  
14:          getresults($('<div/>').text($("#token").val()).html());  
15:     }  
16:    });  
17:  });  
18:  function getresults(token){  
19:       var finalhtml="";  
20:       $.getJSON("http://10.10.10.12:8983/solr/db/select?rows=100&fl=companyname,id,city,state,score&wt=json&json.wrf=?&indent=true&q=" + token, function(result){  
21:       for (var i = 0; i < result.response.docs.length; i++) {  
22:            var thisResult = "<b>" + result.response.docs[i].companyname + "</b>"  
23:            + "<span class=\"loc\">&nbsp;("   
24:            + result.response.docs[i].city + ",&nbsp;"   
25:            + result.response.docs[i].state + ")</span>"  
26:            + "<br>" + result.response.docs[i].id  
27:            + "<br>";  
28:            finalhtml += thisResult;  
29:       }  
30:       $('#rs').html(finalhtml);  
31:       });  
32:  }  
33:  </script>  
34:  <div id="searchbox">  
35:       <input type="text" id="token"></input>  
36:  </div>  
37:  <div id="rs">Nothing to search.....</div>  


The end result is a no-frill search text box that updates the page as you type. This is because I bind the keyup event to a call to Solr. Voila! You'r own version of Google Instant Search!



No comments:

Post a Comment