arangodb AQL 查询以根据条件删除列表及其子项

arangodb AQL query to erase list and it's child depending of condition

我有一个包含日志列表的帐户集合

如果日志的“loggedAt”字段超过 5 天,我需要清除帐户“日志”列表中的每个日志,而不留下孤立日志或损坏“日志”列表的引用。

如何使用 AQL 或 arangosh 命令实现此目的?

像这样

FOR a IN account
 FOR l IN log

FILTER l._id IN a.logs
FILTER DATE_DIFF(l.loggedAt, DATE_NOW(), 'days', false) > 5

UPDATE a WITH { logs: REMOVE_VALUE( a.logs, l ) } IN account
REMOVE { _key: l._key } IN log

账户文件示例

_id:account/1085466856
_rev:_bIYHFNu---
_key:1085466856
{
  "_class": "com.app.Account",
  "logs": [
    "log/1085468455",
    "log/1085468456",
    "log/1085468457"
  ]
}

Account.class

@Data
@Document("account")
public class Account implements Serializable {

    private static final long serialVersionUID = -1615384653229054932L;

    @Id
    private String id;

    @Ref(lazy = false)
    private Collection<Log> logs;
}

日志文档示例

_id:log/1085468455
_rev:_bHhi2zu-_1
_key:1085468455
{
  "_class": "com.app.Log",
  "loggedAt": "2020-08-24T17:44:43.600Z"
}

Log.class

@Data
@Document("log")
public class Log implements Serializable {

    private static final long serialVersionUID = -1969696942832711654L;

    @Id
    private String id;

    private Date loggedAt;

}

您可以在 2 个 AQL 查询中执行此操作:

  1. 先删除日志:
LET fiveDaysAgo = DATE_SUBTRACT(DATE_NOW(), 5, 'days')
FOR rec IN log
  FILTER DATE_DIFF(rec.loggedAt, fiveDaysAgo, 'days') >= 0
  REMOVE rec IN log
  1. 接下来清理帐户:
FOR acc IN account
  LET validLogs = (
    FOR accLog IN acc.logs
      FOR rec IN log
        FILTER accLog == rec._id
        RETURN rec._id
  )
  FILTER LENGTH(acc.logs) != LENGTH(validLogs)
  UPDATE acc WITH {logs: validLogs} IN account

如果需要,可以将上述查询合并为一个查询:

LET fiveDaysAgo = DATE_SUBTRACT(DATE_NOW(), 5, 'days')
FOR acc IN account
  LET invalidLogs = (
    FOR accLog IN acc.logs
      FOR rec IN log
        FILTER accLog == rec._id
        FILTER DATE_DIFF(rec.loggedAt, fiveDaysAgo, 'days') >= 0
        REMOVE rec IN log
        RETURN OLD._id
  )
  FILTER LENGTH(invalidLogs) > 0
  UPDATE acc WITH {logs: OUTERSECTION(acc.logs, invalidLogs)} IN account

但是,如果您在 log 集合中有僵尸记录(与 account 记录没有任何关联的记录),上面的查询不会影响它们。