如何在n1ql Couchbase中创建具有所有组合的对的数组

时间:2018-09-13 07:59:03

标签: couchbase

我在Couchbase文档中有一个嵌套的对象数组:

doc1:{

arr:[v1, v2, v3, v4]// v1, v2, v3 are objects

}

预期结果

arr[
{v1, v2}, 
{v1, v3}, 
{v1, v4},
{v2, v3},
{v2, v4},
{v3, v4}
]

2 个答案:

答案 0 :(得分:1)

假设您的意思是arr应该是一个数组数组,应该这样做:

    JsonDocument doc = bucket.get(docId);
    JsonArray arr = doc.content().getArray("arr");
    JsonArray out = JsonArray.create();

    for(int i = 0; i < arr.size() - 1; i ++) {
        for(int j = i; j < arr.size(); j ++) {
            JsonArray subArray = JsonArray.create()
                    .add(out.get(i))
                    .add(out.get(j));
            out.add(subArray);
        }
    }

    doc.content().put("arr", out);
    bucket.replace(doc);

答案 1 :(得分:1)

更改了预期的输出以反映有效的JSON。即{“ one”:v1,“ two”:v2}

SELECT  ARRAY_FLATTEN((ARRAY (ARRAY {"one":v1, "two":v2} FOR v2 IN d.arr[pos+1:] WHEN  v2 IS VALUED END) FOR pos:v1 IN d.arr END),2)
FROM default AS d ;

SELECT RAW ARRAY_FLATTEN((ARRAY (ARRAY {"one":v1, "two":v2} FOR v2 IN arr[pos+1:] WHEN  v2 IS VALUED END) FOR pos:v1 IN arr END),2)
LET arr = [{"x":"a1"},{"x":"a2"},{"x":"a3"},{"x":"a4"}];

SELECT ARRAY_FLATTEN((ARRAY (ARRAY [v1, v2] FOR v2 IN arr[pos+1:] WHEN  v2 IS VALUED END) FOR pos:v1 IN arr END),1) AS b
LET arr = ["one","two","three","four"];