How to put together this query?
Closed this issue · 5 comments
This query works great and does what I want from the management UI:
r.db("test").table("mailboxes").get("a90b8e49-1564-42b5-a434-882cf84ae3d2").getField("Inbox.Messages").update({"Inbox.Messages": r.row("Inbox.Messages").insertAt(0, {"Text" : "More"})})
It selects particular mailbox, selects inbox messages (which is an array), inserts new message into that array and finally updates the document. I was able to get as far as retrieving the array of existing messages
table("mailboxes") |> get("a90b8e49-1564-42b5-a434-882cf84ae3d2") |> get_field("Inbox.Messages")
but how can I perform an update? I could probably extract an array into a variable, add new message to it and then call an update with modified array but that seems inefficient since it would involve one more query to the DB than necessary. Any pointers would be appreciated.
I haven't used the driver in a while, but try this:
table("mailboxes")
|> get("a90b8e49-1564-42b5-a434-882cf84ae3d2")
|> get_field("Inbox.Messages")
|> update(lambda fn(row) ->
new_value = row |> insert_at(0, %{text: "more"})
%{"Inbox.Messages": new_value}
end)
@sikanhe I'm getting type mismatch errors like "Expected type SELECTION but found DATUM" but thanks for your help. I'll try to play around with this and try to figure out what's going on.
@sikanhe There were two problems with my original query. First, get_field
should have been removed as this returned array of messages and that's not what we want. We want the document itself, not the array. I was playing with that query after I got it to work and copied get_field
accidentally.
Second, row
returns actual row or object
(as I saw in the error) and what we want is specific column in that row
so row["Inbox.Messages"]
is what we want. Final version, which works great is:
table("mailboxes") |> get("a90b8e49-1564-42b5-a434-882cf84ae3d2")|> update(lambda fn(row) -> new_value = row["Inbox.Messages"] |> insert_at(0, %{text: "some text"}) %{"Inbox.Messages": new_value} end) |> DB.run
Great work, thanks for your help!
@Sotorin ah yea, i believe row["field"] gets translated into row |> get_field in lambda macro automatically. So it was extraneous. Glad it worked!
row[:field]
is row |> bracket(:field)