Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateIndex with Binding Objects

Tags:

faunadb

I have a collection that includes a field of type Time. I need to be able to query this collection by year, or month-year combination.

I have tried using the index creation tool on the web site itself, using things like Year(data.expDate) and Month(data.expDate) in the Terms, but this did not work.

Here is the schema for my collection:

type Expense {
  _id: ID!
  expAmount: Float!
  expDate: Time!
  expCategory: Category!
  _ts: Long!
}

I need to be able to list the expenses for a particular year, or a particular month-year, without having to create separate month and year fields in my collection.

like image 488
LesC Avatar asked Oct 17 '19 23:10

LesC


1 Answers

The solution to this was creating an index based on computed fields, which are then bound as terms, something like:

CreateIndex({
  name: "expByYearMonth",
  source: [{
    class: Collection("Expense"),
    fields: {
      year:Query(Lambda("doc",Year(Select(["data","expDate"],Var("doc"))))),
      month:Query(Lambda("doc",Month(Select(["data","expDate"],Var("doc")))))
    }
  }],
  terms: [{ binding: "year" }, { binding: "month" }]
})

I was then able to search by year, month and get the results with something like:

Paginate( Match(Index('expByYearMonth'), [2019, 10]) )

(With special thanks to @colllin and the other helpful folks on the Fauna Slack channel, for pointing me in the right direction.)

like image 113
LesC Avatar answered Sep 30 '22 15:09

LesC