Download the Source Code for this article [zip 8kb]
Comment on this article at thecodeproject
Article I describes building a simple search engine that crawls the filesystem from a specified folder, and indexing all HTML (or other types) of document. A basic design and object model was developed as well as a query / results page which you can see here .
THIS Second Article In The Series Discusses Replacing The 'FileSystem Crawler' with a 'Web Spider' To Search and Catalog A Website by Following The Links in The Html. The Challenges Involved Include:
Downloading HTML (and other document types) via HTTP Parsing the HTML looking for links to other pages Ensuring that we do not keep recursively searching the same pages, resulting in an infinite loop Parsing the HTML to extract the words to populate the search catalog from Article I
DESIGN
The Design from Article I Remains Unchanged ...
A Catalog Contains a Collection of Words, And Each Word Contains a Reference To Every File That It Appears in
... The Object Model Is The Same Too ...
What has changed is the way the Catalog is populed. Instead of looping through folders in the filesystem to look for files to open, the code requires the Url of a start page which it will load, index and then attempt to follow every link within that ............................
Code structure
Some of the code from Article I will be referenced again, but we've added a new page - SearcharooSpider.aspx - that does the HTTP access and HTML link parsing [making the code that walks directories in the filesystem - SearcharooCrawler.aspx -obsolete ] We've also changed the name of the search page to SearcharooToo.aspx so you can use it side-by-side with the old one.Searcharoo.cs Implementation of the object model;. compiled into both ASPX pages RE-USED FROM ARTICLE 1 SearcharooCrawler.aspx OBSOLETE, REPLACED WITH SPIDERSearcharooToo.aspx <% @ Page Language = "C #" Src = "Searcharoo.cs"%> <% @ import Namespace = "Searcharoo.Net"%> Retrieves the Catalog object from the Cache and allows searching via an HTML form. UPDATED SINCE ARTICLE 1 tO IMPROVE uSEABILITY, and renamed to SearcharooToo.aspx SearcharooSpider.aspx <% @ Page Language = "C #" Src = "Searcharoo.cs"%> <% @ import Namespace = " SEARCHAROO.NET "%> Starting from the start page, download and index every linked page. New Page for this Article
There Are Three Fundamental Tasks for a Search Spider:
Finding the page
The big search engines - Yahoo, Google, MSN -. All 'spider' the internet to build their search catalogs Following links to find documents requires us to write an HTML parser that can find and interpret the links, and then follow them This includes! being able to follow HTTP-302 redirects, recognising the type of document that has been returned, determing what character set / encoding was used (for Text and HTML documents), etc. -! basically a mini-browser We'll start small and Attempt to build a passable spoter using c # ... build the spider [Searcharoospider_alpha.aspx]
Getting Started - Download a page
To get something working quickly, let's just try to download the 'start page' - say the root page of the local machine. (Ie Step 2 -. Downloading pages) Here is the simplest possible code to get the contents of an HTML page from A Website (Localhost In this case):
Using system
.NET
;
/*...
String
URL
=
"http:// localhost /"
;
// Just for testing WebClient
Browser
=
NEW WebClient
(
)
;
UTF
8encoding
ENC
=
New UTF
8encoding
(
)
;
String
FileContents
=
ENC
.Getstring
(
Browser
.Downloaddata
(
URL
)
)
;
Listing 1 - SimpleSt Way to Download an Html Document
The first thing to notice is the inclusion of the System.Net namespace. It contains a number of useful classes including WebClient, which is a very simple 'browser-like' object can download text or data from a given URL.The second thing that is that we assume the page is encoded using UTF-8, using the UTF8Encoding class to convert the downloaded Byte [] array into a string. If the page returned was encoded differently (say, Shift_JIS or GB2312) then this conversion would produce garbage. We'll have to fix this later.The third thing, which might not be immediately obvious, is that I have not actually specified a page in the url. We rely on the server to resolve the request and return the default document to us -. however the server might have issued a 302 Redirect to another page (or another directory, or even another site) WebClient will successfully follow those redirects but it's interface has no simple way for the code to query what the pages actual URL is (after The redirects. we'll have to fix this later, too, otherwise it's impossible to resolve relative Urls within the page.Despite those problems, we now have the full text of the 'start page' in a variable. That means we can begin to work on the code for Step 1 - Finding Pages To Index.
Parsing the page
There Are Two Options (OK, Probably More, But Two Main Options) for Parsing The Links (AND Other Data) Out of HTML:
Reading in Entire Page String, Building A Dom and Walking Through It's Elements Looking For Links, or Using Regular Expressions to Find Link Patterns in The Page String.
Although I suspect "commercial" search engines might use option 1 (building a DOM), it's much simpler to use Regular Expressions Because my initial test website had very-well-formed HTMl, I could get away with this code:. // Create ArrayLists to Hold The Links We Find ... arraylist
Linklocal
=
New arraylist
(
)
;
ArrayList
LINKEXTERNAL
=
New arraylist
(
)
;
// DODGY REGEX WILL FIND * SOME * LINKS
Foreach
(Match
Match
in Regex
.Matches
(
HTMLDATA
, @
"(? <= <(a | area) / s href ="
"). *? (? ="
"/ s * /?>)"
, RegexOptions
.IGNORECASE
| Regexoptions
.Explicitcapture
)
)
{
LINK
=
Match
.Value
;
// regex matches from opening "quote
int
Spacepos
=
LINK
.Indexof
(
'' '
)
;
// Find First Space (IE No Spaces in URL)
int
Quotepos
=
LINK
.Indexof
(
'"'"
)
;
// or first closing quote (Single Quotes Not Supported)
int
Choppos
=
(
Quotepos <
Spacepos
?
Quotepos
:
Spacepos
)
;
// end url at the first space or quote
IF
(
Choppos>
0
)
{
// CHOP URL
LINK
=
LINK
.Substring
(
0
,
Choppos
)
;
}
IF
(
(
LINK
"
8
)
&
&
(
LINK
.Substring
(
0
,
Seduce
)
.Tolower
(
)
=
=
"http://"
)
)
{
// Assumes all links beginning with http: // is _external_
LINKEXTERNAL
.Ad
(
LINK
)
;
}
Else
{
// Otherwise they're "relative" / internal links sowe contatenate the base url
LINK
=
StartingURL
LINK
;
Linklocal
.Ad
(
LINK
)
;
}
}
// end looping through matches of the 'link' Pattern in the HTML Data
Listing 2 - SimpleSt Way To Find Links in a page
As with the first cut of page-downloading, there are a number of problems with this code Firstly, the Regular Expression used to find the links is * very * restrictive, ie it will find -..
- Because The Href Appears A (or Area), And The Url Itself Is Double-quoted. However That Code Will Have Trouble with a Lot of Valid Links, Including:
It will also attempt to use 'internal page links' (beginning with #), and it assumes that any link beginning with http: // is external, without first checking the servername against the target server Despite the bugs, testing against tailored HTML. pages this code will successfully parse the links into the linkLocal ArrayList, ready for processing - coupling that list of URLs with the code to download URLs, we can effectively 'spider' a website!
Download More Pages
The Basic Code Is Shown Below - Comments Show Where Additional Code Is Required, Either from The Listings Above Or In Article I.
protected
Void Page_Load
(
Object
Sender
SYSTEM
.Eventargs e
)
{
/ * The initial function call * /
StartingPageurl
=
"http:// localhost /"
;
// Get from Web.config
Parseurl
(
StartingPageurl
,
New UTF
8encoding
(
)
,
NEW WebClient
(
)
)
;
}
/ * This is Called Recursively for Every Link We Find * /
public
Void
Parseurl
(
String
URL
UTF
8encoding
ENC
, WebClient
Browser
)
{
IF
(
Visited
.Contains
(
URL
)
)
{
// URL Already Spide, Skip and Go To Next Link Response
.Write
(
"
"
URL
"Already SpideRed font>"
)
;
}
Else
{
// add this url to the 'visited' list, so we'll Skip it at Id Across It Again
Visited
.Ad
(
URL
)
;
String
FileContents
=
ENC
.Getstring
(
Browser
.Downloaddata
(
URL
)
)
;
// from Listing 1
// ### pseudo-code ###
// 1. Find Links in The Downloaded Page (Add to Linklocal ArrayList - Code in Listing 2)
// 2. Extract
// 3. Remove All HTML and Whitespace (Same As Version 1)
// 4. Convert Words to string Array, And Add to Catalog (Same As Version 1 Listing 7)
// 5. If any links werefact, Recursively Call this Page
IF
(
NULL
!
=
PMD
.Locallinks
)
Foreach
(
Object
LINK
in
PMD
.Locallinks
)
{
Parseurl
(Convert)
.Tostring
(
LINK
)
,
ENC
,
Browser
)
;
}
}
}
Listing 3 - Combining The link Parsing and page Download Code.
Review The Three Fundamental Tasks for a search Spider, and you can see we've developed ENOUGH CODE To Build IT:
Finding the pages to index - we can start at a specific Url and find links using Listings 2 & 3. Downloading each page successfully - we can do this using the WebClient in Listings 1 & 2. Parsing the page content and indexing it - we already have this code from Article IAlthough the example above is picky about what links it will find, it will work to 'spider' and then search a website! FYI, you can view the 'alpha version' of the code and use it in conjunction with . the other files from Article I to search the catalog The remainder of this article discusses the changes required to this code to fix the shortcomings discussed earlier; the ZIP file contains a complete set of updated code.
FIX The Spider [Searcharoospider.aspx]
Problem 1 - Correctly Parsing Relative Links
The Alpha Code Fails To Follow 'Relative' AND 'Absolute' Links (Eg. "../../News/page.htm" and "/news/page2.htm" respective) Partly Because It Does Not 'Remember' What What What? folder / subdirectory it is parsing. My first instinct was to build a new 'Url' class which would take a page URL and a link, and encapsulate the code required to build the complete link by resolving directory traversal (eg "../" Absolute References (Eg. Starting with "/"). The code 10 NEED TO do Something Like this:
Page URLLLINK IN PAGERESULT Should Behttp: //localhost/news/page2.htmhttp://localhost/news/page2.htmhttp://localhost/news/../localhost/contact.htmhttp: // Localhost / news // downloads / http: // localhost / downloads / etc.
Solution: URI Class
The first lesson to learn when you have a class library at your disposal is LOOK BEFORE YOU CODE. It was almost by accident that I stumbled across the Uri class, which has a constructor -new Uri (baseUri, relativeUri)
- That does exactly what I need. No re-inventing the wheel!
Problem 2 - Following Redirects
Following relative links is made even more difficult because the WebClient class, while it enabled us to quickly get the spider up-and-running, is pretty dumb. It does not expose all the properties and methods required to properly emulate a web browser's behaviour. .. IT IS Capable of Following Redirects Issued By A Server, But It Has No Simple Interface To Communicate To The Calling Code Exactly What URL IT Ended Up Requesting.
Solution: httpwebrequest & httpwebresponse classes
The HttpWebRequest and httpwebresponse classes provide a MUch More Powerful Interface for http communication. Httpwebrequest Has A Number of Useful Properties, include:
! AllowAutoRedirect - configurable MaximumAutomaticRedirections - redirection can be limited to prevent 'infinite loops' in naughty pages UserAgent - set to "Mozilla / 6.0 (MSIE 6.0; Windows NT 5.1; Searcharoo.NET Robot)" (see Problem 5 below) KeepAlive - efficient Use of connections timeout - configurable based on the expected performance of the target Website
which are set in the code to help us get the pages we want HttpWebResponse has one key property - ResponseUri - that returns the final Uri that was read; for example, if we tried to access http:. // localhost / and the server issued a 302-redirect to /en/index.html then the HttpWebResponseInstance.ResponseUri would be http: //localhost/en/index.html and NOT just http:. // localhost / This is important because unless we know the URL of the CURRENT PAGE, WE Cannot Process Relative Links Correctly (See Problem 1) .problem 3 - Using The Correct Character-set by When Download Files
Getting content-type
Solution: httpwebresponse and the encoding namespace
The Httpwebresponse Has Another Advantage Over WebClient: It's Easier To Access Http Server Headers Such as the contenttype and contentencoding. This enables the following code to be written:
IF
(
WebResponse
.Contentencoding
!
= String
Empty
)
{
// use the httpheader content-type in preference to the one set in meta
HTMLDOC
.Encoding
=
WebResponse
.Contentencoding
;
}
Else
IF
(
HTMLDOC
.Encoding
=
= String
Empty
)
{
// Todo: if still no encoding determined, Try to readline the stream untric we find
// * meta content-type or * head> (ie. Stop loops for meta)
HTMLDOC
.Encoding
=
"UTF-8"
;
// default
}
//http://www.c-sharpcorner.com/code/2003/Dec/readingwebpagesources.asp system
.Io
.StreamReader
Stream
=
New system
.Io
.StreamReader
(
WebResponse
.GetResponsestream
(
)
, ENCODING
.Geetencoding
(
HTMLDOC
.Encoding
)
)
;
HTMLDOC
.Uri
=
WebResponse
.RESPONSEURI
;
// We * May * Have Been Redirected ... and we want the * final * URL
HTMLDOC
.Length
=
WebResponse
.ContentLength;
HTMLDOC
.All .all .all .all
=
Stream
.Readtoend
(
)
;
Stream
.Close
(
)
;
Listing 4 - Check The Http Content Encoding and Use The Correct Encoding Class to Process The Byte [] Array Returned from The Server
Elsewhere in The Code We Use The ContentType To Paarse Out The Mime-Type of The Data, So That We Can Ignore Images, Stylesheets (AND, For this Version, Word, PDF, Zip and other file types).
Problem 4 - Does Not Recognise Many Valid Link Formats
When Building The Alpha Code I Implement I Could Find To Locate Links in A String - (? <= <(A | area) / s href = "). *? (? =" / S * /? >). The problem is this it is far too dumb to find the massity of links.
Solution: Smarter Regular Expressions
. Regular Expressions can be very powerful, and clearly a more complex expression was required Not being an expert in this area, I turned to Google and eventually Matt Bourne who posted a couple of very useful Regex patterns, which resulted in the following code:
// http://msdn.microsoft.com/library/en-us/script56/HTML/JS56JSGRPREGEXPSYNTAX.ASP
// Original Regex, Just Found links; and was "broky" by spaces, out-of-order, etc
@ "(? <= )"
Foreach
(Match
Match
in Regex
.Matches
(
HTMLDATA
, @
"(?
"[^"
"] *"
"| '[^'] * '| [^"
"<>] ) / s *)?) *)? / s *>)"
, RegexOptions
.IGNORECASE
| Regexoptions
.Explicitcapture
)
)
{
// PARSE All Attributes from With Tags ... Important when're out of Order !!
// in addition to the 'href' attribute, there is might also be 'alt', 'class', 'style', 'Area', etc ...
// there might also be 'spaces' between the attributes and the year be ",', or uNuoted
LINK
= String
Empty
;
Foreach
(Match
Submatch
in Regex
.Matches
(
Match
.Value
.Tostring
(
)
, @
"(?
"(?
"] *)"
"| '(?
"<> / s] ) / s *) "
, RegexOptions
.IGNORECASE
| Regexoptions
.Explicitcapture
)
)
{
// We're only intended in the Href Attribute (Although IN FUTURE MAYBE INDEX THE 'Alt' / 'Title'?)
IF
(
"href"
=
=
Submatch
.Groups
[
1
]
.Tostring
(
)
.Tolower
(
)
)
{
LINK
=
Submatch
.Groups
[
2
]
.Tostring
(
)
;
Break
;
}
}
/ * check for interNal / External Link and supported scheme, the add to arraylist * /
}
// foreach
Listing 5 - More Powerful Regex Matching
Listing 5 Performs Three Steps:
Match Entire Link Tags (from
Problem 5 - Poor meta-tag handling
The alpha has very rudimentary META tag handling - so primative that it accidentally assumed instead of the correct format There are two reasons to. Process the Meta Tags Correctly: (1) TO Get The Description and keywords for this document, and (2) read the robots tag so much Our spider behaves nicely when our spotted.
Solution: Smarter Regular Expressions and Support for more tags
Using a variation of the Regular Expressions from Problem 4, the code parses out the META tags as required, adds Keywords and Description to the indexed content and stores the Description for display on the Search Results page.string
Metakey
= String
Empty
,
Metavalue
= String
Empty
;
Foreach
(Match
Metamatch
in Regex
.Matches
(
HTMLDATA
, @
"
"[^"
"] *"
"| '[^'] * '| [^"
"<>] ) / s *)?) *) /? / s *>"
, RegexOptions
.IGNORECASE
| Regexoptions
.Explicitcapture
)
)
{
Metakey
= String
Empty
;
Metavalue
= String
Empty
;
// loop through the attribute / value pairs inside the tag
Foreach
(Match
Submetamatch
in Regex
.Matches
(
Metamatch
.Value
.Tostring
(
)
, @
"(?
"(?
"] *)"
"| '(?
"<>] ) / s *) "
, RegexOptions
.IGNORECASE
| Regexoptions
.Explicitcapture
)
)
{
IF
(
"http-equiv"
=
=
Submetamatch
.Groups
[
1
]
.Tostring
(
)
.Tolower
(
)
)
{
Metakey
=
Submetamatch
.Groups
[
2
]
.Tostring
(
)
;
}
IF
(
(
"name"
=
=
Submetamatch
.Groups
[
1
]
.Tostring
(
)
.Tolower
(
)
)
&
&
(
Metakey
=
= String
Empty
)
)
{
// if it's already set, http-equiv takes precedence
Metakey
=
Submetamatch
.Groups
[
2
]
.Tostring
(
)
;
}
IF
(
"Content"
=
=
Submetamatch
.Groups
[
1
]
.Tostring
(
)
.Tolower
(
)
)
{
Metavalue
=
Submetamatch
.Groups
[
2
]
.Tostring
(
)
;
}
}
Switch
(
Metakey
.Tolower
(
)
)
{
Case
"description"
:
HTMLDOC
.Description
=
Metavalue
;
Break
;
Case
"keywords"
:
Case
"keyword"
:
HTMLDOC
Keywords
=
Metavalue
;
Break
;
Case
"robots"
:
Case
"robot"
:
HTMLDOC
.Setrobotdirective
(
Metavalue
)
;
Break
;
}
}
Listing 6 - Parsing Meta Tags Is A Two Step Process, Because We Have to Check The 'Name / Http-Equiv' So That We know What the Content Relate To!
It also obeys the ROBOTS NOINDEX and NOFOLLOW directives if they appear in the META tags (you can read more about the Robot Exclusion Protocol as it relates to META tags; note that we have not implemented support for the robots.txt file which sites in the root of a website - perhaps in version 3) We also set our User-Agent (Solution 2) to indicate that we are a Robot so that the web log of any site we spider will clearly differentiate our requests from regular browsers; it!. Also Enables U.
Spidering the web!
When you load the SearcharooSpider.aspx page it immediately begins spidering, starting with either (a) the root document in the folder where the file is located, OR (b) the location specified in web.config (if it exists).
Screenshot 1 - The title of each page is displayed as it is space Factbook as test data
Once the catalog is Built, You are ready to search.
Performing the search
All The Hard Work Was Done in Article 1 - This Code Is Repeated for Your Information ...
///
///
(
String
Searchword
)
{
// Apply the Same 'Trim' As When We're Building The Catalog
Searchword
=
Searchword
RIM
(
'?'
,
'/ "
,
','
,
'/' '
,
';'; '
,
':'
,
'.'. '
,
'
,
')'
)
.Tolower
(
)
;
Hashtable
RetVal
=
NULL
;
IF
(
Index
.Containskey
(
Searchword
)
)
{
// does all the work !!! Word
Thematch
=
(Word
)
Index
[
Searchword
]
;
RetVal
=
Thematch
.Infiles
(
)
;
// Return the Collection of File Objects
}
Return
RetVal
;
}
Article 1 Listing 8 - The Search Method of The Catalog Object
We have not modified any of the Search objects in the diagram at the start of this article, in an effort to show how data encapsulation allows you to change both the way you collect data (ie. From filesystem crawling to website spidering) and the way you present data (ie. updating the search results page) without affecting your data tier. In article 3 we'll examine if it's possible to convert the Search objects to use a database back-end without affecting the collection and presentation classes ...
Improving the results [SearcharoOTOO.ASPX]
THESE Are The Changes We Will Make To The Results Page:
ENABLE SEARCHING for more Than One Word and Requiring All Terms To Appear in The Resulting Document Matches (Boolean and Search) Improved Formatting, Impruted:
Pre-Filled Search Box on The Results Page Document Count For Each Term in The Query, and Link to View Those Results Time Taken To Perform Query
The first change to support searching on muliple terms is to 'parse' the query typed by the user This means:. Trimming whitespace from around the query, and compressing whitespace between the query terms We then Split the query into an Array [] of. Words and Trim Any Puncture from Around Each Term.Searchterm
= Request
.QueryString
[
"SearchFor"
]
.Tostring
(
)
RIM
(
'' '
)
;
Regex R
=
New Regex
(@
"/ s "
)
;
// Remove All Whitespace
Searchterm
= r
.Replace
(
Searchterm
,
""
)
;
// TO a Single Space
Searchterma
=
Searchterm
.Split
(
'' '
)
;
// THEN SPLIT
for
(
INT i
=
0
i <
Searchterma
.Length
i
)
{
// Array of Search Terms
Searchterma
[i
]
=
Searchterma
[i
]
RIM
(
'' '
,
'?'
,
'/ "
,
','
,
'/' '
,
';'; '
,
':'
,
'.'. '
,
'
,
')'
)
.Tolower
(
)
;
// Get Trimmed Individally
}
Listing 7 - The Search Method of The Catalog Object
Now that we have an Array of the individual search terms, we will find ALL the documents matching each individual term. This is done using the same m_catalog.Search () method from Article I. After each search we check if any results were returned, And Store The SearchResultsarrayArray to Process Further.
// array of arrays of results match one of the search criteria hashtable
[
]
SearchResultsarrayArray
=
New hashtable
[
Searchterma
.Length
]
;
// FinalResultsArray Is Populated with Pages That * Match * All The Search Criteria HybridDictionary
FinalResultsArray
=
New hybriddictionary
(
)
;
// html output stringstring
Matches
=
""
;
Bool
BothertofindMatches
=
True
;
int
IndexOfshortestResultset
=
-
1
,
LengthofshortestResultset
=
-
1
;
for
(
INT i
=
0
i <
Searchterma
.Length
i
)
{
SearchResultsarrayArray
[i
]
=
M_catalog
.Search
(
Searchterma
[i
]
.Tostring
(
)
)
;
// ##### THE Search #####
IF
(
NULL
=
=
SearchResultsarrayArray
[i
]
)
{
Matches
=
Searchterma
[i
]
} Else { int Resultsinthisset = SearchResultsarrayArray [i ] .Count ; Matches = " " Searchterma [i ] " (" Resultsinthisset ") font>" ; IF ( ( LengthofshortestResultset = = - 1 ) | | ( LengthofshortestResultSet> Resultsinthisset ) ) { IndexOfshortestResultset = I ; LengthofshortestResultset = Resultsinthisset ; } } } Listing 8 - Find The Results for Each of The Terms Individally Describing how we find the documents that match ALL words in the query is easiest with an example, so imagine we're searching for the query "snow cold weather" in the CIA World FactBook. Listing 8 found the Array of documents matching each word, and placed them inside another Array. "snow" has 10 matching documents, "cold" has 43 matching documents and "weather" has 22 matching documents.Obviously the maximum possible number the of overall matches is 10 (the smallest result set), and minimum is zero -. maybe there are NO documents that appear in all three collections Both of these possibilities catered for - indexOfShortestResultSet remembers which word had fewest results and botherToFindMatches is set to false if any word fails to get a single match. Diagram 1 - Finding The Intersection of The Result Sets for Each Word Involves Traversing The 'Array Of Arrays' Listing 9 shows how we approached this problem. It may not be the most efficient way to do it, but it works! Basically we choose the smallest resultset and loop through its matching Files, looping through the SearchResultsArrayArray (counter 'cx') looking for That Same File in All The Other Results. Imagine, Referring to The Diagram Above, That We Begin with [0] [0] FILE D (We Start with Index [0] "Snow" Because IT's The Smallst Set, Not Just Because it's item 0). The loop bellow Start Checking All The Other Files To See IT Finds D Again ... But n't start in set [0] BECAUSE WE Already Know That D Is UNIQUE IN this set. "IF (cx == c)" Checks That Condition and prevents looping through resultset [0]. Counter 'CX' Will Be Incremented To 1, And The Loop Will Begin Examing Items [1] [0], [1] [1], [1] [2], [1] [3], [1] [4 (FILES G, E, S, H, K, D) But 'ney (fo.key = fox.key) "Won't match because we are still search for matches to file [0] [0] D. However , on the next orthopes, sowe ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ? file exists in both sets I chose a very simple solution - count the number of sets we're comparing totalcount - and keep adding to the matchcount when we find the file in a set We can then safely break out of that loop (knowing. That the file is unique within a resultset, and we would noting the next resultset. After the looping has completed, "if (matchcount == totalcount)" then we know this file exists in ALL the sets, and can be added to the FinalResultsArray, which is what we'll use to show the results page to the user. The looping will continue with 'cx' incremented to 2, and the "weather" matches will be checked for file D. It is found at position [2] [2] and the matchcount will be adjusted accordingly. The whole looping process will then Begin again in the "snow" matches [0] [1] FILE G, AND All The Other Files Will Again Be Checked Against this One To See if IT exissrs in all sets. After a LOT of looping, the code will discover that only files D and G exist in all three sets, and the finalResultsArray will have just two elements which it passes to the same display-code from Listings 10-13 in Article I. // Find The Common Files from the array of arrays of documents // matching one of the criteria IF ( BothertofindMatches ) { // all Words Have * Some * matches Int C = IndexOfshortestResultset ; // loop through the * Shortest * Resultset HashTable SearchResultsArray = SearchResultsarrayArray [c ] ; IF ( NULL ! = SearchResultsArray ) Foreach ( Object FoundInfile in SearchResultsArray ) { // for Each File In The * Shortest * Result Set Dictionaryentry fo = (Dictionaryentry ) FoundInfile ; // Find Matching Files in The Other Resultsets int Matchcount = 0 , Totalcount = 0 , Weight = 0 ; for ( int CX = 0 ; CX < SearchResultsarrayArray .Length ; CX ) { Totalcount = ( CX 1 ) ; // Keep Track, So We CAN Compare At The End (if Term is in All Results) IF ( CX = = C ) { // Current Resultset Matchcount = ( CX 1 ) ; // Implicitly Matches in The Current Resultset Weight = ( int ) fo .Value ; // sum the weighting } Else { Hashtable SearchResultsArrayx = SearchResultsarrayArray [ CX ] ; IF ( NULL ! = SearchResultsArrayx ) Foreach ( Object FoundInfilex in SearchResultsArrayx ) { // for Each File In The Result Set Dictionaryentry Fox = (Dictionaryentry ) FoundInfilex ; IF ( fo Key = = Fox Key ) { // see if it matches Matchcount = ( CX 1 ) ; // and if it matches, TRACK THE MATCHCOUNT Weight = ( int ) Fox .Value ; // and weighting; the Break out of loop, Since Break ; // no need to keep loops} } // foreach } // if } // for IF ( ( Matchcount> 0 ) & & ( Matchcount = = Totalcount ) ) { // Was matched in Each Array fo .Value = Weight ; // set the 'weight' in the combined results to the sum of individual document matches IF ( ! FinalResultsArray .Contains ( fo Key ) ) FinalResultsArray .Ad ( fo Key , fo ) ; } // if } // foreach } // if Listing 9 - Finding The Sub-Set of Documents That Contain Every Word in The Query. There's Three Nested Loops in There - I Never Said this Was Efficient! The algorithm described above is performing a boolean AND query on all the words in the query, ie. The example is searching for "snow AND cold AND weather". If we wished to build an OR query, we could simply loop through all the files And filter out duplicates. or queries aren't this useful unless, such as "Snow and clauses" - But this is not supported in Version 2! BTW, the variables in that code which I've called "Array" for simplicity are actually either Hashtables or HybridDictionaries Do not be confused when you look at the code -. There were good reasons why each Collection class was chosen (mainly that I Didn't Know In Advance The Final Number of items, so useful is too hard. The finished result Screenshot 2 - The Search Input Page Has Minor Changes, Including The FileName To SearcharoOTOO.ASPX! Screenshot 3 - You can refine your search, see the number of matches for each search term, view the time taken to perform the search and, most importantly, see the documents containing all the words in your query Using the sample code! The goal of this article was to build a simple search engine that you can install just by placing some files on your website;! So you can copy Searcharoo.cs, SearcharooSpider.aspx and SearcharooToo.aspx to your web root and away your go However ................... To change Those defaults you need to add some settings to web.config: To Spider -> Second Timeout when Downloading -> Pages to Index -> appsettings> Listing 14 - Web.configthen SIMPLY NAVIGATE TO Http://localhost/searcharootoo.aspx (or wherever you put the search "and it will build the catch. If your application re-starts for any reason (. Ie You compile code into the / bin / folder, or change web.config settings) the catalog will need to be rebuilt - the next user who performs a search will trigger the catalog build. ............. .. FUTURE SearcharooSpider.aspx greatly increases the utility of Searcharoo, because you can now index your static and dynamic (eg. Database generated) pages to allow visitors to search your site. That means you could use it with products like Microsoft Content Management Server (CMS) Which Does Not Expose It's Content-Database Directly.The Two Remaining (Major) Problems With Searcharoo Are: (a) IT cannot Persist the catalog to disk or a database - meaning this a lot of memory to be used to store the catalog, and (B) Most websites contain more than just HTML pages; they also link to Microsoft Word or other Office files, Adobe Acrobat (PDF Files) and other forms of content which Searcharoo currently can not 'understand' (ie parse and catalog.). The Next Articles in this Series Will (Hopefully) Examine these Two Problems in more detil ... Glossary TermMeaningHTMLHyper Text Markup LanguageHTTPHyper Text Transmission ProtocolURLUniversal Resource LocatorURIUniversal Resource IdentifierDOMDocument Object Model302 RedirectThe HTTP Status code that tells a browser to redirect to a different URL / page.UTF-8Unicode Transformation Format - 8 bitMIME TypeMulitpart Internet Mail ExtensionSpiderProgram that goes from webpage to webpage by finding and following links in the HTML: visualize a spider crawling on a web:) CrawlerAlthough the terms 'spider' and 'crawler' are often used interchangably, we'll use 'crawler' to refer to a program that locates target pages on a filesystem OR External 'List'; WHEREAS A 'Spider' Will Find Other Pages Via Embedded Links.shift_JIS, GB2312Character Sets ... Search Engine Glossary Postscript:? What about code-behind and Visual-Studio.NET (from Article I) You'll notice the two ASPX pages use the src = "Searcharoo.cs" @Page attribute to share the common object model without compiling to an assembly WITH 'Using