Search more efficiently with tries using Natural

Hannah Davis
InstructorHannah Davis
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

Tries are a data structure that provide an efficient way to search for the existence of a word or phrase in a body of text, or to search by prefix.

[00:00] First, import the natural library. To make a new trie structure, the syntax is new natural.Trie. By default, tries are case sensitive. If you don't want that to be the case, you can pass in false here. But for this example, we do want it to be case sensitive.

[00:23] Next, we need some data. To create the trie structure, we need to add all of these strings to the trie by saying "trie.addString." One of the simplest things we can do with trie is look to see if a string is contained in the trie.

[00:47] To do that, we say trie.contains a string. We can see that that's true. We can also words starting with a specific prefix by saying trie.keysWithPrefix, and then the prefix. If we search for "cr," we'll get crane, creeper, crossbill and crow back.

[01:18] We can also see if any of the words in trie match a prefix of a word by saying trie.findMatchesOnPath, that's the search path they're referring to. We'll say, "cuckoohead." We can see that cuckoo matches the prefix.