如何仅使用不同的值对JSON文档进行分组?

时间:2017-09-19 10:00:02

标签: json xquery marklogic marklogic-8

我有一些属于同一集合(alpha)的JSON文件:

Aplha_a.json

{
  "date": "24-july-2017",
  "ID": "001", 
  "data": "a",
  "reg_date": "24-july-2017"
}

Aplha_b.json

{
  "date": "24-july-2017",
  "ID": "001", 
  "data": "b", 
  "reg_date": "24-july-2017"
}

Aplha_c.json

{
  "date": "24-july-2017",
  "ID": "001", 
  "data": "c", 
  "reg_date": "24-july-2017" 
}

以上json文件是从集合" alpha"中提取的。使用由以下提到的查询完成的ID:

cts:search(collection("alpha"),
           cts:and-query((
                          cts:json-property-range-query("ID", "=", "001"),
                          cts:json-property-value-query("reg_date", "24-july-2017")
           ))
)

现在,需要将这些不同的json文件分组为一个alpha_family文档,仅返回distinct-nodes。输出应如下:

{Alpha_family: {
  "date": "24-july-2017"
  "ID": "001"
  "data": "a" 
  "data": "b" 
  "data": "c"
  "reg_date": "24-july-2017"
}

任何人都可以帮助实现这一目标吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

如何迭代文档,并在旅途中聚合json对象中的不同值。类似的东西:

xdmp:document-insert("/Aplha_a.json", xdmp:unquote('
  {
    "date": "24-july-2017",
    "ID": "001", 
    "data": "a",
    "reg_date": "24-july-2017"
  }
'), xdmp:default-permissions(), "alpha"),

xdmp:document-insert("/Aplha_b.json", xdmp:unquote('
  {
    "date": "24-july-2017",
    "ID": "001", 
    "data": "b", 
    "reg_date": "24-july-2017"
  }
'), xdmp:default-permissions(), "alpha"),

xdmp:document-insert("/Aplha_c.json", xdmp:unquote('
  {
    "date": "24-july-2017",
    "ID": "001", 
    "data": "c", 
    "reg_date": "24-july-2017" 
  }
'), xdmp:default-permissions(), "alpha")

;

let $json := json:object()
let $_ :=

  for $doc in cts:search(collection("alpha"),
    cts:and-query((
      cts:json-property-value-query("ID", "001"),
      cts:json-property-value-query("reg_date", "24-july-2017")
    ))
  )
  for $prop in $doc//text()
  let $exists := map:get($json, name($prop))
  return
    map:put($json, name($prop), distinct-values(($exists, $prop)))

return $json

我不太确定用例,这种方法会在较大的数据集上严重扩展。但是如果搜索总是只返回少量文档,那对你来说可能已经足够了......

HTH!