【问题标题】:Returning unknown JSON in a query在查询中返回未知 JSON
【发布时间】:2020-05-26 04:13:49
【问题描述】:

这是我的场景。我在 Cosmos DB 中有数据,我想返回 c.this、c.that 等作为 Azure 认知搜索的索引器。我要返回的一个字段是未知结构的 JSON。我所知道的一件事是它是平的。但是,据我了解,需要知道索引器的返回值。如何在 SELECT 中使用 SQL,返回平面对象中的所有 JSON 元素?这是我要查询的示例值:

{
"BusinessKey": "SomeKey",
    "Source": "flat",
    "id": "SomeId",
    "attributes": {
        "Source": "flat",
        "Element": "element",
        "SomeOtherElement": "someOtherElement"
    }
}

所以我希望我的选择可能是这样的:

SELECT 
    c.BusinessKey,
    c.Source,
    c.id,
    -- SOMETHING HERE TO LIST OUT ALL ATTRIBUTES IN THE JSON AS FIELDS IN THE RESULT

我希望结果是:

{
    "BusinessKey": "SomeKey",
    "Source": "flat",
    "id": "SomeId",
    "attributes": [{"Source":"flat"},{"Element":"element"},{"SomeOtherElement":"someotherelement"}]    
}

目前我们在 c.attributes 上调用 ToString,它是未知结构的 JSON,但它正在添加所有转义字符。当我们想要搜索索引时,我们必须添加所有这些转义字符,它变得非常不守规矩。

有没有办法使用 SQL 来做到这一点?

感谢您的帮助!

【问题讨论】:

  • 另一种可能的方法是返回一个键/值对数组。目前,该查询用于 Azure 认知搜索的索引器。当前使用的方法是使用 ToString(c.attributes) 但问题是它返回一个带有转义字符的字符串。在发出搜索时,这对于搜索参数并不适用。我们最终得到了 2 个级别的转义。

标签: sql json azure-cosmosdb azure-cognitive-search


【解决方案1】:

您可以在 cosmos db sql 中使用 UDF

UDF 代码:

function userDefinedFunction(object){
    var returnArray = [];
    for (var key in object) {  
        var map = {};
        map[key] = object[key];
        returnArray.push(map);
    }
    return returnArray;
}

Sql:

SELECT 
    c.BusinessKey,
    c.Source,
    c.id,
    udf.test(c.attributes) as attributes
    from c

输出:

【讨论】:

  • 感谢杰伊的回复。我已经实现了这个,它就像一个魅力。谢谢你的链接。
猜你喜欢
  • 2015-12-24
  • 2019-04-05
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2018-07-06
相关资源
最近更新 更多