2

我以以下格式将 JSON 数据存储在 ArangoDB 集合中。

{ 
  "data": {
    "1":   [ {"db_name": "DSP"}, {"rel": "2"} ], 
    "2":   [ {"rel_name": "DataSource"}, {"tuple": "201"}, {"tuple": "202"}, {"tuple": "203"} ],
    "201": [ {"src_id": "Pos201510070"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151007"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "postgres"}, {"port": "None"} ],
    "202": [ {"src_id": "pos201510060"}, {"src_name": "Postgres"},{"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "DSP"}, {"port": "5432"} ],
    "203": [ {"src_id": "pos201510060"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"},{"src_type": "Structured"},{"db_name": "maindb"},{"port": "5432"} ]
  }
}

我是 ArangoDB 的新手。我不知道从 ArangoDB 存储和查询数据。在我的数据中没有任何预定义的键,并且数据会随时间填充。我的数据就像一个半结构化的数据,没有任何固定数量的属性,并且由于它的迭代列表结构而有点复杂。

首先,任何人都可以建议我在 ArangoDB 中存储上述格式的最佳方式。

其次,我想通过以下方式查询这些数据:通过指定任何键(事先不知道,通过在运行时指定),或通过指定键和值对Key1 == value1的组合,例如,或使用 AND 或 OR 逻辑的组合运营商喜欢Key1 == value1 AND Key2 == value2 OR Key3== value3.

那么,我们如何迭代上述数据呢?

4

1 回答 1

1

如果您真的想将数据存储在这样的结构中,没有任何预定义的属性名称,您仍然可以通过即时将数据转换为规范化结构来迭代数据。

以下 AQL 查询为每个文档创建一个键/值对的平面列表:

FOR doc IN collection 
  LET attributes = ATTRIBUTES(doc.data) 
  FOR attribute IN attributes 
    FOR arrayItem IN doc.data[attribute] 
      LET key = ATTRIBUTES(arrayItem)[0] 
      LET value = arrayItem[key] 
      RETURN { _key: doc._key key: key, value: value }

此查询的结果将是这样的:

[ 
  { 
    "_key" : "864582648369", 
    "key" : "password", 
    "value" : "root" 
  }, 
  { 
    "_key" : "864582648369", 
    "key" : "db_name", 
    "value" : "postgres" 
  }, 
  { 
    "_key" : "864582648369", 
    "key" : "port", 
    "value" : "None" 
  }, 
  ...
]

现在,您可以通过添加选择的过滤条件轻松应用过滤:

FOR doc IN collection 
  LET attributes = ATTRIBUTES(doc.data) 
  FOR attribute IN attributes 
    FOR arrayItem IN doc.data[attribute] 
      LET key = ATTRIBUTES(arrayItem)[0] 
      LET value = arrayItem[key] 
      FILTER key == 'password' || key == 'port' || (key == 'db_name' && value == 'postgres') 
      RETURN { _key: doc._key, key: key, value: value }

请注意,当数据结构发生变化(更多/更少的嵌套级别)时,上述方法将不再起作用。该查询假定文档具有问题中所示的结构。

于 2015-10-27T15:51:29.410 回答