1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Reducing the number of read ops in a query using indexes

    Chris BiscardiChris Biscardi
    faunadbFaunaDB

    The FaunaDB hosted product pricing charges you based on read ops (in addition to write ops, storage, and data transfer). This can make it important to reduce the number of read ops in a heavily used query to stay within your expected limits on a given day.

    Map(
      Paginate(Match(Index("all_customers"))),
      Lambda("X", Get(Var("X")))
    )
    Paginate(Match(Index("all_customers_with_fields"))),

    The number of read ops can be found by inspecting the headers for a given query.

    X-Read-Ops: 4
    Code

    Code

    Become a Member to view code

    You must be a 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
    Discuss

    Discuss

    Transcript

    Transcript

    Chris Biscardi: On the left, we have an FQL query. We match on the index of all customers. We paginate that match. We map over the result set. We're getting each of the refs. If we run this query, we can see that we actually get a full list of all the documents, including all of the fields.

    If we take a look at the headers for the request that we just sent to the database in the Chrome pane, we can see that one of the headers is X-Read-Ops. X-Read-Ops tells us how many read ops our query made. In this case, we made four. Since we only have three records, that's not a huge deal.

    Let's say we had many, many, many records. To reduce the number of read ops, we can use an index. Here in our list of indexes, we can see that we have all customers and a couple of other indexes. We'll create a new index.

    Since we're querying all customers, we'll put it on the customers collection. We'll name our index, and we'll leave terms empty.

    For values, we'll include the firstName, lastName, and telephone. Note that for each field, our value was auto-completed to data.firstname. We can see that our index, all_customers_with_fields, includes all of our documents -- the firstName, the lastName, and the telephone.

    Let's go back to our Shell. Remember that our last query required a read op for every Get, and a read op for the index. If we just run the Paginate on the Match, we can see that we get a number of Refs. If we switch the index to use our new index, all_customers_with_fields, we can see that we got all of the data that we looked for in the index, including the first name, the last name, and the telephone number.

    If we check the headers on our request, we can see that our read ops are now one. We have successfully reduced the number of read ops our query is using by taking advantage of an index.