Couchbase查询以获取嵌套级别属性上的数据并创建索引

时间:2019-05-14 20:07:45

标签: sql couchbase n1ql spring-data-couchbase

如何在Java中的沙发床n1ql中查询嵌套的文档值?

文档值是一个对象(人),其属性类型为1(对象(地址)列表)。

地址对象具有多个属性,例如城市,邮政编码等。

如何编写查询以根据最低级别(例如城市或邮政编码)查找匹配记录

下面是一个示例文档结构,所有文档都具有相似的结构

{
    companyName: "ABC Inc",
    companyId: 123,
    persons: [
        {
          "name": "John Smith",
          "address": [
                {
                    "city": "London",
                    "zipCode": 1234,
                    "street": "23 Nottingham dr",
                    "contact": "123456678"
                },
                {
                    "city": "Los Angeles",
                    "zipCode": 67834,
                    "street": "345 Richmond dr",
                    "contact": "23456"
                }
            ]
        },
        {
          "name": "Peter Drink",
          "address": [
                {
                    "city": "Delhi",
                    "zipCode": 70046,
                    "street": "SP Road",
                    "contact": "9844334"
                },
                {
                    "city": "Los Angeles",
                    "zipCode": 67834,
                    "street": "433 Ku St",
                    "contact": "12345677"
                }
            ]
        }
    ]
}

输入条件是zipCode,我需要能够基于zipCode获取所有文档中的所有person对象

输入:邮政编码67834 预期输出:

[
    {
        "city": "Los Angeles",
        "zipCode": 67834,
        "street": "433 Ku St",
        "contact": "12345677"
    },
    {
        "city": "Los Angeles",
        "zipCode": 67834,
        "street": "345 Richmond dr",
        "contact": "23456"
    }
]

1 个答案:

答案 0 :(得分:2)

您需要先UNNEST数组(这会使数组的每个文档都自连接父文档)

SELECT a.*
FROM default AS d
UNNEST d.persons AS p
UNNEST p.address AS a
WHERE a.zipCode = 67834 AND .....;


CREATE INDEX ix1 ON default(DISTINCT ARRAY (DISTINCT ARRAY a.zipCode FOR a IN p.address END) FOR p IN persons END);

索引中的绑定变量名称必须与Unnest别名匹配,以选择索引。