How to reverse index on junction/jump table?

I have a database with the following structure:

+----------------+       +----------------+       +----------------+
|      foo       |       |    foo_bar     |       |      bar       |
+-------+--------+       +-------+--------+       +-------+--------+
|  _id  |   ID   |---┐   |  _id  |   ID   |   ┌---|  _id  |   ID   |
|  date |  Time  |   └-->| fooID |   ID   |   |   | field | string |
+-------+--------+       | barID |   ID   |<--┘   +-------+--------+
                         | field | string |
                         +-------+--------+

There’s an index on foo_bar to allow retrieval of junction documents based on barID and field:

{
  name: "foo_bar_by_field_and_bar",
  source: Collection("foo_bar"),
  terms: [{ field: ["data", "field"] }, { field: ["data", "barID"] }],
  values: [{ field: ["ref"] }]
}

This is coupled with a function to retrieve foo:

Query(
  Lambda(
    [...],
    Map(
      Paginate(Match(Index("foo_bar_by_field_and_bar"), [..., ...])),
      Lambda(
        ["ref"],
        Get(
          Ref(
            Collection("foo"),
            Select(["data", "fooID"], Get(Var("ref")))
          )
        )
      )
    )
  )
)

This works however I’d like to retrieve foos reverse ordered by date. What’s the best way to do this?

Someone please correct me if I’m wrong, but this calls for 2 things

  1. Another index with the correct ordering:
{
    name: "foo_reverse_date",
    source: Collection("foo"),
    terms: [{ field: ["ref"]}],
    values: [
      { field: ["data", "date"], reverse: true },
      { field: ["ref"] },
      /* whatever else you need */
    ]
}
  1. then you can join the indexes together (taken from this page)
Query(
  Lambda(
    [...],
    Map(
      Paginate(
        Join(
          Match(Index("foo_bar_by_field_and_bar"), [..., ...])),
          Index("foo_reverse_date),
        ),
      )
// Depending on what's in the second index, you may not even need this Map
      Lambda(
        ["date", "ref", ...],
        Get(...)
      )
    )
  )
)
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.