In Search Of... integrating site search
by Ian Barber
- 5,976 views
Presentation from PHP UK 2010. Despite being a key method of navigation on many sites, search functionality often gets the short end of the stick in development, either by handing the job over to ...
Presentation from PHP UK 2010. Despite being a key method of navigation on many sites, search functionality often gets the short end of the stick in development, either by handing the job over to Google or just enabling full text search on the appropriate column in the database. In this talk we will look at how full text search actually works, how to integrate local text search engines into your PHP application, and how it's possible to actually provide better and more relevant results than Google itself, at least for your own site.
Statistics
- Likes
- 6
- Downloads
- 109
- Comments
- 2
- Embed Views
- Views on SlideShare
- 5,901
- Total Views
- 5,976

1–2 of 2 previous next
But with search, they tell us
Search is about getting content to users that want it
Searching users are Active and engaged
Give them what they want and they are more likely to
Buy, Read, Comment, Share etc.
how full text search works,
looks at some different options for integration
looks at making it better
Time for questions at the end, but one does spring to mind now:
Private, intranet, FB inbox, offline
Bad at, twitter for a long time, blogs for a long time
Product focus, like amazon
Speed of update, like a forum
Now, lets look at how a full text search operates.
Raw Text
Documents (add url, title, split up etc.)
Text Analysis
Index
Query Parser
Query
Results
Search UI
Start with pool of raw data, chunked into documents
Analyser processes text in docs , Index stores
Other side: Search UI
Query parsed by query parser, like anlyser,
Searched on index and Results sorted and returned
Can be difficult, even with space char.
Commas - remove punctuation - then send 1.1 mil to 11 mil!
Hyphens
Apostrophes
Here we look for continuous sequences of word chars
Capture with offset, which is for phrase matching.
More advanced SEs have better tokenisation: & in AT&T
Some instead have buzzwords file, specific terms: C++
Filter stop words - an, the, of - don’t distinguish
Position info included
Positions still stored, represented by ()
e.g best @ 4 and 16 in doc 1.
Often stored separate, or just a straight count
List of docs == posting list
Enough to start a search
For each term we array_intersect.
Can do boolean searches by doing array union for OR etc.
BUT no RANK - any result with all words as good as other
Must store importance of terms to documents - weight
TF - term frequency, the count of terms in the document
IDF, inverse document frequency, the rareness of the term in the collection
TF - Count of times term appears
IDF - total docs / docs with term, 10 total / 3 with term. Log to smooth
Store this score with the document in the posting list for the term
Normalise scores over a doc to acct for length - but still boosts short text
One dimension for each term ever seen
Mostly 0
Normalised to length 1 (sqrt of sum of sqrs of vals)
Here, rather than just looking for matches
We accumulate a score for each matching document
246 is our highest scoring document, picking up two good scores
But 120 makes it in at number three, despite not having ‘best’ in it.
Calculate cosine of angle between with dot prod
Similarity - 1 = same, 0 = orthogonal (no shared terms)
We can treat a query as a new document
The documents it is most similar to are the best results
Only need to compare to documents that share terms -rest will be score 0
Treat query term weights as 1 - incorrect, but ok for relative results
Index merge, and calc dot product by summing weights.
So, don’t need a full match
Could add phrase search, or positional bias.
Where does the data come from?
How is the index accessed?
Look at 6 PHP friendly engines
Each different integration method
Each with new bits of functionality
Simplest of all to implement - integrate through query
Note fulltext index.
Straight vector space search impl. as described before.
Only can be used for MyISAM, not InnoDB
If you’re using postgres, tsearch built in since 8.3
Boolean too - all engines have this, we focus on natural
Only one document has both words
Ranked in score order - MATCH AGAINST returns a float
Note there’s some tricky default config: min word length 4, and 50% fill exclusion
Blindly expand the search based on words returned.
Usually not a very good idea, because we want more precision that recall
Precision is quality of results, recall is completeness
In this case it’s expanded to lorenzo, because of marcello’s hatred for bacon
myisam_ftdump
Run from the database directory
However, lets say you want to search on a normalised schema directly - multiple tables
Used on craigslist, and apparently on The Pirate Bay
There is a PHP API for access, or extension pecl/sphinx
Same interface but faster
Top: Connection Stuff - also works with postgresql
Indexing on sql_query - could use view, complex etc.
Adding attributes - non indexed elements of a doc - Numeric or timestamp only in sphinx.
Using multi valued attributes, support tags many to many
Other options, such sql_query_pre or post
Minimum length of indexed word
Prefix for wild card search - infix anywhere, prefix end
We also enable a stemmer
Here each version is reduced to happen, but not always an english word is generated, just a consistent one
This allows us to match more words, and is often, but not always, helpful
The most common algorithm is the Porter stemmer, there is a PHP implementation on the site
Might lock DB table, there is a ranged table work around
Command line search, defaults to require all
Stemmer - love vs loves
Last line - start indexing daemon
Wildcard search - prefix search,
Returns both ‘bacon’ docs
Add filters - limiting to certain values of attributes
Now we just get 1 result
Sphinx can be built into mysql as a table type, and queried via a where arg
Swish-e is an engine with a long pedigree, and a PHP extension.
Used by quite a few universities.
Doesn’t support multibyte charsets, which is a bit of a downside.
Great for combinations where you have a bunch of word docs or similar documents, and a website, and you want to search both.
In the conf we tell it where to look for files
FileFilters extract text from non-text formats doc/pdf
Can specify IndexDir multiple times different doc stores
Requires wv ware and xpdf
Apache Tika
Getting it through the web loses some of the advantages
Can plug into website no real control over
Mode is prog to call out to the spider script
Index file is different name
Here we search fs and www indexes and give combined results
Can use various filters to limit search to parts of HTML documents
Or filter on file system paths
Lucene, apache foundation search engine
Very succesful, but has ports instead of bindings
Native PHP port in Zend Framework, Zend Search Lucene
Lots of control, easy to add metadata/attributes
Lucene calls them fields: string keys, multiple value types
Text indexed and original stored - unstored not
Index compatible w/ Java lucene 2.3 - can index java, search PHP
The scores are only really interesting as a relative value
Spits out various fields such as title and body auto
Allows you to add other fields as required
Advantage of PHP - easy to hack at, add new doc types
HOWEVER - doesn’t scale to large collections so you may prefer to use one the Java based versions... and the easiest way is with Solr
Convenient for all the usual SOA reasons.
Solr is in use by CNET, digg, netflix and other high profile sites.
There is a PHP extension, or a PHP client API
Solr needs you to create a schema first, to define the fields of docs
Note the client commit down the bottom.
Until a document is committed
Hardly know you’re using a webservice
XML based response format means a more complex return struct
Solr is great for larger scale collections
Provides good admin functionality - enterprise friendly
High performance C based search engine.
There is a Solr like service called Flax, but we’ll look at the engine directly.
PHP SWIG based extension and low level API
Gives some cool features, and a lot of control
Creates database on FS, or can be accessed remote
Integration of stemmer - english here
We have an numeric indexed attribute, referred to as a ‘value’ here, for the title
We have more control -
STEM_SOME, don’t stem words that start with a capital letter (proper nouns)
Note the percentage score value - overtly relative, but can be thresholded if needed
We know where data coming from
How can we improve results
To use a classic example, from one of the early papers about google, if someone types ‘big blue’ into google, one of the top results is IBM.com.
But the page it points to doesn’t contain the phrase
Things link to it that do contain that phrase, and Google index against it.
Big win for things like images and videos, where there may be no text
Easy in PHP with the DOM parser
We could then add these to the index, as a new field on a document
ZSL has a built in html document type, but the getLinks function doesn’t include anchor text
This is a page from my blog
I know what’s important on this page - 1 to 3
Google has to guess, based on appearance
Green = boilerplate - don’t index
Index these zones as fields, and weight differently
We can set different ‘boost’ values on them
Boosts > 1 more important, < 1 less important
E.G. de-emphasise comments
In general - not tied to specific query
Page rank - but that wont work on small collection
Comments - “great post”, comment count
Inbound visitors
Retweets - Google uses a UserRank PR type calculation on follower counts
The default is 1
Adding one 100th for each comment
This of course could be tuned for individual circumstances
Now, look at ways to improve search user experience
With search - do what google et al do
Summaries or snippits show a selection of the page
With Sphinx here, we can pass the query and index name to the BuildExcerpts function to get highlighted contextual snippits
getTextFromDB is just a pretend function that would wrap retrieving the raw full text.
We’ve added a StoreDescription based on the body, for 1000 characters
This will appear in the result object as swishdescription.
We may want to index more, then choose the bit we display based on the presence of query words.
Can do on whole document as well
Easy to do in many engines
ZSL highlight matches - could use stored field or external
HighlightMatches without fragment will add HTML headers
Important to correct to known words from the index
Rather than default dictionary
We had an index based on PHP documentation
Have mistyped str_replace and strcmp
They featured in index, and had low edit distance from query
Some low quality results returned - where we might use threshold
Solr/Lucene has a similar plugin
This is an example from google news
E.G. file search, email, private messages may want others (sender, date, subject)
Can be expensive as SEs can’t do normal shortcuts
But normally straightforward
Shows categories and result counts
This is called faceted search, categories = facets
Document has many categories
Good for product based search
Solr was built with faceted search in mind for CNET reviews
If we’d been duplicating epicurious, each of the options on the left would have been a facet.
Get results plus enumeration of options in each facet + count
Find documents like this one
Good for search with many meanings - ‘creed’ (game, band, belief)
Example from a dissertation search engine
Xapian has built in, can do in Solr as well.
Top 40 most important terms extracted (can do more than one doc)
Using str_replace from index of phpdoc
Combine terms with ORs
MySQL FTI has blind query expansion, which gets more results based on the results retrieved - not as good, and hella slow!
Lots of data to process
Most engines have some sort of query cache built in
We’ll take a quick look at some different aspects of performance.
Adding data can be expensive to a large index.
Have two indexes
Merge
Lucene uses segments automatically
But slower update speed
Recombine segments, Merge deltas
Optimise and compress index
This can be an expensive operation though.
Try to keep index on local disk, not network
Replication tends not to give such a boost here, as you generally have too large an index which is too slow for single queries, rather than scale
Need to shard contents based on hash - something not searched for
Most systems have a way of working with remote backends, to give single search and sort point
Xap and Solr should handle into the millions on one server
100s of mil/billions = webscale - Challenges: Data size, rate of update
Nutch is a FOSS webscale SE/crawler created by Doug Cutting, of Lucene.
Also did hadoop: mapreduce, distributes files etc. (not being sued by google)
Used on thousands of nodes at yahoo, among others