25
Thu, Apr
1 New Articles

TechTip: The Sound of Soundex, a Working Example

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

I recently stumbled across something I discovered in the past and almost forgot about. That's how I re-discovered the Soundex algorithm. After reading some trivial examples, I decided to create a truly useful application, and that's how this TechTip came alive.

Before I go into detail about the tip, let me briefly explain what Soundex is. Soundex is a phonetic algorithm that was developed nearly a century ago! The Soundex code consists of one letter followed by three numbers. Each letter in a string of characters has a different "weight," and by using five simple rules, the Soundex algorithm can balance different-sounding words into a Soundex code, which then can be used for searches. Wikipedia explains Soundex brilliantly.

OK, back to the tip. As always, I'll give you a short overview of what you can achieve by reading on:

  • An RPG CGI program will let you search a U.S. cities database using the SQL Soundex code (or the SQL Like code).
  • Another RPG CGI program will show you all the cities and their ZIP codes found and allow you to click a link to see the city on a map stored at the MapQuest Web site. (I have no financial interest in MapQuest; the only reason I used that Web site was that it offered a free and easy-to-understand interface.)

So let's jump into it.

If you have read some of my previous TechTips, you should already be familiar with the way I write the RPG CGI programs. So, to save space and avoid repeating myself, I will not spend much time on that. If you are a "first-timer," please read some of my other tips or just download the code, fire up the debugger, and see it for yourself.

Let's start with the databases. This tip uses two databases: WWWCITIES (18950 records) and WWWUSZIP (42741 records).

WWWCITIES contains two fields: CITY and SDXCITY, which is also the keyfield.
SDXCITY is the Soundex code based on the content of CITY. I have done it this way to make it easy to see the Soundex code, and I also believe it actually speeds up the SQL SELECT. But I could just as well have used the Soundex scalar function to retrieve the Soundex code on the fly.

To create a Soundex code based on a field, execute the following SQL statement against the database (remember to define a four-byte alfa field to store the Soundex code in).

UPDATE your-data-lib/WWWCITIES set SDXCITY = soundex(CITY)

If you download the database, you'll find that I've already done this, but I thought you might like to know how I created the Soundex code.

The Web interface

When you load the Web interface, the first thing you'll see is something like Figure 1:

http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020700.jpg

Figure 1: This is the main search interface. (Click images to enlarge.)

You can enter something in the City search field and then select how you want to search.

If you enter "Danmark" (which is how we spell it here in DK) and select the LIKE search, nothing will be displayed, but if you select the SOUNDEX search, the WWWCITIES database will find five entries:

http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020701.jpg

Figure 2: A Soundex search on "Danmark" returns these results.

I also show the Soundex code for both the search argument and the entries found.
You will of course remove this in a real working application, but it is very useful here to give you an idea of how the Soundex algorithm works.

When you click on the "Show all" link for Denmark, the following will be shown:

http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020702.jpg

Figure 3: All cities with the name of Denmark are found in WWWCITIES.

You can now click on a map link to see where the city is located. If you click the DENMARK IA link, a new window will pop up and the following will be shown:

http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020703.jpg

Figure 4: You now have a map for Denmark, Iowa.

Notice that I do not pass the ZIP code to the MapQuest interface. The reason is that, if I do, the red star won't be placed correctly for some reason.

What Happens Behind the Scenes?

The interesting part of the RPG CGI program FORM012 happens in the SQL statements.

FORM012 has two subroutines where the SQL SELECT occurs: SubrSoundex and SubrLike.

Figure 5 shows the SQL code in action:

http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020704.jpg

Figure 5: Here's the SQL SELECT using Soundex.

First, I use the Soundex scalar in a SET statement:

C/Exec SQL                                                          
C+             Set :SearchStringSoundex  = Soundex( :zSearchString )
C/End-Exec                                                          

This will return the four-byte Soundex code in the field SearchStringSoundex.

Then, I execute an SQL SELECT:

select * from your-data-lib/WWWCITIES where sdxcity = :SearchStringSoundex fetch first 20 row only

Notice the "fetch first 20 rows only." This is the same as the MS Access "Top XX." In other SQL flavors, it's the same as the LIMIT statement.

The result of the SELECT is that a maximum of 20 entries will be displayed in the list.

Every time I get a hit from the SELECT statement, I write it out to the browser, and at the same time, I build a query string link to RPG CGI program FORM012A, which is used to display all the cities and their ZIP codes found in file WWWUSZIP.

The Link to MapQuest

One last thing to point out is the link to MapQuest. The program code that builds the link in FORM012A looks like this:

      // Create link               
        link = '<a href="javascript:PopWin('    
             + q                                
             + 'http://www.mapquest.com/maps/'  
             + 'map.adp?address=&city='         
             + %trim(city)                      
             + '&state='                        
             + %trim(state)                     
             + '&zipcode='                      
             + '&country='                      
             + %trim(country)                   
             + '&cid=lfmaplink'                 
             + q                 
             + ',300,300);"'     
             + ' '               
             + 'title="'         
             + 'Latitude:'       
             + %trim(PNLAT)      
             + '/'               
             + 'Longitude:'      
             + %trim(PNLONG)     
             + '"'               
             + '>'               
             + 'Map';        

How did I know what the query string to MapQuest should look like? A lot of Web sites offer this kind of service for free, so if you don't like the interface of MapQuest, find your own favourite and look around to see if you can find some sample links you can use. Some sites offer a wide range of services if you want to pay for them, so it's just a matter of finding one you like.

To display the map in a pop-up, I use a small JavaScript function to display the map in full screen window:

<script language="JavaScript" data-mce-type="text/javascript"> 
 

Notice that fullscreen=yes is the keyword that does the whole trick.

Downloading and Installing

  1. Create a directory in your root dir called /root/mcpressonline by entering this command from a command line: md '/rootdir/mcpressonline/'
  2. Create a directory called likesoundex inside mcpressonline. Enter the following: md '/rootdir/mcpressonline/likesoundex'
  3. Download likesoundex.zip, unzip it, and upload everything to '/web/mcpressonline/likesoundex'. It should look like this:http://www.mcpressonline.com/articles/images/2002/likesoundexV4--03020705.jpg
  4. Compile WWWCITIES and WWWUSZIP or restore savefile wwwsoundex.zip to your i5.
  5. Save copy book for BUFIO_H to your i5.
  6. Download and save the source to FORM012 and FORM012A on your i5.
  7. If you do not already have it, download and compile CGIPARSEZ.

Before compiling, remember to change "your-data-lib" in the RPG sources and SQL SELECT statements to where you placed the data files. Also, change "your-root-dir" in constant IFSpath to your actual root directory.

When you have installed everything and compiled the RPG programs (compile instructions can be found in the header description), you are ready to test the Soundex search.

Load the search by entering http://your-server-name/cgi-bin/form012frame.htm.

Try It

I know Soundex is not new on the i5, but the examples I found in the IBM manuals were really poor, so I hope you can use this tip. Try building it into, for example, a customer or product file.

Jan Jorgensen is a programmer at Electrolux Laundry Systems Denmark. He works with RPG, HTML, JavaScript, and Perl and is trying hard to learn C#.
You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..

Jan Jorgensen

Jan Jorgensen is one of the owners of www.reeft.dk, which specializes in mobile and i5 solutions. He works with RPG, HTML, JavaScript, Perl, and PHP. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it.

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: