Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Search more efficiently with tries using Natural


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

    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.