Click here to Skip to main content
Licence 
First Posted 27 Dec 2004
Views 214,536
Downloads 2,303
Bookmarked 204 times

Google Suggest like Dictionary

By Gavi Narra | 27 Dec 2004
An implementation of Google suggest using remote scripting.
3 votes, 3.9%
1
2 votes, 2.6%
2
6 votes, 7.9%
3
8 votes, 10.5%
4
57 votes, 75.0%
5
4.77/5 - 77 votes
5 removed
μ 4.61, σa 1.80 [?]

Dictionary

Introduction

This is an implementation of Google Suggest like dictionary in ASP.NET.

Background

After seeing Google Suggest, I was amazed and wanted to know how it worked. This project is just an experiment using the same technique that Google uses.

Using the code

The ZIP file consists of two files. One is an HTML file that uses the XMLHttpRequest object to make requests and get back data. The other one is a server script implemented in ASP.NET that connects to a SQL Server database. If you wish to implement a similar interface, just use the HTML functions provided. A proof of concept website could be accessed here.

How does it work?

The architecture could be explained as outlined below:

  • Concept
  • The database
  • ASP.NET page
  • XMLHttpRequest object in the HTML page
  • Observations

Concept

As you type a word in the textbox, a JavaScript event fires an HTTP GET request to the ASPX page. The response from the ASPX page is simply displayed in a div tag under the textbox. The page is not refreshed/reloaded for every keystroke as everything is done by the JavaScript in the page. The main JavaScript object that allows us to do this is XMLHttpRequest. You could read about it from Apple's developer site here. This is supported by IE 5.0 +, Mozilla 1.0 + and Apple's own Safari 1.2 +.

Database

The database contains just one table. The data comes from a freely available online dictionary (a public domain English word list dictionary, based on the public domain portion of "The Project Gutenberg Etext of Webster's Unabridged Dictionary" which is in turn based on the 1913 US Webster's Unabridged Dictionary. You could download it from here). The table is called WordList:

WordList
Word varchar(255)
Type varchar (10)
Meaning text

I created an index on "Word" column for speed. There are a total of 182696 words in the database.

ASP.NET page

The ASP.NET page is pretty straight forward. Gets the top 10 matching rows from the database and spits it out. Below is the code I am using (although SqlDataReader might be more appropriate):

<%@Page Language="C#"%>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.SqlClient"%>
<%@Import Namespace="System.Configuration"%>

<script runat="server">

    public void Page_Load(object sender,EventArgs args)
    {
        string keyword=Request["k"];
        if(keyword!=null  && keyword.Trim()!="")
        {
            string sql="select top 10* from WordList where" + 
                   " word like '"+keyword.Trim().Replace("'","''")+"%'";
            SqlConnection conn=new 
               SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
            conn.Open();
            DataTable dt=new DataTable();
            SqlCommand command=new SqlCommand(sql,conn);
            SqlDataAdapter adapter=new SqlDataAdapter(command);
            adapter.Fill(dt);
            conn.Close();

            foreach(DataRow row in dt.Rows)
            {
                string meaning=row["Meaning"].ToString();
                Response.Write("<strong>"+row["Word"].ToString()+"</strong> <i>");
                  Response.Write("row["Type"].ToString()+"</i>: "+meaning+"<br>");
            }
        }


    }

</script>

XMLHttpRequest object in the HTML page

<html>
    <head>
        <script>
var req;

function Initialize()
{
    try
    {
        req=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            req=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            req=null;
        }
    }

    if(!req&&typeof XMLHttpRequest!="undefined")
    {
        req=new XMLHttpRequest();
    }

}

function SendQuery(key)
{
    Initialize();
    var url="http://www.objectgraph.com/dictionary/dict.aspx?k="+key;

    if(req!=null)
    {
        req.onreadystatechange = Process;
        req.open("GET", url, true);
        req.send(null);

    }

}

function Process()
{
    if (req.readyState == 4)
        {
        // only if "OK"
            if (req.status == 200)
            {
                if(req.responseText=="")
                    HideDiv("autocomplete");
                else
                {
                    ShowDiv("autocomplete");
                    document.getElementById("autocomplete").innerHTML = 
                                                      req.responseText;
                }
            }
            else
            {
                document.getElementById("autocomplete").innerHTML=
                    "There was a problem retrieving data:<br>" 
                    + req.statusText;
            }
        }
}

function ShowDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="show";
   else document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="hide";
   else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
    HideDiv("autocomplete");
    document.form1.keyword.focus();

}
</script>
    </head>
    <body onload="BodyLoad();">
        <form name="form1">
        <input name="keyword" onKeyUp="SendQuery(this.value)" 
          style="WIDTH:500px" autocomplete="off">
            <div align="left" class="box" id="autocomplete" 
              style="WIDTH:500px;BACKGROUND-COLOR:#ccccff"></div>
        </form>

    </body>
