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

yxyvkwin  于 2022-12-09  发布在  Go
关注(0)|答案(1)|浏览(154)

我有一个包含日志列表的帐户集合
如果日志的“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;

}
vc9ivgsu

vc9ivgsu1#

您可以在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记录没有任何关联的记录),则上面的查询将保持不变。

相关问题