How to get first and last records in AQL ArangoDB query

I need help querying AQL ArangoDB. I have a transaction data collection ( EventTran) that logs update data in its parent table ( Event). EventTranattributes include a timestamplink to the parent _id_event. Im trying to work out a request to return an array of only the first and last (through timestamp) EventTrandocuments for the specified one id_event. Here is an example:

FOR event IN EventTran
    FILTER event._id_event == "Event/167697"
    SORT event.timestamp DESC
    RETURN event

May return:

[
  {
    "_key": "214092",
    "_id": "EventTran/214092",
    "_id_event": "Event/167697",
    "timestamp": 1511202637
  },
  {
    "_key": "213958",
    "_id": "EventTran/213958",
    "_id_event": "Event/167697",
    "timestamp": 1511202542
  },
  {
    "_key": "191809",
    "_id": "EventTran/191809",
    "_id_event": "Event/167697",
    "timestamp": 1511118705
  },
  {
    "_key": "167701",
    "_id": "EventTran/167701",
    "_id_event": "Event/167697",
    "timestamp": 1510965562
  }
]

I need a query that will return an array with only the first and last elements, i.e. the very first log entry and the very last log entry:

[
  {
    "_key": "214092",
    "_id": "EventTran/214092",
    "_id_event": "Event/167697",
    "timestamp": 1511202637
  },
  {
    "_key": "167701",
    "_id": "EventTran/167701",
    "_id_event": "Event/167697",
    "timestamp": 1510965562
  }
]
+4
source share
2 answers

There are two possible solutions:

1) , / :

RETURN [
  (FOR event IN EventTran  
     FILTER event._id_event == "Event/167697"
     SORT event.timestamp DESC
     LIMIT 1
     RETURN event
  )[0],
  (FOR event IN EventTran  
     FILTER event._id_event == "Event/167697"
     SORT event.timestamp ASC
     LIMIT 1
     RETURN event
  )[0]
]

, DESC, ASC. , . _id_event , null . , [null, null].

2) :

LET results = (
  FOR event IN EventTran  
     FILTER event._id_event == "Event/167697"
     SORT event.timestamp ASC
     RETURN event
)
RETURN [
  results[0],
  results[-1]
]

, ( ?), .

+2

, , SORT, , , , .

: min max, , .

LET mnmx = (
  FOR x in EventTran
  FILTER event._id_event == "Event/167697"
  COLLECT AGGREGATE mn = MIN(x.timestamp), mx = MAX(x.timestamp)
  RETURN {mn,mx} )

LET mn = mnmx.mn
LET mx = mnmx.mx

LET least = (
  FOR x in EventTran
  FILTER x.timestamp == mn
  COLLECT y=x INTO minimal
  RETURN minimal[0] )

LET greatest = (
  FOR x in EventTran
  FILTER x.timestamp == mx
  COLLECT y=x INTO maximal
  RETURN maximal[0] )

RETURN {least, greatest}

{ "": , "": }, least greatest - .

+4

Source: https://habr.com/ru/post/1689588/


All Articles