Can `values` on `indexes` help you reduce read ops?

Given

Index

q.CreateIndex({
  name: 'tokensByUserId',
  source: q.Collection('userTokens'),
  terms: [{ field: ['data', 'userId'] }],
  values: [
    { field: ['data', 'organizationId'] },
    { field: ['ref'] }
  ]
});

Question

q.Map(
  q.Paginate(q.Match(q.Index("tokensByUserId"), "0123456789")),
  q.Lambda(
    ["_", "ref"],
    q.Let(
      {
        result: q.Select(["data", q.Get(q.Var("ref"))]),
        organization: q.Select(
          ["data"],
          q.Get(q.Select(["organizationId"], q.Var("result")))
        ),
      },
      q.Var("organization")
    )
  )
);
q.Map(
  q.Paginate(q.Match(q.Index("tokensByUserId"), "0123456789")),
  q.Lambda(
    ["organizationId", "ref"],
    q.Select(
      ["data"],
      q.Get(q.Ref(q.Collection("organizations"), q.Var("organizationId")))
    )
  )
);

On the first query, Let’s pretend that the organizationId is not returned on the values of the index, so I had to Get the result and then Select the organizationId.

On the second query, I did not have to do Get twice, because I already have the organizationId which was returned by the Index.

If there’s only one document currently on the database (on all tables), how many reads would be incurred for each of the queries?

I’m trying to figure out if values on index can help me reduce read ops.

I edited it for more clarity, sorry.

If you run a query in the shell, it will tell you how many resources the query took. You can find those statistics by mouse-overing the little info-mark icon to the left of the line-number column.

(this is just a random query that I did, not your query)

I also want to get feedback actually…

Hey @aprilmintacpineda

Yes the second query is better, by reducing the number of read by 2. (Paginate is 1 read. Get is 1 read, per each item).
Since you removed one Get from the query inside the Map, you reduce the read ops !

You would have more information here : Billing | Fauna Documentation

Also you could use Join to help reduce read ops, since you can go deep with indexes and only use Get at the end :slight_smile:

q.Map(
  q.Paginate(
     q.Join(
        q.Match(q.Index("tokensByUserId"), "0123456789"), // return ref instead of [organizationId, ref]
        q.Index("organizationByToken") // index that accept a token ref argument, returns organization ref
     )
  ),
  x => Get(x)
);

Which would have the same read ops as your second query.
In this case your way is working the same but for some queries, using Join really helps reducing read ops :slight_smile:

3 Likes