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.

egghead
egghead
~ 30 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today