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

Couchbase Query to get data on a nested level property & Create index

如何在 java 的 couchbase 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"
                }
            ]
        }
    ]
}

输入条件是邮政编码,我需要能够根据邮政编码获取所有文档中的所有人员对象

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

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

您需要先 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 别名匹配才能选择索引。