问题描述
我的数据集有两个数组,这些数组包含具有两个属性(日期和值)的对象。对于每个数组,我需要获取具有最新日期的对象。我正在尝试从索引执行此操作,并正在探索使用Optic API进行查询。
我的视图有三列:“ statusType”,指示值来自哪个数组; “ statusDate”;和“价值”。通过以下查询,我可以获取每种类型的最新日期,但是我看不到如何获取与其关联的值。
const op = require('/MarkLogic/optic');
op.fromView('Parent','info')
.where(cts.documentQuery('/test/doc1.json'))
.groupBy([op.col('statusType')],[op.max('maxdate',op.col('statusDate'))])
.result()
产生:
{
"statusType": "subtype1","maxdate": "2020-09-29T16:33:18.6301434-04:00"
},{
"statusType": "subtype2","maxdate": "2020-08-29T16:33:18.6301434-04:00"
}
如果将value
添加到groupBy
的第一个参数中,则会得到类型和值(带有maxdate)的所有不同组合。如果将value
添加到groupBy
的第二个参数中,则会得到最后一个值,而不是与maxdate
关联的值。
预期输出:
{
"statusType": "subtype1","value": "valueB","value": "valueC","maxdate": "2020-08-29T16:33:18.6301434-04:00"
}
样本数据:
'use strict';
declareUpdate();
xdmp.documentInsert(
'/test/doc1.json',{
"parent": {
"subtype1": [
{
"value": "valueA","date": "2020-07-29T16:33:18.6301434-04:00"
},{
"value": "valueB","date": "2020-09-29T16:33:18.6301434-04:00"
}
],"subtype2": [
{
"value": "valueC","date": "2020-08-29T16:33:18.6301434-04:00"
},{
"value": "valueD","date": "2020-07-29T16:33:18.6301434-04:00"
}
]
}
}
)
模板1:
declareUpdate();
const tde = require("/MarkLogic/tde.xqy");
let template =
xdmp.toJSON(
{
"template": {
"context": "/parent/subtype1","rows": [
{
"schemaName": "Parent","viewName": "info","columns": [
{
"name": "statusType","scalarType": "string","val": "'subtype1'"
},{
"name": "value","val": "value"
},{
"name": "statusDate","scalarType": "dateTime","val": "date"
}
]
}
]
}
}
);
// comment and uncomment based on which action you want to take
let action =
//'validate'
//'extract'
'insert'
;
if (action === 'validate') {
tde.validate([template]);
} else if (action === 'extract') {
tde.nodeDataExtract([cts.doc( "/test/doc1.json" )],[template])
} else if (action === 'insert') {
tde.templateInsert("/tde/subtype1.json",template,xdmp.defaultPermissions(),["TDE"])
}
模板2:
declareUpdate();
const tde = require("/MarkLogic/tde.xqy");
let template =
xdmp.toJSON(
{
"template": {
"context": "/parent/subtype2","val": "'subtype2'"
},[template])
} else if (action === 'insert') {
tde.templateInsert("/tde/subtype2.json",["TDE"])
}
解决方法
敬酒,卡塞尔先生:
如果我正确理解了需求,那么我知道的唯一方法是将groupBy()
结果与原始视图结合起来:
-
groupBy()
发出带有分组键和max()聚合值的行,并在fromView()
访问器上传递别名/限定符名称。 - 通过使用相同的视图进行联接(使用maxInfo.statusType = info.statusType和maxInfo.maxdate = info.statusDate上的联接键)来获得max行的其余列。
groupBy()
操作对聚合参数中的任何列进行采样。
希望有帮助,