使用Gremlin将属性和元属性提取到类似JSON的结构中

时间:2019-10-12 13:11:13

标签: gremlin tinkerpop

我的客户顶点具有4个属性和2个元属性(每个属性都包含一个列表)。任务是以JSON结构返回客户数据。我能够提出以下查询:

g.V('customerId')
    .project('customer', 'addresses', 'accounts')
    .by(properties().not(hasLabel('addresses', 'accounts')).group().by(key()).by(value()))
    .by(properties('addresses').valueMap().fold())
    .by(properties('accounts').valueMap().fold())

产生结果

{
  "customer": {
    "firstName": "Carl",
    "middleName": "Friedrich",
    "lastName": "Gauss",
    "age": 77
  },
  "addresses": [
    {
      "streetName": "View",
      "streetNumber": "43",
    },
    {
      "streetName": "Market",
      "streetNumber": "11",
    }
  ],
  "accounts": [
    {
      "accountNumber": "1234"
    },
    {
      "accountNumber": "4321"
    }
  ]
}

我真正需要的是这样的结构:

{
  "firstName": "Carl",
  "middleName": "Friedrich",
  "lastName": "Gauss",
  "age": 77,
  "addresses": [
    {
      "streetName": "View",
      "streetNumber": "43",
    },
    {
      "streetName": "Market",
      "streetNumber": "11",
    }
  ],
  "accounts": [
    {
      "accountNumber": "1234"
    },
    {
      "accountNumber": "4321"
    }
  ]
}

我能得到的最接近的是这个查询:

g.V('customerId')
    .properties()
    .group()
    .by(key)
    .by(choose(hasLabel('addresses','accounts'), valueMap().fold(), value()))

不幸的是,这将地址和帐户内容分组,因此我实际上只能看到最后一个地址/帐户:

{
  "firstName": "Carl",
  "middleName": "Friedrich",
  "lastName": "Gauss",
  "age": 77,
  "addresses": [
    {
      "streetName": "Market",
      "streetNumber": "11",
    }
  ],
  "accounts": [
    {
      "accountNumber": "4321"
    }
  ]
}

是否可以列出所有元属性元素?

1 个答案:

答案 0 :(得分:3)

对于上面的示例,

如果您添加fold().unfold(),它将考虑所有属性:

g.V('c81e3753-1eaa-453b-85bc-818174de70c1')
    .properties()
    .group()
    .by(key)
    .by(fold().unfold().choose(hasLabel('addresses','accounts'), value().fold(), value()))