vovahost
vovahost

Reputation: 36049

How to return the results of a bulk insert?

How do I return the array of newly inserted documents? I want to perform a bulk insert from Java.

INSERT {
  text: @text0,
  createdAt: @createdAt0
} IN messages

LET result0 = { id: NEW._key, text: NEW.text, createdAt: NEW.createdAt }

INSERT {
  text: @text1,
  createdAt: @createdAt1
} IN messages

LET result1 = { id: NEW._key, text: NEW.text, createdAt: NEW.createdAt }

RETURN [result0, result1]

Is there a better way to collect the results from each insert, other than defining a new variable to keep the results in it?

Upvotes: 0

Views: 368

Answers (1)

David Thomas
David Thomas

Reputation: 2349

This query should do what you want.

FOR d IN [
    {text:@text0, createdAt: @createdAt0}, {text:@text1, createdAt: @createdAt1}
]
INSERT d INTO abc
RETURN {
    id: NEW._id,
    text: d.text,
    createdAt: d.createdAt
}

An example response from the AQL is:

[
  {
    "id": "abc/21971344",
    "text": "apple",
    "createdAt": 1584107091
  },
  {
    "id": "abc/21971345",
    "text": "banana",
    "createdAt": 1584108473
  }
]

So long as the end user doesn't craft the AQL it should be fine, especially since you're using parameters.

If you ever used the product beyond testing, I'd definitely recommend looking at Foxx, as it gives you a layer of abstraction, hosted (relatively) within the database, which at the least stops consumers from having to execute AQL queries at all, rather they just communicate via REST endpoints.

PS. This query format also works:

FOR d IN @messages
INSERT d INTO abc
RETURN {
    id: NEW._id,
    text: d.text,
    createdAt: d.createdAt
}

Where @messages is

"messages": [
    {
        "text": "apple",
        "createdAt": 1584107091
    },
    {
        "text": "banana",
        "createdAt": 1584108473
    }
]

Upvotes: 1

Related Questions