We have a database of television scripts and we’d like to search it, getting results as we type.
We often remember words or snippets of dialogue but can’t remember exactly what was said or what episode it was said in: “What was the episode where George goes against his instincts and walks up to the girl at the diner and tells her he’s unemployed?”
With this tool you’d type “George unemployed” and the result with context (and possibly other hits) would pop up:
EPISODE: "The Opposite"
George : Excuse me, I couldn't help but notice that you were looking in my direction.
Victoria : Oh, yes I was, you just ordered the same exact lunch as me.
( G takes a deep breath )
George : My name is George. I'm unemployed and I live with my parents.
Victoria : I'm Victoria. Hi.
My question is about the best way to design a data structure to implement this kind of search?
My idea so far is store a lookup table in an in-memory data store such as redis. To create the table, first I’d give each script (episode) an id, and then i’d parse the script into lines based on the person speaking. So a particular piece of dialogue could be located with an episode id paired with a line id.
Next I would process each line, creating a data structure indexed by all words appearing in any script, and storing the episode/line location of every instance the word was used.
apple -> [
{ scriptid: 9, lines: [11,99] },
{ scriptid: 21, lines: [103,211,214] }
]
orange -> [
{ scriptid: 2, lines: [101] }
]
We could pair this data structure with a simple scoring algorithm, so that when a user searched for multiple words, we’d only show matches where both words occured in the same script, and give higher rank to locations where the words appear closer to one another.
There are other details that, ideally, would be accounted for, such as matching plurals and mispelled words.
Is this a reasonable approach? How could it be improved? What other details should I consider?
3
I would use a search engine, e.g. ElasticSearch, which already has everything you need. It takes care data structure, storage, etc. so you can focus on what filtering the search and returning the results, i.e. drop some words (propositions, etc.), fix misspelled words, give boost to some results, etc. Each of those problem would need a separate discussion on how to solve it. But the default configuration should be enough to get you started.
What type of database are you using? and what programming language?
I personally, using a PHP and MySQL setup, would contain the scripts as an array by first splitting them and inserting into the table.
I would then split the user’s search into an array too by spaces.
Then, I would use the query
SELECT *
FROM 'table'
WHERE 'column'.contains('array[0], array[1]')
Hopefully this makes sense and provides a viable answer, and if not I hope it gives you a ‘starting point’ as such 🙂
2