</html>

The KeyUp event on the textbox triggers the SendQuery method. Note that we are disabling the auto-complete feature so it does not overlap with our div tag. The Initialize method creates the XMLHttpRequest object. In Mozilla and Safari, you could simply do this by using:

req=new XMLHttpRequest();

In IE, you could create the object based on the user's installation of MSXML libraries. The Process method acts as an event handler and displays the response text once the response is complete from the web server.

Observations

  • Google Suggest is probably running by having all the suggestion words in main memory and a custom web server that does nothing else (although this concept is very easy to implement in C#).
  • Roundtrips from the web server should be minimal (2K max) as it might eat up bandwidth pretty fast.

History

  • December 24, 2004
    • Initial version 1.0.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Gavi Narra

Web Developer

United States United States

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalword dictionary Pinmembermohit1119:16 8 Sep '10  
GeneralSo simple yet so powerful,,, Pinmembersevenlogix6:23 22 May '09  
GeneralGoogle Suggest like Dictionary Pinmemberluckyroy21:38 3 May '09  
GeneralQuery Modification PinmemberMember 450581213:29 16 Dec '08  
GeneralProblem in "document.getElementById("autocomplete").innerHTML=req.responseText;" PinmemberMember #31656654:01 10 Jan '07  
Questionselectable values in div tag Pinmemberutsi3:04 12 Oct '06  
Questionget it working with access database??? Pinmemberwahabm1:13 8 Aug '06  
Questionhow to display in listbox... Pinmemberkamalika_kk3:36 10 Jul '06  
GeneralPlease I need the database of this program PinmemberAMRSINAN0:38 13 Jun '06  
Generaldatabase link died Pinmembermasterbkhn8:53 27 Apr '06  
GeneralRe: database link died Pinmemberpiglet0117:09 23 Sep '07  
GeneralAJAX creating problem on Local Site Pinmembereshna21:41 16 Mar '06  
GeneralRe: AJAX creating problem on Local Site Pinmembertejas_chonkar23:21 23 Apr '06  
GeneralW2003K web server permissions PinmemberLeighG2:28 12 Feb '06  
NewsConverted code in vb.net Pinmembersuri197122:25 30 Jan '06  
NewsCode in Vb.net Pinmembersuri197121:59 30 Jan '06  
GeneralSorting a SubString Search PinmemberFabito3:14 24 Nov '05  
QuestionCode behind does not work? Pinmemberpeterver10:40 16 Nov '05  
GeneralStatus 12029 when running code from client PinsussWegas10:24 29 Sep '05  
GeneralRe: Status 12029 when running code from client PinmemberMitchV10:22 14 Feb '06  
Generalproblem implementing in vb.net Pinmembersaggimanoj1:41 23 Sep '05  
I tried the same code to implement in vb.net using different table. I can't say whether it works with word database or not, but definitely id didn't worked with my database. I am giving the server side code here.
 
The html page seems to working fine, as I tried the same html page by changing the URL to objectworks site. The output was displayed correctly. I am sure that there is something missing in server side code.
 
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim keyword As String = Request("k").ToString()
If Not keyword Is Nothing And keyword.Trim() <> "" Then
Dim sql As String = "select Name from Table1 where" & " Name like '" & keyword.Replace("'", "''") & "%'"
Dim conn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
conn.Open()
Dim ds As DataSet = New DataSet
Dim command As SqlCommand = New SqlCommand(sql, conn)
Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
adapter.Fill(ds)
conn.Close()
For Each row As DataRow In ds.Tables(0).Rows
Dim meaning As String = ds.Tables(0).Rows.Item(0).ToString()
Response.ContentType = "text/html"
Response.Write("'" & ds.Tables(0).Rows.Item(0).ToString() & "'
")
Next row
End If
End Sub
 
Pleae tell me if I m wrong somewhere as it is very important for me to impelement this thing today. Any comments shall be highly appreciated by me. Looking forward to members help.
GeneralIts really nice article..great job PinmemberSurendra Sambana20:16 4 Sep '05  
QuestionHow to Change Source From Your Site Pinmembereebb224423:01 21 Aug '05  
GeneralMining Google Web Services: Building Applications with the Google API PinsussAnonymous21:48 21 Aug '05  
GeneralGoogle Hacks: 100 Industrial-Strength Tips & Tools PinsussAnonymous3:53 14 Aug '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120210.1 | Last Updated 27 Dec 2004
Article Copyright 2004 by Gavi Narra
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid