Click here to Skip to main content
Click here to Skip to main content

Google Suggest like Dictionary

By , 26 Dec 2004
 

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
No Biography provided

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.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberFarhan Ghumra11 Jul '12 - 21:23 
you should upload fully worked sample
Generalword dictionarymembermohit118 Sep '10 - 18:16 
my question is from gavi i want to know how to add word dictionary database in my sql server data base og google search ,your code is not giving knowlege about this i am developing c#.net application
GeneralSo simple yet so powerful,,,membersevenlogix22 May '09 - 5:23 
I've seen many implementations of Google Suggest that are way too complex and difficult to implement. The beauty of this example is in its simplicity. Great job!
GeneralGoogle Suggest like Dictionarymemberluckyroy3 May '09 - 20:38 
hi,
 
This is lucky i have downloaded code from this link and added web config file and added appsetings in that and added connection sting in dics .aspx page but i am not getting any error are any result what i have to do sir can u reply me online plz mine is luckyroy29@gmail.com
 
http://www.codeproject.com/KB/aspnet/GoogleSuggestDictionary.aspx
 

Regards
 
Lucky
GeneralQuery ModificationmemberMember 450581216 Dec '08 - 12:29 
Great article - thanks! However, I think your query should include ` ORDER BY Word` at the end of it, otherwise you don't necessarily pick up the top 10 items from the database. For example, just enter an `s` in your proof of concept website and the matches begin with `salt, surface, ...` whereas they should be `S, Saadh, Saan, ...'
GeneralProblem in "document.getElementById("autocomplete").innerHTML=req.responseText;"memberMember #316566510 Jan '07 - 3:01 
Hello Friends,
I download this project, and do some modifiations as per my requirement.
i changed only
 
var url="http://www.objectgraph.com/dictionary/dict.aspx?k="+key;
to-->
var url=document.URL;
url=url+'?k='+key
 
and in code behind i written my code to get the values..
i get the values from database, but it will not showning the result in page, it will throughs "Unknown runtime error" on the line..
"document.getElementById("autocomplete").innerHTML=req.responseText;"
when write the stmt before this as
 
document.write(req.responseText);
 
then it will gives the actual result which is send from codebehind.
I am not able to findout the actual problem, why this code is not working..
why it will gives the error on
 
document.getElementById("autocomplete").innerHTML=req.responseText
 
Please tell me as early as possible
 
Thanks,
Mahadeo.

Questionselectable values in div tagmemberutsi12 Oct '06 - 2:04 
Confused | :confused: i noticed this in email sites(rediff.com,yahoo.com) where when u type name of person in the "to" textbox u get data in similar manner but u can also select values of the list availableOMG | :OMG: .when tab is press the values gets entered in the text box could please give a solution for this.
thks in advance.Cool | :cool:
Questionget it working with access database???memberwahabm8 Aug '06 - 0:13 
Sigh | :sigh:
Hallo dear geniuses, Is there somebody who can use access database with .asp to get it working please. I have tried a lot without any success.
If you can do it please share it with us.
Thnx
Long life all geniuses.
Questionhow to display in listbox...memberkamalika_kk10 Jul '06 - 2:36 

can you please tell me how to display the top 10 search in a listbox so that we can select from the listbox and display records from database accordingly?.....actually i'm trying to develop a search technique as it is in the msdn help in any microsoft product....please can you help with this...?...i'm new in asp.net (1.1)......
GeneralPlease I need the database of this programmemberAMRSINAN12 Jun '06 - 23:38 
Please I need the database of this program because the link bellow does not working
http://msowww.anu.edu.au/%7Eralph/OPTED/v003.zip
 
anybody share this file with me. Thnx
and thanks for this article, bro

 
MCSD Amr Sinan

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

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