Charalarg
Charalarg

Reputation: 75

Fetch records by multiple indexes

What is the most efficient way to get all records by two indexes? Lets say we have two secondary indexes, end_block_num and public_key and the values bellow:

  1. end_block_num = 1000
  2. public_key = "AABBCC"

I have already tried two different queries (i think the second one is more efficient) but is this the optimal way to do that??

agents = (
    r.table("agents")
    .filter(
        reduce(
            operator.or_,
            [r.row["end_block_num"].eq(1000), r.row["public_ket"].eq("AABBCC")],
            False,
        )
    )
    .run(conn)
)

agents = (
    r.table("agents")
    .get_all(1000, index="end_block_num")
    .coerce_to("array")
    .set_union(r.table("agents").get_all("AABBCC", index="public_key").coerce_to("array"))
    .run(conn)
)

Upvotes: 0

Views: 65

Answers (1)

Charalarg
Charalarg

Reputation: 75

I came up with the multi index solution:

r.db(name).table("agents").index_create(
     "my_multi_index",
     lambda agent: [
         agent["public_key"], agent["end_block_num"],
     ],
     multi=True,
 ).run(conn)

Execution:

agents = (
     r.table("agents")
    .get_all(["AABBCC", 1000], index="my_multi_index")
    .run(conn)
)

Upvotes: 0

Related Questions